mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Merge pull request #9288 from dotCooCoo/feat/scripts-doc-defaults
Scripts: Document default fill and stroke members and scaleFactor
This commit is contained in:
21 files changed
+4600
-68
No files matched your search
@@ -920,7 +920,8 @@ pub(crate) fn anchor_from_json(v: &Value, cmd: &str) -> Result<Anchor> {
|
||||
};
|
||||
let mut anchor = Anchor::with_handles(p, handle("in")?, handle("out")?);
|
||||
match v.get("smooth").filter(|b| !b.is_null()) {
|
||||
None | Some(Value::Bool(false)) => {}
|
||||
None => {}
|
||||
Some(Value::Bool(false)) => anchor.kind = AnchorKind::Corner,
|
||||
Some(Value::Bool(true)) => anchor.kind = AnchorKind::Smooth,
|
||||
Some(_) => return Err(bad(cmd, "anchor `smooth` must be true or false")),
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! and strokes, effects, opacity and blend mode, and the link to the style) or, with the Appearance
|
||||
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
|
||||
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
|
||||
//! and a change of selection loads only the proxies. `paint.default` resets it.
|
||||
//! and a change of selection loads only the proxies. `paint.default` resets it, and
|
||||
//! `appearance.setNewArt` sets its fill, stroke and stroke options whatever is selected.
|
||||
//!
|
||||
//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile
|
||||
//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new`
|
||||
@@ -34,7 +35,7 @@ pub(crate) struct NewArtSource {
|
||||
|
||||
use super::gradient::unplaced;
|
||||
use super::paint::SelectionPaints;
|
||||
use super::{CommandSpec, Result, Session, always, cmd, switch_or};
|
||||
use super::{CommandSpec, Result, Session, always, bad, cmd, switch_or};
|
||||
use crate::doc_state::{SelectionRecord, objects_only};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -57,9 +58,181 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
describe
|
||||
),
|
||||
cmd!(
|
||||
"appearance.setNewArt",
|
||||
"Set New Art Appearance",
|
||||
[],
|
||||
None,
|
||||
"{fill?: {color?, none?, swatch?, tint?, gradient?, keepModel?} (a paint as paint.setFill takes it), stroke?: (a paint, as fill), weight?: 0..1000 pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?: 1..500, dash?: [lengths, each 0..1000000 pt, at most 64, not all 0]|null (null: a solid line), dashOffset?: -1000000..1000000 pt (with a dash pattern), fillOverprint?: bool, strokeOverprint?: bool} set the fill, stroke and stroke options the next object drawn gets, whatever is selected: the selection and its art, the active proxy and the recent colors stay as they are. Without `weight` the stored stroke weight stays; a stroke painted on new art without one gets 1 pt only when that stored weight is 0. A bad value is an error with nothing changed, and so is any change while New Art Has Basic Appearance is off and an object is selected (new art takes that object's appearance then) → {changed: whether the next object drawn looks different}",
|
||||
always,
|
||||
set_new_art
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The most dash and gap lengths `appearance.setNewArt` takes.
|
||||
const MAX_DASHES: usize = 64;
|
||||
/// The settings a `fill` or `stroke` paint of `appearance.setNewArt` takes.
|
||||
const PAINT_KEYS: [&str; 6] = ["color", "none", "swatch", "tint", "gradient", "keepModel"];
|
||||
/// The largest dash, gap or dash offset `appearance.setNewArt` takes, in points.
|
||||
const MAX_DASH_LENGTH: f64 = 1_000_000.0;
|
||||
|
||||
/// What [`dash_fault`] finds wrong with a list of dash and gap lengths.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum DashFault {
|
||||
/// More than [`MAX_DASHES`] lengths.
|
||||
TooMany,
|
||||
/// A length that is not a number from 0 to [`MAX_DASH_LENGTH`].
|
||||
OutOfRange,
|
||||
/// Lengths that are all 0.
|
||||
AllZero,
|
||||
}
|
||||
|
||||
/// What is wrong with the dash and gap lengths `lengths`, which `appearance.setNewArt` and the
|
||||
/// scripts' `strokeDashes` and `defaultStrokeDashes` check the same way; `None` when they are good.
|
||||
/// An empty list (a solid line) is good.
|
||||
pub(crate) fn dash_fault(lengths: &[f64]) -> Option<DashFault> {
|
||||
if lengths.len() > MAX_DASHES {
|
||||
Some(DashFault::TooMany)
|
||||
} else if !lengths.iter().all(|n| n.is_finite() && (0.0..=MAX_DASH_LENGTH).contains(n)) {
|
||||
Some(DashFault::OutOfRange)
|
||||
} else if !lengths.is_empty() && lengths.iter().all(|n| *n == 0.0) {
|
||||
Some(DashFault::AllZero)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as `appearance.setNewArt` stores it without `keepModel`: an RGB color in the color mode of
|
||||
/// the document in front.
|
||||
pub(crate) fn stored_color(s: &Session, c: vectorcraft_color::Color) -> vectorcraft_color::Color {
|
||||
super::paint::new_color(s, &json!({}), c)
|
||||
}
|
||||
|
||||
/// `appearance.setNewArt`: new art's fill, stroke and stroke options, every value checked before
|
||||
/// anything changes.
|
||||
fn set_new_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.setNewArt";
|
||||
let paint = |key: &str, fill: bool| -> Result<Option<Paint>> {
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
if !v.is_object() {
|
||||
return Err(bad(C, format!("{key} must be a paint object (color, none, swatch or gradient), got {v}")));
|
||||
}
|
||||
if let Some(k) = v.as_object().and_then(|o| o.keys().find(|k| !PAINT_KEYS.contains(&k.as_str()))) {
|
||||
return Err(bad(C, format!("{key}: unknown setting `{k}` (a paint takes {})", PAINT_KEYS.join(", "))));
|
||||
}
|
||||
if v.get("swatch").is_some_and(|w| !w.is_string()) {
|
||||
return Err(bad(C, format!("{key}: `swatch` must be a swatch name")));
|
||||
}
|
||||
let pattern_only = |name: &str| s.doc().is_ok_and(|st| st.doc.swatch(name).is_none() && st.doc.pattern(name).is_some());
|
||||
if v.get("tint").is_some() && v.get("swatch").and_then(Value::as_str).is_none_or(pattern_only) {
|
||||
return Err(bad(C, format!("{key}: `tint` goes with a global or spot `swatch`")));
|
||||
}
|
||||
let given = super::paint::paint_from(s, v)?.ok_or_else(|| bad(C, format!("{key}: give color, none, swatch or gradient")))?;
|
||||
if !fill && matches!(&given, Paint::Gradient(g) if g.gradient.dither) && v.get("swatch").and_then(Value::as_str).is_none() {
|
||||
return Err(bad(C, "`dither` applies to gradient fills"));
|
||||
}
|
||||
Ok(Some(unplaced(&given)))
|
||||
};
|
||||
let (fill, stroke) = (paint("fill", true)?, paint("stroke", false)?);
|
||||
let number = |key: &str, min: f64, max: f64| -> Result<()> {
|
||||
match p.get(key) {
|
||||
None => Ok(()),
|
||||
Some(v) if v.as_f64().is_some_and(|n| n.is_finite() && (min..=max).contains(&n)) => Ok(()),
|
||||
Some(v) => Err(bad(C, format!("{key} must be a number from {min} to {max}, got {v}"))),
|
||||
}
|
||||
};
|
||||
number("weight", 0.0, 1000.0)?;
|
||||
number("miterLimit", 1.0, 500.0)?;
|
||||
number("dashOffset", -MAX_DASH_LENGTH, MAX_DASH_LENGTH)?;
|
||||
for key in ["cap", "join"] {
|
||||
if p.get(key).is_some_and(|v| !v.is_string()) {
|
||||
return Err(bad(C, format!("{key} must be a name")));
|
||||
}
|
||||
}
|
||||
match p.get("dash") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::Array(a)) if a.len() > MAX_DASHES => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
|
||||
Some(Value::Array(a)) => {
|
||||
let lengths: Option<Vec<f64>> = a.iter().map(Value::as_f64).collect();
|
||||
match lengths.map_or(Some(DashFault::OutOfRange), |l| dash_fault(&l)) {
|
||||
None => {}
|
||||
Some(DashFault::TooMany) => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
|
||||
Some(DashFault::OutOfRange) => return Err(bad(C, format!("each dash length must be a number from 0 to {MAX_DASH_LENGTH}"))),
|
||||
Some(DashFault::AllZero) => return Err(bad(C, "dash needs a length that is not 0")),
|
||||
}
|
||||
}
|
||||
Some(v) => return Err(bad(C, format!("dash must be a list of lengths or null, got {v}"))),
|
||||
}
|
||||
let flag = |key: &str| -> Result<Option<bool>> {
|
||||
p.get(key).map(|v| v.as_bool().ok_or_else(|| bad(C, format!("{key} must be true or false, got {v}")))).transpose()
|
||||
};
|
||||
let (fill_overprint, stroke_overprint) = (flag("fillOverprint")?, flag("strokeOverprint")?);
|
||||
let options: serde_json::Map<String, Value> =
|
||||
["weight", "cap", "join", "miterLimit", "dash", "dashOffset"].iter().filter_map(|k| Some((k.to_string(), p.get(*k)?.clone()))).collect();
|
||||
let change = super::stroke::StrokeChange::parse(&Value::Object(options), C)?;
|
||||
let dashed = match p.get("dash") {
|
||||
Some(Value::Array(a)) => !a.is_empty(),
|
||||
Some(_) => false,
|
||||
None => s.new_art().stroke().is_some_and(|st| st.dash.is_some()),
|
||||
};
|
||||
if p.get("dashOffset").and_then(Value::as_f64).is_some_and(|o| o != 0.0) && !dashed {
|
||||
return Err(bad(C, "dashOffset needs a dash pattern"));
|
||||
}
|
||||
let nothing = fill.is_none() && stroke.is_none() && change.is_empty() && fill_overprint.is_none() && stroke_overprint.is_none();
|
||||
if !nothing
|
||||
&& !s.prefs.new_art_basic
|
||||
&& !(s.tool_paints(false) && s.tool_paints(true))
|
||||
&& s.active().is_some_and(|st| !st.selection.subjects().is_empty())
|
||||
{
|
||||
return Err(bad(
|
||||
C,
|
||||
"with New Art Has Basic Appearance off, new art takes the selected object's appearance: deselect it or turn the option on",
|
||||
));
|
||||
}
|
||||
let look = |s: &Session| {
|
||||
let (opacity, blend, style) = s.new_art_transparency();
|
||||
(s.new_art(), opacity, blend, style.map(str::to_string))
|
||||
};
|
||||
let (before, was) = (s.paint.clone(), look(s));
|
||||
if let Some(f) = fill {
|
||||
s.paint.fill = f;
|
||||
}
|
||||
if let Some(st) = stroke {
|
||||
if !st.is_none() && s.paint.stroke.is_none() && s.paint.stroke_width == 0.0 {
|
||||
s.paint.stroke_width = 1.0;
|
||||
}
|
||||
s.paint.stroke = st;
|
||||
}
|
||||
if let Some(w) = change.weight {
|
||||
s.paint.stroke_width = w;
|
||||
}
|
||||
if !change.is_empty()
|
||||
&& let Some(st) = s.new_art_stroke_mut()
|
||||
{
|
||||
change.apply(st);
|
||||
}
|
||||
if let Some(on) = fill_overprint {
|
||||
let t = s.new_art_template_mut();
|
||||
if t.fill().is_none() {
|
||||
t.items.insert(0, AppearanceItem::Fill(FillLayer::new(Paint::None)));
|
||||
}
|
||||
if let Some(f) = t.fill_mut() {
|
||||
f.overprint = on;
|
||||
}
|
||||
}
|
||||
if let Some(on) = stroke_overprint
|
||||
&& let Some(st) = s.new_art_stroke_mut()
|
||||
{
|
||||
st.overprint = on;
|
||||
}
|
||||
let changed = look(s) != was;
|
||||
if !changed {
|
||||
s.paint = before;
|
||||
}
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
/// `t` reduced to a basic appearance: an empty fill under its top stroke (options kept, without
|
||||
/// its own transparency or effects).
|
||||
fn basic_of(t: &Appearance) -> Appearance {
|
||||
|
||||
@@ -180,8 +180,9 @@ pub struct DocSettings {
|
||||
pub layout: ArtboardLayout,
|
||||
/// Columns of a grid layout.
|
||||
pub columns: u32,
|
||||
/// Rows of a grid by column, in place of `columns` when more than 0.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
/// Rows of a grid by column, in place of `columns` when more than 0, up to `MAX_ARTBOARDS` (a
|
||||
/// saved or Recent preset's larger value is read as `MAX_ARTBOARDS`).
|
||||
#[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")]
|
||||
pub rows: u32,
|
||||
/// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value
|
||||
/// outside that range is read as the nearer end).
|
||||
@@ -380,12 +381,25 @@ impl DocSettings {
|
||||
return Ok(());
|
||||
}
|
||||
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?;
|
||||
let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32);
|
||||
for (k, v) in o {
|
||||
match k.as_str() {
|
||||
"layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?,
|
||||
"columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?,
|
||||
"rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?,
|
||||
"columns" => {
|
||||
self.columns = v
|
||||
.as_f64()
|
||||
.filter(|c| c.is_finite() && *c >= 1.0)
|
||||
.ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?
|
||||
.round()
|
||||
.min(MAX_ARTBOARDS as f64) as u32
|
||||
}
|
||||
"rows" => {
|
||||
self.rows = v
|
||||
.as_f64()
|
||||
.map(f64::round)
|
||||
.filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r))
|
||||
.map(|r| r as u32)
|
||||
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))?
|
||||
}
|
||||
"spacing" => {
|
||||
self.spacing = v
|
||||
.as_f64()
|
||||
@@ -590,6 +604,12 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u
|
||||
Ok(f64::deserialize(d)?.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32)
|
||||
}
|
||||
|
||||
/// A saved or Recent preset's grid rows, kept to at most [`MAX_ARTBOARDS`]; 0 (columns in their
|
||||
/// place) stays 0.
|
||||
fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D::Error> {
|
||||
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
|
||||
}
|
||||
|
||||
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
|
||||
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
|
||||
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Anchors",
|
||||
[],
|
||||
None,
|
||||
"{id, subpaths: [{anchors: [{x,y,in?,out?}], closed}]} replace a path's geometry",
|
||||
"{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry",
|
||||
has_doc,
|
||||
set_anchors
|
||||
),
|
||||
|
||||
@@ -104,6 +104,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"appearance.removeItem",
|
||||
"appearance.setActiveItem",
|
||||
"appearance.setItem",
|
||||
"appearance.setNewArt",
|
||||
"appearance.showAllHidden",
|
||||
"appearance.targetContents",
|
||||
"appearance.transfer",
|
||||
|
||||
+162
-21
@@ -111,6 +111,13 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
|
||||
variables::after_command(h, before);
|
||||
}
|
||||
|
||||
mod colors;
|
||||
mod defaults;
|
||||
mod paths;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
|
||||
/// The error for a member read or called with no document open.
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
/// The error for an object that was deleted, or that came from an earlier run.
|
||||
@@ -161,14 +168,38 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
|
||||
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
|
||||
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
|
||||
/// each kept while its document is unchanged, 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), and the `Variable` and `Dataset` objects it
|
||||
/// gave out.
|
||||
/// 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
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
items: RefCell<Vec<ItemList>>,
|
||||
/// The last list of each document's paths ([`paths`]), kept while that document is unchanged.
|
||||
paths: RefCell<Vec<ItemList>>,
|
||||
/// A path and its subpaths with the point changes the run has made to it and not written yet
|
||||
/// ([`flush`]).
|
||||
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
|
||||
/// The index of the first point of each subpath of the path whose points the run read last,
|
||||
/// and what they were counted from ([`paths`]).
|
||||
point_starts: RefCell<Option<(paths::Counted, Rc<Vec<usize>>)>>,
|
||||
/// How many times the points the run read of each path went stale, by document uid and path id
|
||||
/// ([`paths`]).
|
||||
point_cuts: RefCell<std::collections::HashMap<(u64, u64), u64>>,
|
||||
/// Each path whose points the run read, as the run last saw it, by document uid and then path
|
||||
/// id ([`paths`]).
|
||||
point_nodes: RefCell<std::collections::HashMap<u64, std::collections::HashMap<u64, Arc<crate::doc::Node>>>>,
|
||||
/// The path whose points the object model is writing with `path.setAnchors`, the only path
|
||||
/// that command changes ([`paths`]).
|
||||
one_path: Cell<Option<Item>>,
|
||||
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
|
||||
/// points it read ([`paths`]).
|
||||
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
|
||||
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
|
||||
/// change.
|
||||
editing: Cell<Option<Item>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
text: text::TextState,
|
||||
@@ -223,6 +254,24 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
/// 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>>);
|
||||
|
||||
/// The most documents whose lists [`State`] keeps at once, the least recently listed going first.
|
||||
const KEPT_LISTS: usize = 8;
|
||||
|
||||
/// The list kept in `lists` for the document `st`, while that document is unchanged.
|
||||
fn kept_list(lists: &RefCell<Vec<ItemList>>, st: &DocState) -> Option<Rc<Vec<NodeId>>> {
|
||||
lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone())
|
||||
}
|
||||
|
||||
/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had.
|
||||
fn keep_list(lists: &RefCell<Vec<ItemList>>, st: &DocState, ids: &Rc<Vec<NodeId>>) {
|
||||
let mut l = lists.borrow_mut();
|
||||
l.retain(|(uid, ..)| *uid != st.uid);
|
||||
if l.len() >= KEPT_LISTS {
|
||||
l.remove(0);
|
||||
}
|
||||
l.push((st.uid, st.doc.clone(), ids.clone()));
|
||||
}
|
||||
|
||||
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
|
||||
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
|
||||
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
|
||||
@@ -279,15 +328,40 @@ type Answer = std::result::Result<Data, HostError>;
|
||||
/// A member function: the run's host and the call's arguments, `this` first.
|
||||
type Member = fn(&Host, &[Data]) -> Answer;
|
||||
|
||||
/// A member function that first writes the point changes waiting in [`State`] ([`flush`]).
|
||||
fn function(link: &Link, f: Member) -> HostFunction {
|
||||
call(link, f, true)
|
||||
}
|
||||
|
||||
/// A member function of the points of a path, which reads and adds to the point changes waiting in
|
||||
/// [`State`] instead of writing them first.
|
||||
fn point_function(link: &Link, f: Member) -> HostFunction {
|
||||
call(link, f, false)
|
||||
}
|
||||
|
||||
fn call(link: &Link, f: Member, flushing: bool) -> HostFunction {
|
||||
let l = link.clone();
|
||||
Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(data_size).sum::<u64>())?;
|
||||
if flushing {
|
||||
flush(&h)?;
|
||||
}
|
||||
f(&h, &a)
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes the point changes of a path that wait in [`State`] with one command ([`paths::flush`]).
|
||||
pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> {
|
||||
paths::flush(h)
|
||||
}
|
||||
|
||||
/// Notes the changes a command made to the points of the paths the run has read
|
||||
/// ([`paths::see_all_points`]).
|
||||
pub(super) fn see_points(h: &Host) {
|
||||
paths::see_all_points(h)
|
||||
}
|
||||
|
||||
fn get(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Get(function(link, f))
|
||||
}
|
||||
@@ -300,6 +374,19 @@ fn method(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Method(function(link, f))
|
||||
}
|
||||
|
||||
/// [`get`], [`property`] and [`method`] for a member of the points of a path ([`point_function`]).
|
||||
fn point_get(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Get(point_function(link, f))
|
||||
}
|
||||
|
||||
fn point_property(link: &Link, g: Member, s: Member) -> HostMember {
|
||||
HostMember::Property { get: point_function(link, g), set: point_function(link, s) }
|
||||
}
|
||||
|
||||
fn point_method(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Method(point_function(link, f))
|
||||
}
|
||||
|
||||
/// A member of a class with what `reflect` tells of it.
|
||||
pub(super) type Described = (String, HostMember, MemberInfo);
|
||||
|
||||
@@ -315,8 +402,9 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo
|
||||
}
|
||||
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
|
||||
/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
/// the check that a document, page item, path point or text range `this` is still there.
|
||||
/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and
|
||||
/// `reflect` leaves it out.
|
||||
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
let message = format!("{class}.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
@@ -327,9 +415,12 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
|
||||
"Document" => {
|
||||
doc_of(&h, arg(&a, 0), "Document")?;
|
||||
}
|
||||
"PageItem" | "TextFrame" => {
|
||||
"PageItem" | "PathItem" | "TextFrame" => {
|
||||
item_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
"PathPoint" => {
|
||||
paths::this_point(&h, &a)?;
|
||||
}
|
||||
"TextRange" => {
|
||||
text::check_range(&h, arg(&a, 0))?;
|
||||
}
|
||||
@@ -656,6 +747,12 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
return Ok(());
|
||||
}
|
||||
let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id);
|
||||
// Anchors and segments the change removed (a path opened or given fewer points) are left out.
|
||||
let left = |id: &NodeId, p: usize, test: &dyn Fn(&vectorcraft_geom::path::SubPath) -> bool| {
|
||||
doc.node(*id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.get(p).is_some_and(test))
|
||||
};
|
||||
let anchor_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| k < sp.anchors.len());
|
||||
let segment_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| sp.has_segment(k, true));
|
||||
let kept: Vec<NodeId> = before.objects.iter().copied().filter(keep).collect();
|
||||
if kept.is_empty() {
|
||||
command(h, "select.none", &json!({}))?;
|
||||
@@ -668,7 +765,7 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
|
||||
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
|
||||
Some(a) => a.iter().filter(|(p, k)| anchor_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect(),
|
||||
// A path with only segments selected gets them back below, with no anchors.
|
||||
None if before.segments.contains_key(i) => Vec::new(),
|
||||
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
|
||||
@@ -679,7 +776,10 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?;
|
||||
}
|
||||
for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) {
|
||||
let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect();
|
||||
let segments: Vec<[usize; 2]> = segments.iter().filter(|(p, k)| segment_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect();
|
||||
if segments.is_empty() {
|
||||
continue;
|
||||
}
|
||||
command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?;
|
||||
}
|
||||
let guides: Vec<NodeId> = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect();
|
||||
@@ -799,9 +899,15 @@ pub(super) fn after_kept_command(h: &Host) {
|
||||
text::styles::after_command(h);
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept.
|
||||
/// 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`]).
|
||||
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
|
||||
paths::see_all_points(h);
|
||||
let kept = h.dom.editing.replace(Some(item));
|
||||
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
|
||||
h.dom.editing.set(kept);
|
||||
r
|
||||
}
|
||||
|
||||
/// Reads the document of `doc` with `f`.
|
||||
@@ -1208,6 +1314,22 @@ fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static s
|
||||
})
|
||||
}
|
||||
|
||||
/// The `file.newPresets` fields `addDocument` gives `file.new`: those of the profile's first
|
||||
/// built-in preset with `presetSettings` over them.
|
||||
const BUILT_IN_SETTINGS: &[&str] = &[
|
||||
"width",
|
||||
"height",
|
||||
"units",
|
||||
"artboards",
|
||||
"artboardLayout",
|
||||
"bleed",
|
||||
"backgroundContents",
|
||||
"colorMode",
|
||||
"rasterEffectsPpi",
|
||||
"previewMode",
|
||||
"alignNewObjectsToPixelGrid",
|
||||
];
|
||||
|
||||
/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from
|
||||
/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in
|
||||
/// place of the profile's.
|
||||
@@ -1254,15 +1376,25 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())),
|
||||
Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())),
|
||||
}
|
||||
// The document starts from the first preset of the profile's category (Print: Letter).
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
|
||||
if let Some(first) = first {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
}
|
||||
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
|
||||
if let Some(m) = mode {
|
||||
p.entry("colorMode").or_insert_with(|| json!(m));
|
||||
}
|
||||
// The document starts from the first built-in preset of the profile's category (Print:
|
||||
// Letter) with `presetSettings` over it, given in full so that a saved preset of the same name
|
||||
// does not stand in for it. Settings the built-in preset refuses are an error.
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
|
||||
if let Some(first) = first {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
|
||||
if let Value::Object(settings) = full.to_json() {
|
||||
for key in BUILT_IN_SETTINGS {
|
||||
if let Some(v) = settings.get(*key) {
|
||||
p.insert((*key).into(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
|
||||
// A profile whose file could not be read throws, and the document `file.new` made with the
|
||||
// defaults is put back, with the Recent sizes as they were.
|
||||
atomically(h, |h| {
|
||||
@@ -2681,6 +2813,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
paths::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.
|
||||
@@ -2778,17 +2911,17 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]),
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("pathItems", get(l, paths::doc_path_items), MemberInfo { collection: true, ..typed("PathItems") }),
|
||||
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
|
||||
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
@@ -2889,7 +3022,15 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
);
|
||||
page_item.extend(variables::page_item_members(l));
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None)));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| {
|
||||
let mut members = variables::item_members(l, c);
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
}
|
||||
class(c, Some("PageItem"), members, None)
|
||||
}));
|
||||
classes.extend(paths::classes(l));
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.push(class(
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
//! The color classes of the script object model, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/RGBColor/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/LabColor/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/> describe them.
|
||||
//!
|
||||
//! A color is plain data: `new RGBColor()` gives an object with `typename` and its components,
|
||||
//! which the script can change, and reading `fillColor` or `strokeColor` gives a new one each time.
|
||||
//! 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;
|
||||
//! `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. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
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.
|
||||
const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"];
|
||||
|
||||
/// The components of each color class, with the value `new` gives them.
|
||||
const CLASSES: &[(&str, &[&str])] = &[
|
||||
("RGBColor", &["red", "green", "blue"]),
|
||||
("CMYKColor", &["cyan", "magenta", "yellow", "black"]),
|
||||
("GrayColor", &["gray"]),
|
||||
("LabColor", &["l", "a", "b"]),
|
||||
("NoColor", &[]),
|
||||
("GradientColor", &[]),
|
||||
("SpotColor", &["tint"]),
|
||||
("PatternColor", &[]),
|
||||
];
|
||||
|
||||
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
|
||||
let mut items = vec![("typename".to_string(), text(class))];
|
||||
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
|
||||
Data::Object(items)
|
||||
}
|
||||
|
||||
/// A component as the script sees it: `exact` rounded to the fewest decimals, from 4 to 9, that
|
||||
/// `back` turns into the stored `v` again, else `exact` itself, so that assigning a color read
|
||||
/// from an object gives that object the same color.
|
||||
fn shown_as(exact: f64, v: f32, back: impl Fn(f64) -> f32) -> f64 {
|
||||
let mut scale = 1e4;
|
||||
for _ in 4..=9 {
|
||||
let r = (exact * scale).round() / scale;
|
||||
if back(r) == v {
|
||||
return r;
|
||||
}
|
||||
scale *= 10.0;
|
||||
}
|
||||
exact
|
||||
}
|
||||
|
||||
/// A component stored as `v`, from 0 to 1, that the script sees times `scale`.
|
||||
fn shown(v: f32, scale: f64) -> f64 {
|
||||
shown_as(f64::from(v) * scale, v, |r| unit(r, scale))
|
||||
}
|
||||
|
||||
/// The color object for a solid color.
|
||||
fn of_color(c: &Color) -> Data {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]),
|
||||
Color::Cmyk { c, m, y, k } => color_object(
|
||||
"CMYKColor",
|
||||
&[("cyan", shown(c, 100.0)), ("magenta", shown(m, 100.0)), ("yellow", shown(y, 100.0)), ("black", shown(k, 100.0))],
|
||||
),
|
||||
Color::Gray { k } => color_object("GrayColor", &[("gray", shown_as((1.0 - f64::from(k)) * 100.0, k, |g| unit(100.0 - g, 100.0)))]),
|
||||
Color::Lab { l, a, b } => color_object("LabColor", &[("l", shown(l, 1.0)), ("a", shown(a, 1.0)), ("b", shown(b, 1.0))]),
|
||||
}
|
||||
}
|
||||
|
||||
/// What reading `fillColor` or `strokeColor` gives for `paint`: a new color object, a `SpotColor`
|
||||
/// with its `tint` for a color linked to a global or spot swatch.
|
||||
pub(super) fn of_paint(paint: &Paint) -> Data {
|
||||
match paint {
|
||||
Paint::None => color_object("NoColor", &[]),
|
||||
Paint::Solid { swatch: Some(_), tint, .. } => color_object("SpotColor", &[("tint", shown(*tint, 100.0))]),
|
||||
Paint::Solid { color, .. } => of_color(color),
|
||||
Paint::Gradient(_) => color_object("GradientColor", &[]),
|
||||
Paint::Pattern { .. } => color_object("PatternColor", &[]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether assigning the color object `d`, read as `assigned`, leaves the paint `now` as it is: a
|
||||
/// `NoColor` on no paint, or on an unlinked color either a color equal to it once `store` makes
|
||||
/// it what the document stores, or the components reading `now` gives (a Gray value read back can
|
||||
/// stand for an ink amount that no Gray value names exactly).
|
||||
pub(super) fn unchanged(d: &Data, assigned: Option<Color>, now: &Paint, store: impl FnOnce(Color) -> Color) -> bool {
|
||||
match (assigned, now) {
|
||||
(None, Paint::None) => true,
|
||||
(Some(c), Paint::Solid { color, swatch: None, .. }) => store(c) == *color || shows(d, &of_color(color)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the color object `d` has the class and every component of `shown`.
|
||||
fn shows(d: &Data, shown: &Data) -> bool {
|
||||
let (Data::Object(a), Data::Object(b)) = (d, shown) else { return false };
|
||||
b.iter().all(|(k, v)| a.iter().any(|(n, w)| n == k && w == v))
|
||||
}
|
||||
|
||||
/// The component `key` of color object `o`, from `min` to `max` (0 when it is left out).
|
||||
fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -> std::result::Result<f64, HostError> {
|
||||
match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) {
|
||||
None | Some(Data::Undefined) => Ok(0.0),
|
||||
Some(Data::Number(n)) if n.is_finite() && (min..=max).contains(n) => Ok(*n),
|
||||
Some(Data::Number(_)) => Err(HostError::Range(format!("{class}.{key} must be from {min} to {max}"))),
|
||||
Some(_) => Err(HostError::Type(format!("{class}.{key} must be a number"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
fn unit(v: f64, scale: f64) -> f32 {
|
||||
(v / scale) as f32
|
||||
}
|
||||
|
||||
/// The color a script assigned, checked: `None` for a `NoColor`. `what` names the property.
|
||||
pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result<Option<Color>, HostError> {
|
||||
let Data::Object(o) = d else { return Err(HostError::Type(format!("{what} must be a color object"))) };
|
||||
let class = match o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v) {
|
||||
Some(Data::String(s)) => s.as_str(),
|
||||
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
|
||||
};
|
||||
let c = |key: &str, min: f64, max: f64| component(o, class, key, min, max);
|
||||
Ok(Some(match class {
|
||||
"NoColor" => return Ok(None),
|
||||
"RGBColor" => {
|
||||
Color::Rgb { r: unit(c("red", 0.0, 255.0)?, 255.0), g: unit(c("green", 0.0, 255.0)?, 255.0), b: unit(c("blue", 0.0, 255.0)?, 255.0) }
|
||||
}
|
||||
"CMYKColor" => Color::Cmyk {
|
||||
c: unit(c("cyan", 0.0, 100.0)?, 100.0),
|
||||
m: unit(c("magenta", 0.0, 100.0)?, 100.0),
|
||||
y: unit(c("yellow", 0.0, 100.0)?, 100.0),
|
||||
k: unit(c("black", 0.0, 100.0)?, 100.0),
|
||||
},
|
||||
"GrayColor" => Color::Gray { k: unit(100.0 - c("gray", 0.0, 100.0)?, 100.0) },
|
||||
"LabColor" => Color::Lab { l: unit(c("l", 0.0, 100.0)?, 1.0), a: unit(c("a", -128.0, 128.0)?, 1.0), b: unit(c("b", -128.0, 128.0)?, 1.0) },
|
||||
l if LATER.contains(&l) => return Err(HostError::Error(format!("assigning a {l} is not available yet"))),
|
||||
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `color` as `paint.setFill` and `paint.setStroke` take it.
|
||||
pub(super) fn param(color: &Color) -> Value {
|
||||
serde_json::to_value(color).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// The constructors of the color classes, and `cmykColor`.
|
||||
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
let make = |name: &str, components: &'static [&'static str]| {
|
||||
let l = link.clone();
|
||||
let class = name.to_string();
|
||||
let f: HostFunction = Rc::new(move |_| {
|
||||
current(&l)?.charge_call(64)?;
|
||||
let zeros: Vec<(&str, f64)> = components.iter().map(|k| (*k, if *k == "tint" { 100.0 } else { 0.0 })).collect();
|
||||
Ok(color_object(&class, &zeros))
|
||||
});
|
||||
f
|
||||
};
|
||||
let mut out: Vec<HostClass> = CLASSES
|
||||
.iter()
|
||||
.map(|(name, components)| HostClass {
|
||||
name: (*name).into(),
|
||||
parent: None,
|
||||
members: Vec::new(),
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: Some(make(name, components)),
|
||||
})
|
||||
.collect();
|
||||
out.push(HostClass {
|
||||
name: "cmykColor".into(),
|
||||
parent: None,
|
||||
members: Vec::new(),
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: Some(make("CMYKColor", CLASSES[1].1)),
|
||||
});
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! A document's default fill and stroke in the script object model, the `Document` members whose
|
||||
//! names start with `default` that the help page
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/> describes, and `scaleFactor`.
|
||||
//!
|
||||
//! The defaults are what the next object drawn gets ([`crate::Session::new_art`]), the same for
|
||||
//! every open document, as the help page says of these global settings. Reading one reads new
|
||||
//! art's top fill or stroke, and assigning one runs `appearance.setNewArt`, which leaves the
|
||||
//! selection, its art, the active proxy and the recent colors as they were. A value that changes
|
||||
//! nothing runs no command, and a bad value throws an error with nothing changed.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help page does not state:
|
||||
//! - A color is new art's fill or stroke itself: assigning a color also makes `defaultFilled` or
|
||||
//! `defaultStroked` true, and assigning a `NoColor` makes it false. `defaultFilled` or
|
||||
//! `defaultStroked` set to true with no default fill or stroke gives black.
|
||||
//! - An RGB color is stored in the color mode of the document in front, as `paint.setFill` stores
|
||||
//! it.
|
||||
//! - `defaultStrokeWidth` is 0 to 1000 points, a dash or gap 0 to 1,000,000 points (at most 64 of
|
||||
//! them, not all 0), and `defaultStrokeDashOffset` -1,000,000 to 1,000,000 points, which needs a
|
||||
//! dash pattern unless it is 0.
|
||||
//! - While New Art Has Basic Appearance is off and an object is selected, assigning a default
|
||||
//! throws an error, since new art then takes that object's appearance.
|
||||
//! - `scaleFactor` is 1: VectorCraft draws every document at its own size.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, LineCap, LineJoin};
|
||||
use vectorcraft_js::{Data, HostError, MemberInfo};
|
||||
|
||||
use super::paths::{CAPS, JOINS, MAX_STROKE_WIDTH, dash_lengths};
|
||||
use super::{Answer, Described, Host, Link, arg, boolean, colors, command, get, named, num, number, property, this_doc, typed};
|
||||
|
||||
/// New art's appearance, after the check that the document `this` names is still open.
|
||||
fn new_art(h: &Host, a: &[Data]) -> std::result::Result<Appearance, HostError> {
|
||||
this_doc(h, a)?;
|
||||
Ok(h.session.borrow().new_art())
|
||||
}
|
||||
|
||||
/// Runs `appearance.setNewArt` with `params`, unless `same`.
|
||||
fn set(h: &Host, same: bool, params: Value) -> Answer {
|
||||
if !same {
|
||||
command(h, "appearance.setNewArt", ¶ms)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn top_paint(ap: &Appearance, fill: bool) -> Paint {
|
||||
if fill { ap.fill_paint() } else { ap.stroke_paint() }
|
||||
}
|
||||
|
||||
fn default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
Ok(colors::of_paint(&top_paint(&new_art(h, a)?, fill)))
|
||||
}
|
||||
|
||||
fn set_default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let what = if fill { "defaultFillColor" } else { "defaultStrokeColor" };
|
||||
let color = colors::assigned(arg(a, 1), what)?;
|
||||
let now = top_paint(&new_art(h, a)?, fill);
|
||||
let same = colors::unchanged(arg(a, 1), color, &now, |c| crate::cmd::newart::stored_color(&h.session.borrow(), c));
|
||||
let paint = match color {
|
||||
Some(c) => json!({"color": colors::param(&c)}),
|
||||
None => json!({"none": true}),
|
||||
};
|
||||
let key = if fill { "fill" } else { "stroke" };
|
||||
set(h, same, json!({ key: paint }))
|
||||
}
|
||||
|
||||
fn default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
Ok(Data::Bool(!top_paint(&new_art(h, a)?, fill).is_none()))
|
||||
}
|
||||
|
||||
fn set_default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let on = boolean(arg(a, 1), if fill { "defaultFilled" } else { "defaultStroked" })?;
|
||||
let now = !top_paint(&new_art(h, a)?, fill).is_none();
|
||||
let paint = if on { json!({"color": colors::param(&Color::BLACK)}) } else { json!({"none": true}) };
|
||||
let key = if fill { "fill" } else { "stroke" };
|
||||
set(h, now == on, json!({ key: paint }))
|
||||
}
|
||||
|
||||
fn default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let ap = new_art(h, a)?;
|
||||
Ok(Data::Bool(if fill { ap.fill().is_some_and(|f| f.overprint) } else { ap.stroke().is_some_and(|s| s.overprint) }))
|
||||
}
|
||||
|
||||
fn set_default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let (key, what) = if fill { ("fillOverprint", "defaultFillOverprint") } else { ("strokeOverprint", "defaultStrokeOverprint") };
|
||||
let on = boolean(arg(a, 1), what)?;
|
||||
let now = default_overprint(h, a, fill)? == Data::Bool(on);
|
||||
set(h, now, json!({ key: on }))
|
||||
}
|
||||
|
||||
/// New art's top stroke option `f` reads, or `none` when new art has no stroke.
|
||||
fn stroke_option<T>(h: &Host, a: &[Data], none: T, f: impl FnOnce(&vectorcraft_doc::StrokeLayer) -> T) -> std::result::Result<T, HostError> {
|
||||
Ok(new_art(h, a)?.stroke().map_or(none, f))
|
||||
}
|
||||
|
||||
fn default_stroke_width(h: &Host, a: &[Data]) -> Answer {
|
||||
this_doc(h, a)?;
|
||||
Ok(num(h.session.borrow().paint.stroke_width))
|
||||
}
|
||||
|
||||
fn set_default_stroke_width(h: &Host, a: &[Data]) -> Answer {
|
||||
let w = number(arg(a, 1), "defaultStrokeWidth")?;
|
||||
if !(0.0..=MAX_STROKE_WIDTH).contains(&w) {
|
||||
return Err(HostError::Range("defaultStrokeWidth must be from 0 to 1000 points".into()));
|
||||
}
|
||||
this_doc(h, a)?;
|
||||
let now = h.session.borrow().paint.stroke_width;
|
||||
set(h, now == w, json!({"weight": w}))
|
||||
}
|
||||
|
||||
fn default_cap(h: &Host, a: &[Data]) -> Answer {
|
||||
let cap = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
|
||||
Ok(Data::String(CAPS.iter().find(|c| c.0 == cap).map_or("StrokeCap.BUTTENDCAP", |c| c.1).into()))
|
||||
}
|
||||
|
||||
fn set_default_cap(h: &Host, a: &[Data]) -> Answer {
|
||||
let found = match arg(a, 1) {
|
||||
Data::String(s) => CAPS.iter().find(|c| c.1 == s),
|
||||
_ => None,
|
||||
};
|
||||
let Some(&(cap, _, name)) = found else { return Err(HostError::Type("defaultStrokeCap must be a StrokeCap value".into())) };
|
||||
let now = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
|
||||
set(h, now == cap, json!({"cap": name}))
|
||||
}
|
||||
|
||||
fn default_join(h: &Host, a: &[Data]) -> Answer {
|
||||
let join = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
|
||||
Ok(Data::String(JOINS.iter().find(|j| j.0 == join).map_or("StrokeJoin.MITERENDJOIN", |j| j.1).into()))
|
||||
}
|
||||
|
||||
fn set_default_join(h: &Host, a: &[Data]) -> Answer {
|
||||
let found = match arg(a, 1) {
|
||||
Data::String(s) => JOINS.iter().find(|j| j.1 == s),
|
||||
_ => None,
|
||||
};
|
||||
let Some(&(join, _, name)) = found else { return Err(HostError::Type("defaultStrokeJoin must be a StrokeJoin value".into())) };
|
||||
let now = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
|
||||
set(h, now == join, json!({"join": name}))
|
||||
}
|
||||
|
||||
fn default_miter(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(num(stroke_option(h, a, 10.0, |s| s.miter_limit)?))
|
||||
}
|
||||
|
||||
fn set_default_miter(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = number(arg(a, 1), "defaultStrokeMiterLimit")?;
|
||||
if !(1.0..=500.0).contains(&v) {
|
||||
return Err(HostError::Range("defaultStrokeMiterLimit must be from 1 to 500".into()));
|
||||
}
|
||||
let now = stroke_option(h, a, 10.0, |s| s.miter_limit)?;
|
||||
set(h, now == v, json!({"miterLimit": v}))
|
||||
}
|
||||
|
||||
fn dashes(h: &Host, a: &[Data]) -> std::result::Result<Vec<f64>, HostError> {
|
||||
stroke_option(h, a, Vec::new(), |s| s.dash.as_ref().map_or_else(Vec::new, |d| d.pattern.clone()))
|
||||
}
|
||||
|
||||
fn default_dashes(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Array(dashes(h, a)?.into_iter().map(num).collect()))
|
||||
}
|
||||
|
||||
fn set_default_dashes(h: &Host, a: &[Data]) -> Answer {
|
||||
let lengths = dash_lengths(arg(a, 1), "defaultStrokeDashes")?;
|
||||
let now = dashes(h, a)?;
|
||||
let dash = if lengths.is_empty() { Value::Null } else { json!(lengths) };
|
||||
set(h, now == lengths, json!({"dash": dash}))
|
||||
}
|
||||
|
||||
fn default_dash_offset(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(num(stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?))
|
||||
}
|
||||
|
||||
fn set_default_dash_offset(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = number(arg(a, 1), "defaultStrokeDashOffset")?;
|
||||
if v.abs() > MAX_STROKE_WIDTH * 1000.0 {
|
||||
return Err(HostError::Range("defaultStrokeDashOffset must be from -1000000 to 1000000 points".into()));
|
||||
}
|
||||
if dashes(h, a)?.is_empty() && v != 0.0 {
|
||||
return Err(HostError::Error("defaultStrokeDashOffset needs defaultStrokeDashes first".into()));
|
||||
}
|
||||
let now = stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?;
|
||||
set(h, now == v, json!({"dashOffset": v}))
|
||||
}
|
||||
|
||||
fn scale_factor(h: &Host, a: &[Data]) -> Answer {
|
||||
this_doc(h, a)?;
|
||||
Ok(num(1.0))
|
||||
}
|
||||
|
||||
/// The `Document` members of this module.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("defaultFillColor", property(l, |h, a| default_color(h, a, true), |h, a| set_default_color(h, a, true)), typed("Color")),
|
||||
("defaultFilled", property(l, |h, a| default_painted(h, a, true), |h, a| set_default_painted(h, a, true)), typed("boolean")),
|
||||
("defaultFillOverprint", property(l, |h, a| default_overprint(h, a, true), |h, a| set_default_overprint(h, a, true)), typed("boolean")),
|
||||
("defaultStrokeColor", property(l, |h, a| default_color(h, a, false), |h, a| set_default_color(h, a, false)), typed("Color")),
|
||||
("defaultStroked", property(l, |h, a| default_painted(h, a, false), |h, a| set_default_painted(h, a, false)), typed("boolean")),
|
||||
("defaultStrokeOverprint", property(l, |h, a| default_overprint(h, a, false), |h, a| set_default_overprint(h, a, false)), typed("boolean")),
|
||||
(
|
||||
"defaultStrokeWidth",
|
||||
property(l, default_stroke_width, set_default_stroke_width),
|
||||
MemberInfo { min: Some(0.0), max: Some(MAX_STROKE_WIDTH), ..typed("number") },
|
||||
),
|
||||
("defaultStrokeCap", property(l, default_cap, set_default_cap), typed("StrokeCap")),
|
||||
("defaultStrokeJoin", property(l, default_join, set_default_join), typed("StrokeJoin")),
|
||||
("defaultStrokeMiterLimit", property(l, default_miter, set_default_miter), typed("number")),
|
||||
("defaultStrokeDashes", property(l, default_dashes, set_default_dashes), typed("Array")),
|
||||
("defaultStrokeDashOffset", property(l, default_dash_offset, set_default_dash_offset), typed("number")),
|
||||
("scaleFactor", get(l, scale_factor), typed("number")),
|
||||
])
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1174,6 +1174,8 @@ struct Job {
|
||||
name: String,
|
||||
/// The file-access scope `script.run` came in, which every slice runs in.
|
||||
scope: crate::file_access::ScopeHandle,
|
||||
/// The script has ended, and the run waits for the person's growth answer before it is kept.
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
/// The `Data` for a JSON value, within `limits`. When it does not fit, the error is the place in
|
||||
@@ -1402,6 +1404,8 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
|
||||
|
||||
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
|
||||
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
// Point changes that wait in the object model are written before any command runs.
|
||||
dom::flush(host)?;
|
||||
let session = host.session.clone();
|
||||
let started = clock();
|
||||
let before = dom::before_command(host, id);
|
||||
@@ -1446,6 +1450,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
dom::after_command(host, before);
|
||||
// Style objects follow only a command that is kept.
|
||||
if crossed.is_ok() {
|
||||
dom::see_points(host);
|
||||
dom::after_kept_command(host);
|
||||
} else {
|
||||
session.borrow_mut().script_style_trail = StyleTrail::default();
|
||||
@@ -1517,6 +1522,7 @@ pub(crate) fn retained_style_lists(s: &Session) -> usize {
|
||||
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
|
||||
/// of a crossing throws a `RangeError`.
|
||||
fn vc_document(host: &Host) -> std::result::Result<Data, HostError> {
|
||||
dom::flush(host)?;
|
||||
let s = host.session.borrow();
|
||||
let Some(st) = s.active() else { return Ok(Data::Null) };
|
||||
let ids: Vec<u64> = st.selection.objects.iter().take(1_000).map(|i| i.0).collect();
|
||||
@@ -2103,7 +2109,7 @@ impl Session {
|
||||
if h.waiting.replace(false) {
|
||||
h.continues.set(h.continues.get() + 1);
|
||||
h.allowance_objects.set(h.allowance_objects.get().saturating_add(growth_objects()));
|
||||
h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(GROWTH_BYTES));
|
||||
h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(growth_bytes()));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2282,7 +2288,7 @@ impl Session {
|
||||
bytes_kept: Cell::new(0),
|
||||
bridge: Cell::new(0),
|
||||
allowance_objects: Cell::new(growth_objects()),
|
||||
allowance_bytes: Cell::new(GROWTH_BYTES),
|
||||
allowance_bytes: Cell::new(growth_bytes()),
|
||||
continues: Cell::new(0),
|
||||
waiting: Cell::new(false),
|
||||
log: RefCell::new(Vec::new()),
|
||||
@@ -2407,7 +2413,7 @@ impl Session {
|
||||
}
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
let (run, line_name) = (host.run, host.name.clone());
|
||||
let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope };
|
||||
let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope, finished: false };
|
||||
let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(id, job));
|
||||
self.script_key = Some(JobKey { id, run, name: line_name });
|
||||
@@ -2461,6 +2467,28 @@ impl Session {
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
}
|
||||
// A run whose script ended past its growth allowance is kept once the person lets it go on,
|
||||
// and put back when they stop it.
|
||||
if job.finished {
|
||||
if self.script_stop.is_set() {
|
||||
let kind = LimitKind::Interrupted;
|
||||
let e =
|
||||
RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
// One more allowance may still leave the growth past it: the person is asked again
|
||||
// while they may be, and past that the run ends unkept.
|
||||
if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) {
|
||||
let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
if job.host.waiting.get() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
}
|
||||
return Some(self.script_ended(job));
|
||||
}
|
||||
// A stop while a dialog waits ends the run there; the interpreter cannot go on from the call.
|
||||
if job.realm.waits() {
|
||||
let kind = LimitKind::Interrupted;
|
||||
@@ -2486,24 +2514,35 @@ impl Session {
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => {
|
||||
let n = job.host.dialogs.unused();
|
||||
let kind = LimitKind::Host;
|
||||
let message = if n == 1 {
|
||||
format!("`answers` has {n} answer the script did not use")
|
||||
} else {
|
||||
format!("`answers` has {n} answers the script did not use")
|
||||
};
|
||||
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false }))
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => {
|
||||
let r = self.script_commit(job);
|
||||
self.trim_histories();
|
||||
Some(r)
|
||||
// The point changes written as the script ended went past the growth allowance.
|
||||
Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => {
|
||||
job.finished = true;
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the run whose script has ended: it fails when answers it was given went unused, and is
|
||||
/// kept otherwise.
|
||||
fn script_ended(&mut self, job: Job) -> Result<Value> {
|
||||
let n = job.host.dialogs.unused();
|
||||
if n > 0 {
|
||||
let kind = LimitKind::Host;
|
||||
let message = if n == 1 {
|
||||
format!("`answers` has {n} answer the script did not use")
|
||||
} else {
|
||||
format!("`answers` has {n} answers the script did not use")
|
||||
};
|
||||
return self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false });
|
||||
}
|
||||
let r = self.script_commit(job);
|
||||
self.trim_histories();
|
||||
r
|
||||
}
|
||||
|
||||
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
|
||||
job.host.dialogs.stopped();
|
||||
job.host.disk.borrow_mut().picker = None;
|
||||
@@ -2823,6 +2862,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
let scope = job.scope.clone();
|
||||
let realm = &mut job.realm;
|
||||
let host = &job.host;
|
||||
let started = clock();
|
||||
let r = scope.run(|| {
|
||||
guard::catch_panic(|| {
|
||||
@@ -2830,7 +2870,14 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
if PANIC_IN_SLICE.with(Cell::get) {
|
||||
panic!("a slice failed");
|
||||
}
|
||||
realm.advance(SLICE_FUEL)
|
||||
// Point changes that still wait in the object model are written when the script ends. Between
|
||||
// slices the run's documents are put aside, so they can wait across slices.
|
||||
realm.advance(SLICE_FUEL).and_then(|progress| {
|
||||
if matches!(progress, Progress::Done(_)) {
|
||||
dom::flush(host).map_err(end_flush_error)?;
|
||||
}
|
||||
Ok(progress)
|
||||
})
|
||||
})
|
||||
});
|
||||
if let Some(started) = started {
|
||||
@@ -2844,6 +2891,17 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
r
|
||||
}
|
||||
|
||||
/// The error that ends a run when the point changes waiting at the end of its script cannot be
|
||||
/// written.
|
||||
fn end_flush_error(e: HostError) -> RunError {
|
||||
let message = match e {
|
||||
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) | HostError::Abort(m) => m,
|
||||
HostError::Marked { error, .. } => return end_flush_error(*error),
|
||||
HostError::Wait => "a host function waited for its result where the run cannot pause".into(),
|
||||
};
|
||||
RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false }
|
||||
}
|
||||
|
||||
/// Tests: removes the session's running job while the session keeps its hold on it. → whether a
|
||||
/// job was removed.
|
||||
#[cfg(test)]
|
||||
@@ -2860,6 +2918,15 @@ fn growth_objects() -> u64 {
|
||||
GROWTH_OBJECTS
|
||||
}
|
||||
|
||||
/// The bytes of new document data a run may keep before it is asked to continue or stop.
|
||||
fn growth_bytes() -> u64 {
|
||||
#[cfg(test)]
|
||||
if let Some(n) = TEST_GROWTH_BYTES.with(Cell::get) {
|
||||
return n;
|
||||
}
|
||||
GROWTH_BYTES
|
||||
}
|
||||
|
||||
/// The data a run may pass to and from commands.
|
||||
fn bridge_bytes() -> u64 {
|
||||
#[cfg(test)]
|
||||
@@ -2886,6 +2953,8 @@ thread_local! {
|
||||
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
|
||||
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
|
||||
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 heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
|
||||
|
||||
@@ -180,6 +180,8 @@ mod script_console;
|
||||
mod script_dialogs;
|
||||
mod script_dollar;
|
||||
mod script_dom;
|
||||
mod script_dom_defaults;
|
||||
mod script_dom_paths;
|
||||
mod script_engines;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! The new-art template (M3.65): Stroke panel options and graphic styles chosen with nothing
|
||||
//! selected, New Art Has Basic Appearance and `paint.default`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, Dash, LineCap, Node};
|
||||
@@ -377,3 +379,98 @@ fn fill_line_gives_a_new_line_the_current_fill() {
|
||||
assert_ne!(s.paint.fill, Paint::None);
|
||||
assert!(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 1, "y2": 1, "fill": "yes"})).is_err());
|
||||
}
|
||||
|
||||
/// `appearance.setNewArt` sets what the next object gets while the selection keeps its own look.
|
||||
#[test]
|
||||
fn set_new_art_changes_the_next_object_and_not_the_selection() {
|
||||
let mut s = session();
|
||||
let picked = rect(&mut s, 20.0);
|
||||
run(&mut s, "select.set", json!({"ids": [picked.0]}));
|
||||
let (look, undo, recent, active) = (node(&s, picked).appearance, undo_len(&s), s.recent_colors.clone(), s.fill_active);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"appearance.setNewArt",
|
||||
json!({"fill": {"color": "#ff0000"}, "stroke": {"none": true}, "weight": 4, "cap": "round", "dash": [3, 1], "dashOffset": 1, "fillOverprint": true}),
|
||||
);
|
||||
assert_eq!(r, json!({"changed": true}));
|
||||
assert_eq!(node(&s, picked).appearance, look, "the selected art kept its look");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![picked]);
|
||||
assert_eq!((undo_len(&s), &s.recent_colors, s.fill_active), (undo, &recent, active));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let id = rect(&mut s, 200.0);
|
||||
let ap = node(&s, id).appearance;
|
||||
let (fill, st) = (ap.fill().unwrap(), ap.stroke().unwrap());
|
||||
assert_eq!(fill.paint, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert!(fill.overprint);
|
||||
assert_eq!((st.paint.clone(), st.width, st.cap), (Paint::None, 4.0, LineCap::Round));
|
||||
assert_eq!(st.dash, Some(Dash { pattern: vec![3.0, 1.0], offset: 1.0, ..Default::default() }));
|
||||
// The same values again change nothing.
|
||||
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 4, "cap": "round"})), json!({"changed": false}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_new_art_refuses_bad_values_with_nothing_changed() {
|
||||
let mut s = session();
|
||||
let before = s.paint.clone();
|
||||
for params in [
|
||||
json!({"weight": -1}),
|
||||
json!({"weight": 1001}),
|
||||
json!({"weight": "3"}),
|
||||
json!({"miterLimit": 0.5}),
|
||||
json!({"cap": "flat"}),
|
||||
json!({"join": 2}),
|
||||
json!({"dash": [0, 0]}),
|
||||
json!({"dash": [-1]}),
|
||||
json!({"dash": "4 2"}),
|
||||
json!({"dashOffset": 2}),
|
||||
json!({"fill": "#ff0000"}),
|
||||
json!({"fill": {}}),
|
||||
json!({"fill": {"color": "#ff0000"}, "weight": -1}),
|
||||
json!({"stroke": {"tint": 50, "color": "#000000"}}),
|
||||
json!({"fillOverprint": "yes"}),
|
||||
json!({"widht": 3}),
|
||||
// A setting a paint does not take, here or nested in it, is refused too.
|
||||
json!({"fill": {"color": "#ff0000", "opacity": 25}}),
|
||||
json!({"stroke": {"none": true, "weight": 2}}),
|
||||
] {
|
||||
assert!(s.execute("appearance.setNewArt", ¶ms).is_err(), "accepted {params}");
|
||||
assert_eq!(s.paint, before, "changed new art for {params}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_new_art_refuses_a_tint_on_a_pattern_without_a_swatch_entry() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 20.0);
|
||||
let name = run(&mut s, "object.pattern.make", json!({"ids": [id.0], "edit": false}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "select.none", json!({}));
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).remove_swatch(&name);
|
||||
let before = s.paint.clone();
|
||||
assert!(s.execute("appearance.setNewArt", &json!({"fill": {"swatch": name, "tint": 50}})).is_err(), "accepted a tint on {name}");
|
||||
assert_eq!(s.paint, before);
|
||||
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"fill": {"swatch": name}})), json!({"changed": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_new_art_refuses_a_swatch_that_is_not_a_name() {
|
||||
let mut s = session();
|
||||
let before = s.paint.clone();
|
||||
for p in [json!({"fill": {"swatch": 7, "color": "#ff0000"}}), json!({"stroke": {"swatch": null, "color": "#ff0000"}})] {
|
||||
assert!(s.execute("appearance.setNewArt", &p).is_err(), "accepted {p}");
|
||||
assert_eq!(s.paint, before, "{p} changed new art");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_new_art_refuses_while_new_art_takes_the_selected_look() {
|
||||
let mut s = session();
|
||||
let picked = rect(&mut s, 20.0);
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [picked.0]}));
|
||||
let before = s.paint.clone();
|
||||
assert!(s.execute("appearance.setNewArt", &json!({"weight": 7})).is_err());
|
||||
assert_eq!(s.paint, before);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 7})), json!({"changed": true}));
|
||||
assert_eq!(s.new_art().stroke().unwrap().width, 7.0);
|
||||
}
|
||||
@@ -161,6 +161,8 @@ fn ppi_overprint_preview_and_bad_params() {
|
||||
json!({"artboardLayout": {"layout": "spiral"}}),
|
||||
json!({"artboardLayout": {"columns": 0}}),
|
||||
json!({"artboardLayout": {"rows": 0}}),
|
||||
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.4}}),
|
||||
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1001}}),
|
||||
json!({"artboardLayout": {"tiles": 2}}),
|
||||
json!({"units": "furlongs"}),
|
||||
json!({"width": 160000, "artboards": 1000}),
|
||||
@@ -1212,3 +1214,11 @@ fn the_new_layer_takes_an_id_no_profile_art_has() {
|
||||
// Ids given out later skip the symbol's art too.
|
||||
assert!(d.peek_next_id() > d.layers[0].id.0 && d.peek_next_id() > next);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_presets_rows_are_read_within_the_artboard_limit() {
|
||||
let rows = |n: u32| serde_json::from_value::<crate::cmd::newdoc::DocSettings>(json!({"rows": n})).unwrap().rows;
|
||||
assert_eq!(rows(1001), crate::cmd::newdoc::MAX_ARTBOARDS, "file.new takes the listed rows again");
|
||||
assert_eq!(rows(0), 0, "0 stays: columns in their place");
|
||||
assert_eq!(rows(12), 12, "more rows than artboards stay");
|
||||
}
|
||||
@@ -1017,7 +1017,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
|
||||
let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap());
|
||||
assert_eq!(plain.grid_columns(), spaced.grid_columns());
|
||||
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string();
|
||||
assert!(e.contains("rows must be 1 or more"), "{e}");
|
||||
assert!(e.contains("rows must be from 1 to 1000"), "{e}");
|
||||
for layout in ["gridByRow", "row", "column"] {
|
||||
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string();
|
||||
assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}");
|
||||
@@ -1074,6 +1074,22 @@ fn an_edit_keeps_direct_selected_anchors() {
|
||||
assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
|
||||
let anchors = s.active().unwrap().selection.anchors.clone();
|
||||
assert!(anchors.contains_key(&a));
|
||||
// Lists start with the topmost object, so `b` is `pageItems[0]`.
|
||||
log(&mut s, "app.activeDocument.pageItems[0].selected = false;");
|
||||
let sel = &s.active().unwrap().selection;
|
||||
assert_eq!((sel.objects.clone(), sel.anchors.clone()), (vec![a], anchors.clone()));
|
||||
log(&mut s, "app.activeDocument.pageItems[0].selected = true;");
|
||||
let sel = &s.active().unwrap().selection;
|
||||
assert_eq!((sel.objects.clone(), sel.anchors.get(&a)), (vec![a, b], anchors.get(&a)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_keeps_the_order_of_a_mixed_selection() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -1259,9 +1275,11 @@ fn a_startup_preset_alone_gives_its_first_size() {
|
||||
#[test]
|
||||
fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
|
||||
let (mut s, _, _) = doc();
|
||||
for source in
|
||||
["app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"]
|
||||
{
|
||||
for source in [
|
||||
"app.activeDocument.pageItems[0].isIsolated;",
|
||||
"app.activeDocument.pageItems[0].uuid = 'x';",
|
||||
"app.activeDocument.pageItems[0].transform(5);",
|
||||
] {
|
||||
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
|
||||
}
|
||||
assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet"));
|
||||
@@ -1443,6 +1461,16 @@ fn note_is_the_attributes_note() {
|
||||
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap();
|
||||
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);");
|
||||
assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]);
|
||||
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);");
|
||||
assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_preset_applies_only_its_given_fields() {
|
||||
let mut s = Session::new();
|
||||
@@ -1477,6 +1505,17 @@ fn document_preset_applies_only_its_given_fields() {
|
||||
assert!(e.contains(part), "{source}: {e}");
|
||||
}
|
||||
assert_eq!(s.documents().len(), 2, "a refused preset makes no document");
|
||||
// A saved preset with the built-in preset's name does not make the refused settings fit.
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "artboardLayout": "column"})).unwrap();
|
||||
// With the layout unset, the built-in preset puts the five 1,000,000 pt artboards in one row,
|
||||
// which does not fit, while the saved preset would put them in one column.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
"var p = new DocumentPreset(); p.width = 1000000; p.numArtboards = 5;\
|
||||
p.artboardLayout = undefined; p.artboardRowsOrCols = undefined; app.documents.addDocument('Print', p);",
|
||||
);
|
||||
assert!(e.contains("don't fit"), "{e}");
|
||||
assert_eq!(s.documents().len(), 2, "settings the built-in preset refuses make no document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2149,7 +2188,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('rotate'), d.hasOwnProperty('layers'),\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('transform'), d.hasOwnProperty('layers'),\
|
||||
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')]);",
|
||||
);
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//! The script object model's document defaults for new art and `scaleFactor`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::LineCap;
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
/// A 400 × 300 pt document with one rectangle, selected.
|
||||
fn doc() -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> crate::doc::Node {
|
||||
s.active().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wider_default_stroke_goes_to_the_next_path_drawn() {
|
||||
let (mut s, picked) = doc();
|
||||
let (look, steps) = (node(&s, picked).appearance, undo_steps(&s));
|
||||
let wider = s.paint.stroke_width + 1.0;
|
||||
let r = run(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth += 1; vc.log(d.defaultStrokeWidth);").unwrap();
|
||||
assert_eq!(r["log"][0].as_f64(), Some(wider));
|
||||
assert_eq!(undo_steps(&s), steps, "a default alone is no undo step");
|
||||
assert_eq!(node(&s, picked).appearance, look, "the selected path kept its stroke");
|
||||
assert_eq!(s.new_art().stroke().unwrap().width, wider);
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(200, 100, 50, 50); vc.log(p.strokeWidth);");
|
||||
assert_eq!(out.iter().map(Value::as_f64).collect::<Vec<_>>(), vec![Some(wider)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_default_throws_and_changes_nothing() {
|
||||
let (mut s, _) = doc();
|
||||
let before = s.paint.clone();
|
||||
for (source, name) in [
|
||||
("app.activeDocument.defaultStrokeWidth = -1", "RangeError"),
|
||||
("app.activeDocument.defaultStrokeWidth = 1001", "RangeError"),
|
||||
("app.activeDocument.defaultStrokeWidth = 'wide'", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeMiterLimit = 0", "RangeError"),
|
||||
("app.activeDocument.defaultStrokeCap = 'round'", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeJoin = 1", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeDashes = [0, 0]", "RangeError"),
|
||||
("app.activeDocument.defaultStrokeDashes = '4 2'", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeDashOffset = 3", "Error"),
|
||||
("app.activeDocument.defaultFillColor = 5", "TypeError"),
|
||||
("var c = new RGBColor(); c.red = 300; app.activeDocument.defaultStrokeColor = c", "RangeError"),
|
||||
("app.activeDocument.defaultFilled = 1", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeOverprint = 'yes'", "TypeError"),
|
||||
] {
|
||||
let out = log(&mut s, &format!("try {{ {source}; vc.log('ran'); }} catch (e) {{ vc.log(e.name); }}"));
|
||||
assert_eq!(out, vec![json!(name)], "{source}");
|
||||
assert_eq!(s.paint, before, "{source} changed new art");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_colors_and_flags_read_back_and_paint_the_next_path() {
|
||||
let (mut s, picked) = doc();
|
||||
let look = node(&s, picked).appearance;
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, c = new RGBColor(); c.red = 255;\
|
||||
d.defaultFillColor = c; vc.log(d.defaultFillColor.typename); vc.log(d.defaultFillColor.red); vc.log(d.defaultFilled);\
|
||||
d.defaultStroked = false; vc.log(d.defaultStroked); vc.log(d.defaultStrokeColor.typename);\
|
||||
d.defaultStrokeColor = new GrayColor(); vc.log(d.defaultStroked);\
|
||||
d.defaultFillColor = new NoColor(); vc.log(d.defaultFilled); d.defaultFilled = true; vc.log(d.defaultFilled);\
|
||||
d.defaultFillColor = c;",
|
||||
);
|
||||
assert_eq!(out, vec![json!("RGBColor"), json!(255), json!(true), json!(false), json!("NoColor"), json!(true), json!(false), json!(true)]);
|
||||
assert_eq!(node(&s, picked).appearance, look);
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
let ap = node(&s, id).appearance;
|
||||
assert_eq!(ap.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert!(!ap.stroke_paint().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_stroke_options_read_back_and_a_same_value_runs_no_command() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.defaultStrokeCap = StrokeCap.ROUNDENDCAP; d.defaultStrokeJoin = StrokeJoin.BEVELENDJOIN;\
|
||||
d.defaultStrokeMiterLimit = 7; d.defaultStrokeDashes = [6, 2]; d.defaultStrokeDashOffset = 1;\
|
||||
d.defaultStrokeOverprint = true; d.defaultFillOverprint = true;\
|
||||
vc.log([d.defaultStrokeCap, d.defaultStrokeJoin, d.defaultStrokeMiterLimit, d.defaultStrokeDashes, d.defaultStrokeDashOffset,\
|
||||
d.defaultStrokeOverprint, d.defaultFillOverprint]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["StrokeCap.ROUNDENDCAP", "StrokeJoin.BEVELENDJOIN", 7, [6, 2], 1, true, true])]);
|
||||
let st = s.new_art().stroke().unwrap().clone();
|
||||
assert_eq!((st.cap, st.miter_limit, st.overprint), (LineCap::Round, 7.0, true));
|
||||
let r = run(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.defaultStrokeCap = StrokeCap.ROUNDENDCAP; d.defaultStrokeMiterLimit = 7;\
|
||||
d.defaultStrokeDashes = [6, 2]; d.defaultStrokeOverprint = true; d.defaultStrokeWidth = d.defaultStrokeWidth;\
|
||||
d.defaultFillColor = d.defaultFillColor;",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["slowestCommands"], json!([]), "the same values run no command");
|
||||
// `{}` and `[]` give a solid line.
|
||||
assert_eq!(log(&mut s, "var d = app.activeDocument; d.defaultStrokeDashes = {}; vc.log(d.defaultStrokeDashes.length);"), vec![json!(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slightly_different_number_reaches_new_art() {
|
||||
let (mut s, _) = doc();
|
||||
log(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth = 1; d.defaultStrokeMiterLimit = 7; d.defaultStrokeDashes = [6, 2];");
|
||||
log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.defaultStrokeWidth = 1.0000000005; d.defaultStrokeMiterLimit = 7.0000000005;\
|
||||
d.defaultStrokeDashOffset = 0.0000000005;",
|
||||
);
|
||||
let st = s.new_art().stroke().unwrap().clone();
|
||||
assert_eq!(st.width, 1.000_000_000_5);
|
||||
assert_eq!(st.miter_limit, 7.000_000_000_5);
|
||||
assert_eq!(st.dash.map(|d| d.offset), Some(0.000_000_000_5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_rgb_default_in_a_cmyk_document_runs_no_command_the_second_time() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
let set = "var d = app.activeDocument, c = new RGBColor(); c.red = 200; c.green = 40; c.blue = 90; d.defaultFillColor = c;";
|
||||
let first = run(&mut s, set).unwrap();
|
||||
assert_ne!(first["slowestCommands"], json!([]), "the first assignment changes new art");
|
||||
let again = run(&mut s, set).unwrap();
|
||||
assert_eq!(again["slowestCommands"], json!([]), "the same RGB value runs no command");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_factor_is_one_and_read_only() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(&mut s, "var d = app.activeDocument; vc.log(d.scaleFactor); d.scaleFactor = 4; vc.log(d.scaleFactor);");
|
||||
assert_eq!(out, vec![json!(1), json!(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_refuse_while_new_art_takes_the_selected_look() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let before = s.paint.clone();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"try { app.activeDocument.defaultStrokeWidth = 9; } catch (e) { vc.log(e.message.indexOf('New Art Has Basic Appearance') >= 0); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true)]);
|
||||
assert_eq!(s.paint, before);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,7 @@ use std::cell::Cell;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_RESULT_BYTES};
|
||||
use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_GROWTH_BYTES, TEST_RESULT_BYTES};
|
||||
use crate::*;
|
||||
|
||||
fn rect(x: i64) -> Value {
|
||||
@@ -1371,6 +1371,54 @@ fn a_person_can_let_a_growing_run_go_on_or_stop_it() {
|
||||
assert_eq!(state(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() {
|
||||
// The point change waits in the object model until the script ends.
|
||||
let source = "app.activeDocument.pathItems[0].pathPoints[0].anchor = [3, -4];";
|
||||
let mut s = two_docs();
|
||||
let start = s.documents()[1].doc.clone();
|
||||
assert_eq!(run(&mut s, source).unwrap()["ok"], true);
|
||||
let added = start.retained_bytes_each(&s.documents()[1].doc).1 as u64;
|
||||
assert!(added >= 3, "{added}");
|
||||
// The change goes past this allowance and stays within twice it.
|
||||
TEST_GROWTH_BYTES.with(|g| g.set(Some(added * 2 / 3)));
|
||||
let run_to_the_question = |s: &mut Session| {
|
||||
s.script_frames = true;
|
||||
run(s, source).unwrap();
|
||||
for _ in 0..1_000 {
|
||||
if s.script_waiting() {
|
||||
break;
|
||||
}
|
||||
assert!(s.script_pump().is_none());
|
||||
}
|
||||
assert!(s.script_waiting());
|
||||
assert!(s.script_pump().is_none());
|
||||
assert!(s.script_running());
|
||||
};
|
||||
let mut s = two_docs();
|
||||
let before = state(&s);
|
||||
let undo = s.documents()[1].history.undo.len();
|
||||
run_to_the_question(&mut s);
|
||||
assert_eq!(state(&s), before);
|
||||
s.script_continue();
|
||||
assert!(!s.script_waiting());
|
||||
let done = s.script_pump().expect("the run ends once it may go on");
|
||||
assert_eq!(done.unwrap()["ok"], true);
|
||||
assert_eq!(s.documents()[1].history.undo.len(), undo + 1);
|
||||
assert_ne!(state(&s), before);
|
||||
|
||||
let mut s = two_docs();
|
||||
let before = state(&s);
|
||||
run_to_the_question(&mut s);
|
||||
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
|
||||
let ended = s.script_pump().expect("a stopped run ends");
|
||||
TEST_GROWTH_BYTES.with(|g| g.set(None));
|
||||
assert!(ended.is_err());
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "stopped");
|
||||
assert!(!s.script_running());
|
||||
assert_eq!(state(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() {
|
||||
TEST_GROWTH.with(|g| g.set(Some(20)));
|
||||
|
||||
@@ -83,7 +83,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"",
|
||||
"activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
|
||||
DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \
|
||||
Documents ElementPlacement Layer PageItem PageItems RulerUnits ScreenMode selection selection= Tag Tags View Views \
|
||||
Documents ElementPlacement Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType \
|
||||
PolarityValues RulerUnits ScreenMode selection selection= StrokeCap StrokeJoin Tag Tags Transformation View Views \
|
||||
ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
@@ -107,8 +108,13 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
|
||||
documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \
|
||||
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \
|
||||
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 groupItems \
|
||||
groupItems= height layers layers= name pageItems paragraphStyles parent pathItems rulerOrigin \
|
||||
rulerOrigin= rulerUnits saveAs saveAs= scaleFactor selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
@@ -129,6 +135,25 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
|
||||
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
|
||||
),
|
||||
("PathItems.", "prototype"),
|
||||
("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"),
|
||||
("PathItem.", "prototype"),
|
||||
(
|
||||
"PathItem.prototype.",
|
||||
"area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \
|
||||
filled= guides guides= length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \
|
||||
setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \
|
||||
strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \
|
||||
strokeWidth strokeWidth= stroked stroked= translate",
|
||||
),
|
||||
("PathPoints.", "prototype"),
|
||||
("PathPoints.prototype.", "add constructor index length parent removeAll typename"),
|
||||
("PathPoint.", "prototype"),
|
||||
(
|
||||
"PathPoint.prototype.",
|
||||
"anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \
|
||||
rightDirection= selected selected= typename",
|
||||
),
|
||||
("Tags.", "prototype"),
|
||||
("Tags.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("Tag.", "prototype"),
|
||||
@@ -150,8 +175,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed",
|
||||
),
|
||||
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
|
||||
("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"),
|
||||
("PointType.", "CORNER SMOOTH"),
|
||||
("PolarityValues.", "NEGATIVE POSITIVE"),
|
||||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||||
("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"),
|
||||
("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"),
|
||||
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
|
||||
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
(
|
||||
"",
|
||||
@@ -282,9 +313,11 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("TextFrame.prototype.", "contentVariable contentVariable="),
|
||||
];
|
||||
|
||||
/// The classes the host adds with nothing but a prototype and its constructor: the page item types.
|
||||
const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \
|
||||
PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem";
|
||||
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
|
||||
/// other than `PathItem`, and the color classes.
|
||||
const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \
|
||||
IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \
|
||||
SymbolItem cmykColor";
|
||||
|
||||
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
|
||||
/// own API, and what `vc.run` does depends on the command it runs.
|
||||
|
||||
+3
-2
@@ -846,11 +846,12 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
|
||||
## G6 Automation and scripting
|
||||
|
||||
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths and the other classes)
|
||||
- **Missing:** the rest of the document object model for scripts (layers, artboards, gradient stops and the other classes)
|
||||
and the `#engine` script directive (#1183 is open). Scripts have `app`, the open
|
||||
documents, new documents, each document's selection and its page items, its text frames with their text ranges and
|
||||
character and paragraph attributes, their links to each other and the stories they form, its character and
|
||||
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries.
|
||||
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries, and
|
||||
`Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms.
|
||||
File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
|
||||
runs a script in a named engine whose globals last between runs,
|
||||
File › Scripts lists the scripts of the Scripts folder, and
|
||||
|
||||
+106
-5
@@ -3079,7 +3079,8 @@ through `$`:
|
||||
a list of at most 10,000, `null` or `[]`. Any other value, `undefined` included (such as an index past the end
|
||||
of `pageItems`), throws a `TypeError`, and an object that cannot be selected throws `Cannot select`, each with
|
||||
nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or
|
||||
with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path,
|
||||
with `selected`. Assigning a page item's `selected` leaves the direct-selected anchors and segments of the other
|
||||
selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path,
|
||||
letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when
|
||||
the automation read roots allow its file, and that check can look the document's file up on disk. A path with
|
||||
`..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined`
|
||||
@@ -3094,7 +3095,100 @@ through `$`:
|
||||
layer, a document or the application does not have does not keep the value; it does not throw, except in
|
||||
strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. Other members
|
||||
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
|
||||
themselves, such as a path's fill, are not defined yet and read as `undefined`.
|
||||
themselves that this page does not describe are not defined yet and read as `undefined`.
|
||||
- `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the
|
||||
order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`,
|
||||
`getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new
|
||||
art has no fill and no stroke, the path has neither), and the shape creators
|
||||
`rectangle(top, left, width, height, reversed?)`, `roundedRectangle(top, left, width, height, horizontalRadius = 15,
|
||||
verticalRadius = 20, reversed?)`, `ellipse(top = 100, left = 100, width = 50, height = 100, reversed?, inscribed?)`,
|
||||
`polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed?)` and `star(centerX = 200, centerY = 300,
|
||||
radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`,
|
||||
`shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new
|
||||
art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing
|
||||
mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item
|
||||
members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`,
|
||||
`guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`,
|
||||
`stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to
|
||||
500), `strokeDashes`, `strokeDashOffset`, `translate(deltaX?, deltaY?, ...)`, `rotate(angle, ..., rotateAbout?)`
|
||||
(counterclockwise for a positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The
|
||||
geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the
|
||||
stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through
|
||||
`object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the
|
||||
points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one
|
||||
`path.setAnchors` before the script uses any other member or command, or the points of another path, and when the
|
||||
script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points
|
||||
read as the grid snaps them.
|
||||
`pathPoints`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and
|
||||
`removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`,
|
||||
`leftDirection` (the handle into the point), `rightDirection` (the handle out of it), `pointType`, `selected`,
|
||||
`parent` and `remove()`. Assigning `guides` makes the path a guide with `view.guides.make` (`true`) or a path again
|
||||
with `view.guides.release` (`false`), with the selection kept; a value that is not a boolean throws a `TypeError`.
|
||||
`PathPoint.selected` reads `PathPointSelection.ANCHORPOINT` for a selected anchor point and
|
||||
`PathPointSelection.NOSELECTION` otherwise; assigning `ANCHORPOINT` adds the point to the direct-selected anchors and
|
||||
`NOSELECTION` removes it, through `select.anchorsMany`, with the other selected objects and anchors kept.
|
||||
`selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `new RGBColor()` (0 to
|
||||
255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes
|
||||
the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues`
|
||||
and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`.
|
||||
VectorCraft's own rules: a point's index counts across the path's subpaths; `closed` is true when every subpath is
|
||||
closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner
|
||||
points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and
|
||||
`pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point
|
||||
whose index is past the end of its path throws `Stale path point`, and so does a point read before the script removed
|
||||
a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`), or before anything other
|
||||
than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`,
|
||||
`object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an
|
||||
object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point,
|
||||
and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole.
|
||||
Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT`
|
||||
to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a
|
||||
path in a selected group or compound path. Selecting a point of a path with selected segments replaces that path's
|
||||
segment selection. Changing `selected` adds no undo step. Selecting a point of a path that cannot be selected
|
||||
throws `Cannot select`, and selecting a point of a guide while guides are locked throws an error. A clipping path
|
||||
cannot be made a guide, and `guides = true` on one throws an error. Assigning `guides` the value a path already
|
||||
has runs no command. Assigning the other value throws an error that says it is not available yet on a path inside
|
||||
a compound path, throws `Cannot edit` on a path that is hidden, locked or cannot be selected, and throws an error
|
||||
while guides are locked. Color components left out count as 0, `new
|
||||
cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of
|
||||
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
|
||||
art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the
|
||||
stroke; 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.
|
||||
`fillOverprint` and `strokeOverprint` read and change the top fill or stroke only. Sizes and
|
||||
radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000,
|
||||
`strokeWidth` 0 to 1000 points (a `changeLineWidths` that would scale it past 1000 throws), `strokeDashes` at most
|
||||
64 lengths that are not all 0 (`[]` or `{}` for a solid line), and `rotateAbout` and `scaleAbout` default to
|
||||
`Transformation.CENTER`. A transform that leaves the path where it is, such as `rotate(360)` or
|
||||
`resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and
|
||||
`changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with
|
||||
`inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path
|
||||
that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing
|
||||
changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
|
||||
shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new
|
||||
art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity` and the gradient stops
|
||||
are not available yet.
|
||||
- A `Document`'s default paint members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set what
|
||||
the next object drawn gets, as `appearance.newArt` reports it, the same for every open document: `defaultFillColor`,
|
||||
`defaultFilled`, `defaultFillOverprint`, `defaultStrokeColor`, `defaultStroked`, `defaultStrokeOverprint`,
|
||||
`defaultStrokeWidth`, `defaultStrokeCap`, `defaultStrokeJoin`, `defaultStrokeMiterLimit`, `defaultStrokeDashes`
|
||||
(`[]` or `{}` for a solid line) and `defaultStrokeDashOffset`. Assigning one runs `appearance.setNewArt`, which
|
||||
leaves the selection, its art, the active Fill or Stroke proxy and Recent Colors as they were and adds no undo step.
|
||||
A value that changes nothing runs no command, and a bad value throws an error with nothing changed. VectorCraft's
|
||||
own rules: assigning a color also makes `defaultFilled` or `defaultStroked` true, and a `NoColor` makes it false;
|
||||
`defaultFilled` or `defaultStroked` set to true with no fill or stroke gives black; an RGB color is stored in the
|
||||
front document's color mode, as `paint.setFill` stores it; `defaultStrokeWidth` is 0 to 1000 points, a dash or gap 0
|
||||
to 1,000,000 points (at most 64, not all 0), and `defaultStrokeDashOffset` -1,000,000 to 1,000,000 points, which
|
||||
needs a dash pattern unless it is 0; while New Art Has Basic Appearance is off and an object is selected, assigning
|
||||
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.
|
||||
- `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
|
||||
@@ -10259,6 +10353,13 @@ colorized) changes nothing. With the option off (`appearance.setNewArtBasic {on:
|
||||
whole appearance of the last selected object. `appearance.newArt` reports what the next object gets; `paint.default`
|
||||
resets it.
|
||||
`appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference.
|
||||
`appearance.setNewArt {fill?, stroke?, weight?, cap?, join?, miterLimit?, dash?, dashOffset?, fillOverprint?,
|
||||
strokeOverprint?}` sets new art's fill, stroke and stroke options whatever is selected, and leaves the selection, its
|
||||
art, the active proxy and Recent Colors as they were. `fill` and `stroke` take a paint as `paint.setFill` does, and
|
||||
`tint` only with a global or spot `swatch`. Without `weight` the stored stroke weight stays; a stroke painted on new
|
||||
art without one gets 1 pt only when that stored weight is 0. Every value is checked before
|
||||
anything changes, and any change while New Art Has Basic Appearance is off and an object is selected is an error. It
|
||||
returns `{changed}`, false when the next object would look the same.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"select.none","params":{}}}
|
||||
@@ -10396,7 +10497,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes
|
||||
|
||||
`file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height`
|
||||
(points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns,
|
||||
rows, spacing, rightToLeft}` (`rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
|
||||
rows, spacing, rightToLeft}` (`rows`, 1 to 1000 and rounded to a whole number, gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
|
||||
an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are
|
||||
fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns
|
||||
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes),
|
||||
@@ -10600,8 +10701,8 @@ runs, as `document.open` reads its file when it runs. A file larger than 64 MiB
|
||||
When the file is a link or a folder, cannot be read, is too large or is not a native document, or the request's read
|
||||
roots leave out the folder (whether or not the file exists), the document starts with the defaults and
|
||||
`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and
|
||||
a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's
|
||||
file. The
|
||||
a script's `app.documents.addDocument` throws it. Reading the profile's file is not limited to the script's folder (the
|
||||
`File` and `Folder` rule in [Script engines](#script-engines)), but the request's automation read roots still apply. The
|
||||
reason given when the read roots leave out the folder does not name the folder's path. Color profiles the profile's
|
||||
file carries are installed when they are missing, as `document.open` installs them, and each one that can't be used
|
||||
adds a line to `file.new`'s `warnings`. The new document's links find their files through relative paths from the
|
||||
|
||||
@@ -1120,13 +1120,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
|
||||
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
|
||||
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`.
|
||||
|
||||
Reference in new issue
Block a user