Scripts: duplicate, selection and wrapper fixes for the object model

- duplicate() runs Edit > Duplicate, the place and the selection
  restore under one savepoint, so a refused place leaves the documents,
  the selection and the undo history as they were. It reads the copy's
  id from the command's own result, so ids above 2^53 return the copy.
  A path inside a compound path throws an error instead of copying the
  whole compound path.
- An edit restores a mixed selection (direct-selected anchors and whole
  objects) in its original order with one select.anchorsMany.
- Assigning the selection clears a Layers panel target.
- A call on an inactive document switches back even when the selection
  restore fails.
- documents.add with a grid by column passes the row count to file.new,
  which takes a new artboardLayout.rows key: 5 artboards in 4 rows give
  columns of 4 and 1. A preset keeps the rows until columns without
  rows, or another layout, is given, and New Document drops them when
  Columns or the layout changes.
- A held page item stays the same object when its class changes in the
  same family (a placed image that is embedded becomes a RasterItem).
- A waiting class member's answer is read as a class instance, and a
  class constructor called with new cannot wait.

Docs: docs/mcp.md (DocumentPreset, duplicate, file.new rows), docs/gaps.md
(G6).
This commit is contained in:
dotCooCoo committed 2026-11-21 08:43:10 -08:00
1 parent f2d3b09fe6
commit f70d2ee7e6
14 files changed
+408 -104

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
+48 -16
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Document Presets",
[],
None,
"{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one",
"{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, rows? (a grid by column made with rows), spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one",
always,
list
),
@@ -146,6 +146,11 @@ fn de_ppi<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D:
Ok(Some(f64::deserialize(d)?).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0))
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero(n: &u32) -> bool {
*n == 0
}
/// Everything New Document sets: a preset (built-in, saved or recent) or `file.new`'s params.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
@@ -166,6 +171,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")]
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).
#[serde(deserialize_with = "de_spacing")]
@@ -203,6 +211,7 @@ impl Default for DocSettings {
artboards: 1,
layout: ArtboardLayout::GridByRow,
columns: 0,
rows: 0,
spacing: 20.0,
right_to_left: false,
bleed: [0.0; 4],
@@ -222,9 +231,17 @@ pub const MAX_ARTBOARDS: u32 = 1000;
pub const RASTER_PPI: [(f64, &str); 3] = [(72.0, "Screen (72 ppi)"), (150.0, "Medium (150 ppi)"), (300.0, "High (300 ppi)")];
impl DocSettings {
/// The rows a grid by column with `rows` uses, at most one for each artboard.
fn grid_rows(&self) -> Option<usize> {
(self.layout == ArtboardLayout::GridByColumn && self.rows > 0).then(|| (self.rows as usize).min(self.artboards.max(1) as usize))
}
/// The columns a grid actually uses (0 or more than the artboards: one row).
pub fn grid_columns(&self) -> usize {
let n = self.artboards.max(1) as usize;
if let Some(rows) = self.grid_rows() {
return n.div_ceil(rows);
}
match self.layout {
ArtboardLayout::Row => n,
ArtboardLayout::Column => 1,
@@ -246,6 +263,11 @@ impl DocSettings {
/// As `file.newPresets` lists it (and `file.new` takes it back).
pub fn to_json(&self) -> Value {
let mut layout =
json!({"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left});
if let (Some(rows), Some(o)) = (self.grid_rows(), layout.as_object_mut()) {
o.insert("rows".into(), json!(rows));
}
json!({
"name": self.name,
"size": self.size_label(),
@@ -254,7 +276,7 @@ impl DocSettings {
"units": self.units.label(),
"orientation": self.orientation(),
"artboards": self.artboards,
"artboardLayout": {"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left},
"artboardLayout": layout,
"bleed": self.bleed,
"backgroundContents": self.background.id(),
"colorMode": color_mode_id(self.color_mode),
@@ -337,25 +359,23 @@ impl DocSettings {
Ok(self)
}
/// `artboardLayout: {layout?, columns?, spacing?, rightToLeft?}` or just a layout id.
/// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id.
fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> {
let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column");
if let Some(id) = l.as_str() {
self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?;
if self.layout != ArtboardLayout::GridByColumn {
self.rows = 0;
}
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 = 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
}
"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"))?,
"spacing" => {
self.spacing = v
.as_f64()
@@ -366,18 +386,30 @@ impl DocSettings {
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))),
}
}
if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn {
return Err(bad(cmd, "artboardLayout.rows needs the gridByColumn layout"));
}
// Columns without rows, or another layout, replace a preset's rows.
if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn {
self.rows = 0;
}
if self.grid_rows().is_some() {
self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX);
}
Ok(())
}
/// The artboard rectangles, the first at the origin's side.
/// The artboard rectangles, the first at the origin's side. A grid by column with `rows` has
/// that many rows (at most one for each artboard).
pub fn boards(&self) -> Vec<Rect> {
let n = self.artboards.max(1) as usize;
let sizes = vec![(self.width, self.height); n];
let by_column = self.layout == ArtboardLayout::GridByColumn;
grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left)
.into_iter()
.map(|o| Rect::from_origin_size(o, (self.width, self.height)))
.collect()
let origins = match self.grid_rows() {
Some(rows) => grid_origins_rc(&sizes, Point::ZERO, (rows, n.div_ceil(rows)), self.spacing, true, self.right_to_left),
None => grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left),
};
origins.into_iter().map(|o| Rect::from_origin_size(o, (self.width, self.height))).collect()
}
/// The new document (title and swatches set by `file.new`).
+87 -49
View File
@@ -35,7 +35,7 @@ use serde_json::{Value, json};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts};
use super::{Host, Link, command, current, data_size};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
use crate::{DocState, Document, NodeId, NodeKind, Session};
/// The error for a member read or called with no document open.
@@ -84,12 +84,41 @@ pub(super) enum Coords {
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
/// What the object model keeps for one run: its coordinate system and the last list of a
/// document's page items, kept while that document is unchanged.
/// What the object model keeps for one run: its coordinate system, the last list of a document's
/// page items, kept while that document is unchanged, and whether a call's own savepoint
/// ([`atomically`]) is open.
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
items: RefCell<Option<ItemList>>,
saving: Cell<bool>,
}
impl State {
/// Whether a call's own savepoint is open: its commands take none of their own.
pub(super) fn saving(&self) -> bool {
self.saving.get()
}
}
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
/// document, the selection and the undo histories are as they were before it, with no undo step
/// and no change to the document's saved state.
fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
if h.dom.saving.get() {
return f(h);
}
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
h.dom.saving.set(true);
let r = f(h);
h.dom.saving.set(false);
let mut s = h.session.borrow_mut();
if r.is_ok() {
save.keep(&mut s);
} else if !save.restore(&mut s) {
return Err(HostError::Abort(HISTORY_LOST.to_string()));
}
r
}
/// A document's uid, the document as it was, and the ids of its page items then.
@@ -414,9 +443,9 @@ fn coords_of(d: &Data) -> std::result::Result<Coords, HostError> {
}
/// Selects `before` again in the active document `doc` with the selection commands, so that the
/// journal holds the change: the whole objects, then the direct-selected anchors and segments, the
/// ruler guides and the key object, guide or anchor. Objects that are now deleted, hidden or
/// locked are left out.
/// journal holds the change: the objects in their order with their direct-selected anchors, then
/// the segments, the ruler guides and the key object, guide or anchor. Objects that are now
/// deleted, hidden or locked are left out.
fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> {
// Slices selected with the Slice Selection tool are the whole selection when there are any.
let slices: Vec<u64> = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect();
@@ -426,20 +455,25 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
}
let keep = |id: &NodeId| editable(doc, *id);
let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id);
let whole: Vec<u64> = before.objects.iter().filter(|i| keep(i) && !partial(i)).map(|i| i.0).collect();
if whole.is_empty() {
let kept: Vec<NodeId> = before.objects.iter().copied().filter(keep).collect();
if kept.is_empty() {
command(h, "select.none", &json!({}))?;
} else if !kept.iter().any(partial) {
command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::<Vec<_>>()}))?;
} else {
command(h, "select.set", &json!({"ids": whole}))?;
}
let items: Vec<Value> = before
.anchors
.iter()
.filter(|(i, _)| keep(i))
.map(|(i, a)| json!({"id": i.0, "anchors": a.iter().map(|(p, k)| [p, k]).collect::<Vec<_>>()}))
.collect();
if !items.is_empty() {
command(h, "select.anchorsMany", &json!({"items": items, "mode": "add"}))?;
// One `select.anchorsMany` selects every object in its order: a partly selected path with
// its anchors, a whole path with all of them and any other object with none.
let items: Vec<Value> = kept
.iter()
.map(|i| {
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
};
json!({"id": i.0, "anchors": anchors})
})
.collect();
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();
@@ -487,25 +521,26 @@ fn on_doc<T>(
command(h, "document.activate", &json!({"index": index}))?;
}
let r = f(h);
let mut restored = Ok(());
if keep_selection {
let doc = {
let s = h.session.borrow();
s.active().filter(|st| st.uid == uid && st.selection != before).map(|st| st.doc.clone())
};
if let Some(doc) = doc {
let back = restore_selection(h, &doc, &before);
if r.is_ok() {
back?;
}
restored = restore_selection(h, &doc, &before);
}
}
if switch && let Some(a) = active {
let back = command(h, "document.activate", &json!({"index": a}));
if r.is_ok() {
back?;
}
}
r
// The document that was active is active again before any error is given: `f`'s error first,
// then the selection's, then the switch back's.
let back = match active {
Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop),
_ => Ok(()),
};
let v = r?;
restored?;
back?;
Ok(v)
}
/// Runs `id` with `params` on the item's document, its selection kept.
@@ -707,10 +742,9 @@ impl NewDoc<'_> {
if n.fract() != 0.0 || n < 1.0 || n > count {
return Err(HostError::Range("artboardRowsOrCols must be a whole number from 1 to numArtBoards".into()));
}
// A grid filled by column takes the number of rows; `file.new` takes columns.
// A grid filled by column takes the number of rows.
let by_column = layout.get("layout").is_some_and(|l| l == "gridByColumn");
let columns = if by_column { (count / n).ceil() } else { n };
layout.insert("columns".into(), json!(columns));
layout.insert((if by_column { "rows" } else { "columns" }).into(), json!(n));
}
if !layout.is_empty() {
p.insert("artboardLayout".into(), Value::Object(layout));
@@ -1020,11 +1054,12 @@ fn doc_set_selection(h: &Host, a: &[Data]) -> Answer {
}
/// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each
/// selected as a whole, and no ruler guide, slice or key.
/// selected as a whole, and no ruler guide, slice, key or Layers panel target.
fn set_selection(h: &Host, doc: Doc, ids: Vec<NodeId>) -> Answer {
let same = with_doc(h, doc, |_, st| {
let sel = &st.selection;
sel.objects == ids
&& sel.target.is_none()
&& sel.anchors.is_empty()
&& sel.segments.is_empty()
&& sel.guides.is_empty()
@@ -1502,11 +1537,21 @@ fn item_move(h: &Host, a: &[Data]) -> Answer {
Ok(arg(a, 0).clone())
}
/// The error of `duplicate` on a path inside a compound path.
pub const COMPOUND_MEMBER: &str = "Duplicating a path inside a compound path is not available yet";
/// `duplicate(relativeObject?, insertionLocation?)`: a copy of the item, directly above it as
/// Edit › Duplicate makes one, or into or beside `relativeObject` as `move` puts it. → the copy.
/// When `node.move` refuses the place, the copy is deleted and the error is thrown.
/// When `node.move` refuses the place, the copy and every change it made are put back, and the
/// error is thrown.
fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let in_compound = with_doc(h, item.doc, |_, st| {
st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }))
});
if in_compound {
return Err(HostError::Error(COMPOUND_MEMBER.into()));
}
let to = match arg(a, 1) {
Data::Undefined => {
if !matches!(arg(a, 2), Data::Undefined) {
@@ -1516,21 +1561,14 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
}
target => Some(destination(h, item, target, arg(a, 2), true)?),
};
let r = edit_item(h, item, "edit.duplicate", &json!({"ids": [item.id.0]}))?;
let id = match &r {
Data::Object(o) => o.iter().find(|(k, _)| k == "ids").and_then(|(_, v)| match v {
Data::Array(ids) => ids.first().and_then(|d| if let Data::Number(n) = d { whole(*n) } else { None }),
_ => None,
}),
_ => None,
};
let id = id.ok_or_else(|| HostError::Error("the copy was not made".into()))?;
if let Some(to) = to
&& let Err(e) = place(h, item.doc, NodeId(id), &to)
{
edit_item(h, item, "edit.clear", &json!({"ids": [id]}))?;
return Err(e);
}
let id = atomically(h, |h| {
let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?;
let id = made["ids"].get(0).and_then(Value::as_u64).ok_or_else(|| HostError::Error("the copy was not made".into()))?;
if let Some(to) = to {
place(h, item.doc, NodeId(id), &to)?;
}
Ok(id)
})?;
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
Ok(item_ref(h, st, NodeId(id)))
+8 -2
View File
@@ -1237,7 +1237,8 @@ fn note_ids(s: &mut Session) {
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<Savepoint>)> {
raise_ids(s);
let mutating = waits_for_tool_edit(id);
let save = mutating.then(|| Savepoint::take(s, id));
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back.
let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id));
let before: Vec<(u64, Arc<crate::Document>, u64)> =
if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() };
crate::file_access::start_recording_writes();
@@ -1303,6 +1304,11 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
/// transaction, its growth is counted, and a command that fails, or whose result cannot cross to
/// the script, is put back. → its result.
fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
command_value(host, id, params).map(|(data, _)| data)
}
/// [`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> {
let id = id.to_string();
let params = params.clone();
let session = host.session.clone();
@@ -1340,7 +1346,7 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
return Err(HostError::Abort(HISTORY_LOST.to_string()));
}
}
crossed
crossed.map(|data| (data, value))
}
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
+2 -1
View File
@@ -160,7 +160,8 @@ fn ppi_overprint_preview_and_bad_params() {
json!({"previewMode": "xray"}),
json!({"artboardLayout": {"layout": "spiral"}}),
json!({"artboardLayout": {"columns": 0}}),
json!({"artboardLayout": {"rows": 2}}),
json!({"artboardLayout": {"rows": 0}}),
json!({"artboardLayout": {"tiles": 2}}),
json!({"units": "furlongs"}),
json!({"width": 160000, "artboards": 1000}),
] {
+131 -7
View File
@@ -327,6 +327,7 @@ fn a_copy_that_cannot_be_placed_is_deleted() {
s.execute("text.create", &json!({"x": 200, "y": 200, "text": "Hi"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let before = format!("{:?}", s.active().unwrap().doc.layers);
let (steps, step) = (undo_steps(&s), s.active().unwrap().history.step());
// A Live Paint group takes no type, so the copy is refused after it was made.
let out = log(
&mut s,
@@ -337,13 +338,50 @@ fn a_copy_that_cannot_be_placed_is_deleted() {
assert!(out[0].as_str().is_some_and(|m| m.contains("Live Paint takes paths")), "{out:?}");
assert_eq!(out[1], json!(true));
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
// The refused copy leaves no undo step and does not change the document's step.
assert_eq!((undo_steps(&s), s.active().unwrap().history.step()), (steps, step));
}
#[test]
fn a_path_inside_a_compound_path_is_not_duplicated() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let before = format!("{:?}", s.active().unwrap().doc.layers);
let steps = undo_steps(&s);
let e = failure(&mut s, "var p = app.activeDocument.pageItems; vc.log(p[0].typename); p[1].duplicate();");
assert!(e.contains("Duplicating a path inside a compound path is not available yet"), "{e}");
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
// The compound path itself is copied whole.
let out = log(&mut s, "var p = app.activeDocument.pageItems, c = p[0].duplicate(); vc.log([c.typename, p.length]);");
assert_eq!(out, vec![json!(["CompoundPathItem", 6])]);
}
#[test]
fn a_copy_of_an_object_with_a_large_id_is_the_copy() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
// The copy's id, 2^53 + 1, is not exact as a number.
let big = 1u64 << 53;
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
assert_eq!(a.0, big);
let out = log(&mut s, "var i = app.activeDocument.pageItems[0], c = i.duplicate(); c.name = 'copy'; vc.log(c === i); vc.log(i.name);");
assert_eq!(out, vec![json!(false), json!("")]);
let d = &s.active().unwrap().doc;
assert_eq!(d.node(NodeId(big + 1)).and_then(|n| n.name.clone()).as_deref(), Some("copy"));
assert_eq!(d.node(a).unwrap().name, None);
}
#[test]
fn a_grid_by_column_takes_the_number_of_rows() {
let mut s = Session::new();
for (layout, rows, cols) in [("GridByCol", 2, 3), ("RLGridByCol", 2, 3), ("GridByRow", 3, 2)] {
run(&mut s, &format!("app.documents.add(DocumentColorSpace.RGB, 100, 100, 6, DocumentArtboardLayout.{layout}, 10, 2);")).unwrap();
// With five artboards in four rows, the columns hold four and one.
for (layout, count, given, rows, cols) in
[("GridByCol", 6, 2, 2, 3), ("RLGridByCol", 6, 2, 2, 3), ("GridByRow", 6, 2, 3, 2), ("GridByCol", 5, 4, 4, 2), ("RLGridByCol", 5, 4, 4, 2)]
{
run(&mut s, &format!("app.documents.add(DocumentColorSpace.RGB, 100, 100, {count}, DocumentArtboardLayout.{layout}, 10, {given});")).unwrap();
let boards = &s.active().unwrap().doc.artboards;
let distinct = |mut v: Vec<i64>| {
v.sort_unstable();
@@ -352,7 +390,43 @@ fn a_grid_by_column_takes_the_number_of_rows() {
};
let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect());
let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect());
assert_eq!((tops, lefts), (rows, cols), "{layout}");
assert_eq!((tops, lefts), (rows, cols), "{layout} {count}");
}
}
#[test]
fn file_new_takes_the_rows_of_a_grid_by_column() {
let mut s = Session::new();
let first_column = |s: &mut Session, layout: Value| {
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": layout})).unwrap();
let boards = &s.active().unwrap().doc.artboards;
boards.iter().filter(|b| b.rect.x0.round() as i64 == boards[0].rect.x0.round() as i64).count()
};
assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4})), 4);
// Rows take the place of columns given beside them.
assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4, "columns": 1})), 4);
// A preset keeps and lists the rows, with the columns they give.
use crate::cmd::newdoc::{ArtboardLayout, DocSettings};
let settings = DocSettings { artboards: 5, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() };
let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap();
let listed = settings.to_json();
assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(2), &json!(4)), "{listed}");
let stored: DocSettings = serde_json::from_value(serde_json::to_value(&settings).unwrap()).unwrap();
assert_eq!(stored.rows, 4);
// More artboards keep the rows; columns alone, or another layout, replace them.
let more = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap();
assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4);
let by_columns = stored.clone().with_params(&json!({"artboardLayout": {"columns": 1}}), "file.new").unwrap();
assert_eq!((by_columns.rows, by_columns.boards().iter().filter(|b| b.x0 == by_columns.boards()[0].x0).count()), (0, 5));
for layout in [json!({"layout": "gridByRow"}), json!("gridByRow")] {
let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap();
assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}");
}
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}");
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}");
}
}
@@ -390,6 +464,47 @@ fn an_edit_keeps_direct_selected_anchors() {
assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore");
}
#[test]
fn an_edit_keeps_the_order_of_a_mixed_selection() {
let (mut s, a, b) = doc();
rect(&mut s, 200.0, 200.0, 20.0, 20.0);
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
let before = s.active().unwrap().selection.clone();
assert_eq!(before.objects, vec![a, b]);
log(&mut s, "app.activeDocument.pageItems[2].duplicate();");
let sel = &s.active().unwrap().selection;
assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors));
}
#[test]
fn assigning_the_selection_clears_a_layers_panel_target() {
let (mut s, a, _) = doc();
s.execute("layer.target", &json!({"id": a.0})).unwrap();
assert_eq!(s.active().unwrap().selection.target, Some(a));
log(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[0];");
let sel = &s.active().unwrap().selection;
assert_eq!((sel.objects.clone(), sel.target), (vec![a], None));
}
#[test]
fn a_held_image_stays_the_same_object_when_it_is_embedded() {
let dir = super::links::Folder::new("dom-embed");
let photo = dir.file("photo.png");
super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0]));
let mut s = super::links::session();
let id = super::links::place(&mut s, &photo);
let out = log(
&mut s,
&format!(
"var i = app.activeDocument.pageItems[0]; vc.log(i.typename); vc.run('links.embed', {{ids: [{}]}});\
var j = app.activeDocument.pageItems[0]; vc.log([i === j, i.typename, i instanceof RasterItem, i instanceof PlacedItem]);",
id.0
),
);
assert_eq!(out, vec![json!("PlacedItem"), json!([true, "RasterItem", true, false])]);
}
#[test]
fn an_edit_keeps_the_key_object() {
let (mut s, a, b) = doc();
@@ -630,8 +745,16 @@ fn get_is_file_open_cannot_probe_outside_script_scope() {
let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id()));
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let p = path.to_string_lossy().replace('\\', "\\\\");
let out = log(&mut s, &format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"));
let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));");
let out = log(&mut s, &query);
assert_eq!(out, vec![json!(true), json!(false)]);
// Read roots that leave out the document's file: the same path does not count.
let elsewhere = std::env::temp_dir().join(format!("vc-dom-roots-{}", std::process::id()));
std::fs::create_dir_all(&elsewhere).unwrap();
let roots = crate::file_access::AutomationRoots::new(&[&elsewhere], &[]).unwrap().unwrap();
let out = crate::file_access::confine(Some(&roots), || log(&mut s, &query));
assert_eq!(out, vec![json!(false), json!(false)]);
let _ = std::fs::remove_dir_all(&elsewhere);
for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] {
assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}");
}
@@ -647,12 +770,13 @@ fn hostile_dom_values_do_not_reenter_or_exceed_limits() {
let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['PathItem', 0, 1, 1]; app.activeDocument.selection = f;");
assert!(e.contains("not plain data"), "{e}");
// A getter in a value is refused before it runs.
let e = failure(
let out = log(
&mut s,
"var hit = 0, v = {}; Object.defineProperty(v, 0, {get: function () { hit++; return 1; }, enumerable: true});\
try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(hit); throw e; }",
try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(e.message); } vc.log(hit);",
);
assert!(e.contains("rulerOrigin"), "{e}");
assert!(out[0].as_str().is_some_and(|m| m.contains("rulerOrigin")), "{out:?}");
assert_eq!(out[1], json!(0));
let e = failure(&mut s, "var a = []; for (var i = 0; i < 10001; i++) a.push(app.activeDocument.pageItems[0]); app.activeDocument.selection = a;");
assert!(e.contains("at most 10000"), "{e}");
assert_eq!(s.active().unwrap().selection.objects, before);
+4 -2
View File
@@ -407,8 +407,9 @@ impl Interp {
}
_ => self.read_args(name, args, how)?,
};
// Only the script's own code, in a run that can pause, can wait for a result.
let can_wait = self.in_slice && self.reentry == 0;
// Only the script's own code, in a run that can pause, can wait for a result, and a host
// class's constructor called with `new` cannot.
let can_wait = self.in_slice && self.reentry == 0 && !self.constructing;
self.can_wait.set(can_wait);
let result = f(data);
self.can_wait.set(false);
@@ -417,6 +418,7 @@ impl Interp {
Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)),
Err(HostError::Wait) if can_wait => {
self.waiting = true;
self.waiting_hosted = matches!(how, ArgRead::Hosted);
self.pause.set(true);
Ok(Value::Undefined)
}
+30 -14
View File
@@ -8,7 +8,9 @@
//! object a script made that carries [`HOST_REF_KEY`] is refused, so a script cannot make an object
//! of a host class from its own data. A class's prototype and constructor are frozen. While a
//! script holds the object for a class and handle, each read of that class and handle gives the
//! same object.
//! same object. Classes that descend from the same class without a parent share their objects: a
//! read of another of them with the same handle gives the object the script holds, now of the
//! class that read names.
//!
//! Every member function gets the object it is called on (`this`) as its first argument, or
//! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a
@@ -67,6 +69,9 @@ pub(crate) struct Entry {
proto: ObjId,
ctor: ObjId,
index: Option<HostFunction>,
/// The class without a parent this class descends from (itself for such a class), as an index
/// into the realm's classes.
family: u32,
}
impl Entry {
@@ -75,24 +80,26 @@ impl Entry {
}
}
/// A class, as an index into the realm's classes, and the bits of a handle.
/// A family of classes ([`Entry::family`]) and the bits of a handle.
type MadeKey = (u32, Box<[u64]>);
/// The object made for each class and handle ([`Interp::host_objects`]).
/// The object made for each family of classes and handle ([`Interp::host_objects`]).
pub(crate) type Made = std::collections::HashMap<MadeKey, ObjId>;
/// Whether `id` is still the object made for `key`, and not a freed cell or another object that
/// was given its cell.
fn is_made(heap: &crate::heap::Heap, id: ObjId, key: &MadeKey) -> bool {
fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey) -> bool {
heap.object(id).is_some_and(|o| match &o.class {
Class::Host(h) => h.class == key.0 && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied()),
Class::Host(h) => {
classes.get(h.class as usize).is_some_and(|e| e.family == key.0) && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied())
}
_ => false,
})
}
/// Drops the entries of `made` whose objects the last collection freed.
pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap) {
made.retain(|key, id| is_made(heap, *id, key));
pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap, classes: &[Entry]) {
made.retain(|key, id| is_made(heap, classes, *id, key));
}
/// The [`Data`] that stands for the object of host class `class` with `handle`.
@@ -132,12 +139,20 @@ impl Interp {
let Some((class, entry)) = self.host_classes.iter().enumerate().find(|(_, e)| &*e.name == name) else {
return Err(self.throw(ErrorType::Type, &format!("a host value names the unknown class {name}")));
};
let proto = entry.proto;
let (proto, family) = (entry.proto, entry.family);
let class = u32::try_from(class).unwrap_or(u32::MAX);
let made = (class, handle.iter().map(|n| n.to_bits()).collect::<Box<[u64]>>());
let made = (family, handle.iter().map(|n| n.to_bits()).collect::<Box<[u64]>>());
if let Some(&id) = self.host_objects.get(&made)
&& is_made(&self.heap, id, &made)
&& is_made(&self.heap, &self.host_classes, id, &made)
{
// An object of another class of the family becomes one of `class`.
let o = self.object_mut(id)?;
if let Class::Host(h) = &mut o.class
&& h.class != class
{
h.class = class;
o.proto = Some(proto);
}
return Ok(Value::Object(id));
}
self.reserve_heap(crate::heap::OBJECT_BYTES)?;
@@ -207,10 +222,11 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
if i.host_classes.iter().any(|e| *e.name == *class.name) {
return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name)));
}
let parent = match &class.parent {
None => i.intrinsics.object_proto,
let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX);
let (parent, family) = match &class.parent {
None => (i.intrinsics.object_proto, own),
Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) {
Some(e) => e.proto,
Some(e) => (e.proto, e.family),
None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))),
},
};
@@ -220,7 +236,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
let r = fill_class(i, proto, &class);
i.temp_roots.truncate(mark);
let ctor = r?;
i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index });
i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family });
let global = i.global;
i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
}
+40
View File
@@ -636,6 +636,46 @@ fn a_host_function_that_waits_where_it_cannot_ends_the_run() {
assert_eq!(e.kind, RunErrorKind::Internal);
}
/// The host class `Thing` with the method `fetch`, which waits for its answer where it can, the
/// getter `id`, the first number of the object's handle, and the constructor `make`; and the
/// global `thing`, the `Thing` with the handle `[1]`.
fn with_thing(r: &mut Realm, make: Option<HostFunction>) {
let can_wait = r.wait_flag();
let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) });
let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number)));
let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))];
let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make };
r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap();
}
#[test]
fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() {
let mut r = realm(1_000_000);
with_thing(&mut r, None);
r.start("var t = thing.fetch(), u = thing.fetch(); [t instanceof Thing, t.id, t === u, t === thing].join()").unwrap();
for _ in 0..2 {
assert_eq!(r.advance(1_000).unwrap(), Progress::Paused);
assert!(r.waits());
r.answer(host_ref("Thing", &[2.0])).unwrap();
}
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into()));
}
#[test]
fn a_host_class_constructor_called_with_new_cannot_wait() {
let mut r = realm(1_000_000);
let could: Rc<Cell<Option<bool>>> = Rc::default();
let (seen, can_wait) = (could.clone(), r.wait_flag());
let make: HostFunction = Rc::new(move |_| {
seen.set(Some(can_wait.get()));
if can_wait.get() { Err(HostError::Wait) } else { Ok(Data::Object(Vec::new())) }
});
with_thing(&mut r, Some(make));
r.start("var c = new Thing(); c instanceof Thing").unwrap();
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true));
assert_eq!(could.get(), Some(false));
}
#[test]
fn a_converted_function_reads_each_argument_as_its_list_says() {
let mut r = realm(1_000_000);
+14 -4
View File
@@ -257,7 +257,7 @@ pub(crate) struct Interp {
pub(crate) host_classes: Vec<crate::host_classes::Entry>,
/// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`].
pub(crate) write_hosted: bool,
/// The object made for each class and handle ([`crate::host_classes`]), so that two reads of
/// The object made for each family of classes and handle ([`crate::host_classes`]), so that two reads of
/// the same one give the same object. It is not a root: an entry whose object was collected is
/// dropped after each collection.
pub(crate) host_objects: crate::host_classes::Made,
@@ -281,6 +281,11 @@ pub(crate) struct Interp {
pub(crate) can_wait: Rc<std::cell::Cell<bool>>,
/// A host function's call waits for its result: the value on top of the stack stands in for it.
pub(crate) waiting: bool,
/// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its
/// answer is read as such a member's result is ([`Interp::write_hosted`]).
pub(crate) waiting_hosted: bool,
/// A host class's constructor runs with `new`: it may not wait for its result.
pub(crate) constructing: bool,
/// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before
/// the next instruction runs.
pub(crate) resuming: Option<Resumption>,
@@ -538,6 +543,8 @@ impl Interp {
in_slice: false,
can_wait: Rc::default(),
waiting: false,
waiting_hosted: false,
constructing: false,
resuming: None,
host_abort: None,
data_limits: crate::DataLimits::default(),
@@ -788,7 +795,7 @@ impl Interp {
roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects));
roots.envs.push(self.global_env);
self.heap.collect(&roots);
crate::host_classes::forget_collected(&mut self.host_objects, &self.heap);
crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes);
// The collection counts the live total again, so bytes already released are not in it.
self.held.released.set(0);
self.flattened.set(0);
@@ -2392,11 +2399,14 @@ impl Interp {
}
// A host class's constructor ([`crate::host_classes`]) gives the object it makes. A plain
// object it gives inherits from the class's prototype. The class's other functions are
// not constructors.
// not constructors. A constructor called with `new` cannot wait for its result.
Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted })
if f.as_object().is_some_and(|o| self.is_host_constructor(o)) =>
{
let v = self.call_data(&host, &name, &Value::Undefined, &args, &read)?;
let was = std::mem::replace(&mut self.constructing, true);
let v = self.call_data(&host, &name, &Value::Undefined, &args, &read);
self.constructing = was;
let v = v?;
if let (Some(callee), Value::Object(o)) = (f.as_object(), &v)
&& matches!(self.object(*o)?.class, Class::Ordinary)
&& let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))?
+8 -1
View File
@@ -255,6 +255,8 @@ impl Realm {
interp.last_error = Value::Null;
interp.host_abort = None;
interp.waiting = false;
interp.waiting_hosted = false;
interp.constructing = false;
interp.resuming = None;
interp.error_tag = UNKNOWN_SOURCE;
interp.thrown_mark = None;
@@ -291,6 +293,8 @@ impl Realm {
interp.temp_roots.clear();
interp.join_stack.clear();
interp.waiting = false;
interp.waiting_hosted = false;
interp.constructing = false;
interp.resuming = None;
interp.passing = Value::Undefined;
match result {
@@ -406,8 +410,11 @@ impl Realm {
});
}
interp.waiting = false;
// A member of a host class gets its answer as it gets an immediate result.
let hosted = std::mem::take(&mut interp.waiting_hosted);
// The value on top of the stack stood in for the result.
let r = interp.write_data(d, 0, false).and_then(|v| {
let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) };
let r = written.and_then(|v| {
interp.stack.pop();
interp.push(v)
});
@@ -245,8 +245,13 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) {
)
}
/// Sets one artboard layout field. A new layout or column count replaces the rows of a preset
/// made with `file.new`'s `rows`.
fn set_layout(d: &mut Dialog, key: &str, v: Value) {
let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) {
o.remove("rows");
}
l[key] = v;
d.fields.insert("artboardLayout".into(), l);
}
@@ -890,6 +895,21 @@ mod tests {
app.ui.dialog.as_ref().unwrap().fields.get(k).cloned().unwrap_or_default()
}
/// A preset's rows stay until Columns or the layout changes.
#[test]
fn a_new_column_count_replaces_a_presets_rows() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.newDialog", json!({})).unwrap();
set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 4}));
super::set_layout(app.ui.dialog.as_mut().unwrap(), "spacing", json!(5.0));
assert_eq!(field(&app, "artboardLayout")["rows"], json!(4));
super::set_layout(app.ui.dialog.as_mut().unwrap(), "columns", json!(3));
assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 3, "spacing": 5.0}));
set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4}));
super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow"));
assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"}));
}
/// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of
/// their own orientations, and only the chosen one is selected (#2860).
#[test]
+3 -2
View File
@@ -807,8 +807,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
## G6 Automation and scripting
- **Missing:** the document object model for scripts and the `#engine` script directive (#1183 is
open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type 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. 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
Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and
+12 -5
View File
@@ -2631,9 +2631,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot
`file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset
`file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()`
(https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset`
starts with the defaults that page gives; `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid`
throw an error that says they are not available yet, and `showOptionsDialog` true throws `Dialog unavailable`
with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`,
starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and
`transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when
the preset it is given holds one of them with a value other than `null`, and makes no document.
`showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`,
`width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source,
destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/)
has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each
@@ -2648,7 +2649,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot
document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a
group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER`
directly below it. An object of another document throws `Cross-document placement is not available`, and when
`node.move` refuses the place of a copy, `duplicate` deletes the copy and throws that error. The
`node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and
the undo history as they were before the call. `duplicate` on a path inside a compound path throws
`Duplicating a path inside a compound path is not available yet`. A script that holds a placed image keeps the
same object when the image is embedded: the next read gives that object, now a `RasterItem`. The
enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`,
`DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and
`DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`.
@@ -8847,7 +8851,10 @@ 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,
spacing, rightToLeft}`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's
rows, spacing, rightToLeft}` (`rows` 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 until `columns` without `rows`, or another layout, is given,
and New Document drops them when Columns or the layout changes),
`bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's
value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see
[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)).
`file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets,