mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 12:21:08 +01:00
Merge pull request #9019 from dotCooCoo/feat/scripts-api-d1a-app-documents
Scripts: app gives scripts the open documents, their selection and page items
This commit is contained in:
29 files changed
+5094
-85
No files matched your search
@@ -105,8 +105,9 @@ proptest = { workspace = true }
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
# How many times the symbol list is read to find symbols by name.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
|
||||
# How many times the symbol list is read to find symbols by name, and how many objects are
|
||||
# measured against locked artboards.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] }
|
||||
wat = { workspace = true }
|
||||
# Zstandard streams for the Illustrator editing data fuzz tests.
|
||||
ruzstd = { workspace = true }
|
||||
|
||||
@@ -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 is a link or a folder, 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
|
||||
),
|
||||
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected",
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -1224,6 +1224,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let guides = switch_or(p, "guides", false, "edit.clear")?;
|
||||
let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?;
|
||||
switch_or(p, "keepJoined", false, "edit.clear")?;
|
||||
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
|
||||
// An object of a symbol instance's art can't be removed from the instance alone.
|
||||
@@ -1257,8 +1258,11 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Clear", |d, sel| {
|
||||
let parents: Vec<_> =
|
||||
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect();
|
||||
let parents: Vec<_> = if keep_empty {
|
||||
Vec::new()
|
||||
} else {
|
||||
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect()
|
||||
};
|
||||
d.remove_many(&ids)?;
|
||||
for p in parents {
|
||||
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
|
||||
|
||||
@@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Current Layer",
|
||||
[],
|
||||
None,
|
||||
"{id} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. Not an undo step → {id, layer}",
|
||||
"{id, keepRows?: bool} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. `keepRows` true leaves the highlighted rows as they are. Not an undo step → {id, layer}",
|
||||
has_doc,
|
||||
set_current
|
||||
),
|
||||
@@ -642,10 +642,13 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn set_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.setCurrent";
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let keep_rows = switch_or(p, "keepRows", false, C)?;
|
||||
let st = s.doc_mut()?;
|
||||
let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?;
|
||||
st.active_layer = Some(layer);
|
||||
st.layer_rows = vec![id];
|
||||
if !keep_rows {
|
||||
st.layer_rows = vec![id];
|
||||
}
|
||||
st.revision += 1;
|
||||
Ok(json!({ "id": id.0, "layer": layer.0 }))
|
||||
}
|
||||
|
||||
@@ -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,12 @@ 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});
|
||||
// The rows as set, also when there are fewer artboards than rows.
|
||||
if let Some(o) = layout.as_object_mut().filter(|_| self.grid_rows().is_some()) {
|
||||
o.insert("rows".into(), json!(self.rows));
|
||||
}
|
||||
json!({
|
||||
"name": self.name,
|
||||
"size": self.size_label(),
|
||||
@@ -254,7 +277,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 +360,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 +387,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`).
|
||||
@@ -528,7 +561,7 @@ pub(crate) fn side_error(cmd: &str, units: Unit) -> crate::EngineError {
|
||||
bad(cmd, format!("width and height must be more than 0 and at most {limit}"))
|
||||
}
|
||||
/// Largest artboard spacing, points.
|
||||
const MAX_SPACING: f64 = 1.0e5;
|
||||
pub(crate) const MAX_SPACING: f64 = 1.0e5;
|
||||
|
||||
pub fn color_mode_id(m: ColorMode) -> &'static str {
|
||||
match m {
|
||||
@@ -968,20 +1001,29 @@ impl Session {
|
||||
|
||||
/// Profile `name`'s document, its file's path and a warning for each color profile the file
|
||||
/// carries that can't be used: `None` when it has no file (the shipped profile, the defaults),
|
||||
/// the reason when the request being served may not read it, or its file can't be read, is
|
||||
/// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads.
|
||||
/// the reason when the request being served may not read it, or its file is a link or a folder,
|
||||
/// can't be read, is larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft
|
||||
/// reads.
|
||||
fn read_profile(&self, name: &str) -> std::result::Result<Option<ReadProfile>, String> {
|
||||
let Some(path) = self.profile_path(name) else { return Ok(None) };
|
||||
let file = path.to_string_lossy().to_string();
|
||||
// Checked before the file is looked for, so a request that may not read the folder learns
|
||||
// nothing of its files, nor where the folder is.
|
||||
// A script's gate does not apply to reads of the app's own folder; the automation roots in
|
||||
// force still do.
|
||||
let denied = |_| PROFILE_DENIED.to_string();
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) {
|
||||
return Ok(None);
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?;
|
||||
let read = crate::file_access::app_folder_read(|| {
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
// A link is refused: the script's gate does not check where it leads.
|
||||
Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()),
|
||||
_ => {}
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some)
|
||||
})?;
|
||||
let Some(bytes) = read else { return Ok(None) };
|
||||
// The color profiles the file carries are installed where missing, as opening it installs
|
||||
// them, so the new document's assigned profiles draw and are saved with it.
|
||||
let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Anchor Points",
|
||||
[],
|
||||
None,
|
||||
"{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)",
|
||||
"{keepEmpty?: bool (keep a compound path left with no members)} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)",
|
||||
has_anchors,
|
||||
delete_anchors
|
||||
),
|
||||
@@ -1731,6 +1731,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: bool) -> Result<Value> {
|
||||
// `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step.
|
||||
let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?;
|
||||
let keep_empty = switch_or(p, "keepEmpty", false, "path.deleteAnchors")?;
|
||||
let st = s.doc()?;
|
||||
let sel = st.selection.anchors.clone();
|
||||
let segments = st.selection.segments.clone();
|
||||
@@ -1748,12 +1749,16 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
|
||||
.copied()
|
||||
.filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor)))
|
||||
.collect();
|
||||
// The compound paths that hold a deleted object; one left with no members goes too.
|
||||
let compounds: BTreeSet<NodeId> = whole_ids
|
||||
.iter()
|
||||
.chain(sel.keys())
|
||||
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
|
||||
.collect();
|
||||
// The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`.
|
||||
let compounds: BTreeSet<NodeId> = if keep_empty {
|
||||
BTreeSet::new()
|
||||
} else {
|
||||
whole_ids
|
||||
.iter()
|
||||
.chain(sel.keys())
|
||||
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
|
||||
.collect()
|
||||
};
|
||||
if !whole_ids.is_empty() {
|
||||
d.remove_many(&whole_ids)?;
|
||||
}
|
||||
|
||||
@@ -207,9 +207,16 @@ pub fn unconfined<T>(f: impl FnOnce() -> T) -> T {
|
||||
with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f))
|
||||
}
|
||||
|
||||
/// Run `f`, a read of a file in one of the app's own folders, with reads exempt from the gate of
|
||||
/// the script command this thread runs. Unlike [`unconfined`], the roots in force still apply.
|
||||
pub(crate) fn app_folder_read<T>(f: impl FnOnce() -> T) -> T {
|
||||
with_gate_reads_exempt(true, f)
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Are reads on this thread exempt from the gate of the script command it runs? Only inside an
|
||||
/// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]).
|
||||
/// [`unconfined`] or an [`app_folder_read`] entered after the gate was put in force
|
||||
/// ([`with_script_gate`]).
|
||||
static GATE_READS_EXEMPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -51,6 +51,7 @@
|
||||
pub mod console;
|
||||
pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod dom;
|
||||
pub mod include;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
@@ -799,6 +800,8 @@ struct Host {
|
||||
dollar: dollar::RunState,
|
||||
/// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it.
|
||||
args: RefCell<(Data, u64)>,
|
||||
/// The run's state of the script object model (`app`).
|
||||
dom: dom::State,
|
||||
/// The documents open when the run began as the person last left them, each with its own file
|
||||
/// and the file it was read from ([`crate::DocState::as_person_left`],
|
||||
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
|
||||
@@ -1072,7 +1075,7 @@ impl Host {
|
||||
}
|
||||
let bridge = self.bridge.get().saturating_add(bytes);
|
||||
self.bridge.set(bridge);
|
||||
if bridge > MAX_BRIDGE_BYTES {
|
||||
if bridge > bridge_bytes() {
|
||||
return Err(self.over(OVER_BRIDGE));
|
||||
}
|
||||
let n = self.calls_this_slice.get() + 1;
|
||||
@@ -1263,7 +1266,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();
|
||||
@@ -1332,6 +1336,20 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
|
||||
let bytes = args.iter().map(data_size).sum();
|
||||
host.charge_call(bytes)?;
|
||||
bump(&host.counts.vc_run);
|
||||
command(host, &id, ¶ms)
|
||||
}
|
||||
|
||||
/// Runs command `id` for the script as `vc.run` does, its call already charged: it joins the run's
|
||||
/// 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();
|
||||
let started = clock();
|
||||
let r = {
|
||||
@@ -1367,7 +1385,7 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
|
||||
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
|
||||
@@ -1603,10 +1621,10 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
|
||||
/// `e`'s message, with what to do about a failure that comes from a script written for another
|
||||
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
|
||||
fn explained(e: &RunError) -> String {
|
||||
const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"];
|
||||
const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"];
|
||||
let message = &e.message;
|
||||
let names_host_object =
|
||||
message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o)));
|
||||
let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next());
|
||||
let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f));
|
||||
if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object {
|
||||
format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)")
|
||||
} else {
|
||||
@@ -2084,6 +2102,7 @@ impl Session {
|
||||
eval_strict: Cell::new(None),
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
dom: dom::State::default(),
|
||||
run_docs: RefCell::new(
|
||||
self.docs
|
||||
.iter()
|
||||
@@ -2130,6 +2149,7 @@ impl Session {
|
||||
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
|
||||
.and_then(|()| {
|
||||
let r = realm.start(&expanded.source);
|
||||
@@ -2537,6 +2557,15 @@ fn growth_objects() -> u64 {
|
||||
GROWTH_OBJECTS
|
||||
}
|
||||
|
||||
/// The data a run may pass to and from commands.
|
||||
fn bridge_bytes() -> u64 {
|
||||
#[cfg(test)]
|
||||
if let Some(n) = TEST_BRIDGE_BYTES.with(Cell::get) {
|
||||
return n;
|
||||
}
|
||||
MAX_BRIDGE_BYTES
|
||||
}
|
||||
|
||||
/// The limits of a command's result on its way to the script.
|
||||
fn result_limits() -> DataLimits {
|
||||
#[cfg(test)]
|
||||
@@ -2554,6 +2583,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 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`].
|
||||
pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`].
|
||||
|
||||
@@ -176,6 +176,7 @@ mod scalestrokes;
|
||||
mod script_console;
|
||||
mod script_dialogs;
|
||||
mod script_dollar;
|
||||
mod script_dom;
|
||||
mod script_engines;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
|
||||
@@ -157,6 +157,13 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() {
|
||||
let n = rect(&mut s, 50.0);
|
||||
assert_eq!(parent(&s, n), Some(sub));
|
||||
assert!(s.execute("layer.setCurrent", &json!({"id": 9999})).is_err());
|
||||
// `keepRows` makes the layer current and leaves the highlighted rows.
|
||||
run(&mut s, "layer.setCurrent", json!({"id": b.0}));
|
||||
run(&mut s, "layer.setCurrent", json!({"id": c.0, "keepRows": true}));
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!((st.highlighted_rows(), st.current_layer()), (vec![b], Some(layer)));
|
||||
assert!(s.execute("layer.setCurrent", &json!({"id": a.0, "keepRows": 1})).is_err());
|
||||
assert_eq!(s.doc().unwrap().current_layer(), Some(layer), "a bad keepRows changes nothing");
|
||||
// Shift/Ctrl: several rows.
|
||||
run(&mut s, "layer.highlight", json!({"ids": [a.0, g.0], "mode": "set"}));
|
||||
run(&mut s, "layer.highlight", json!({"ids": [c.0], "mode": "add"}));
|
||||
|
||||
@@ -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}),
|
||||
] {
|
||||
@@ -1001,6 +1002,22 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_profile_that_is_a_link_is_not_followed() {
|
||||
let (mut s, dir) = with_profiles("link");
|
||||
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
|
||||
// A profile the folder held, moved out and linked back in.
|
||||
let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id()));
|
||||
std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap();
|
||||
let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap();
|
||||
assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}");
|
||||
assert!(r.get("profile").is_none(), "{r}");
|
||||
let _ = std::fs::remove_file(&outside);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_names_are_checked_and_editing_needs_the_folder() {
|
||||
let mut s = Session::new();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -165,7 +165,9 @@ fn an_error_names_the_script_its_place_and_kind() {
|
||||
assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)");
|
||||
let e = run(&mut s, "var = 1;").unwrap_err().to_string();
|
||||
assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}");
|
||||
assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`"));
|
||||
assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`"));
|
||||
// The application's members need no `app.`, so naming one alone is not an error.
|
||||
assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true);
|
||||
assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _"));
|
||||
assert_eq!(s.script_report().unwrap()["line"], 1);
|
||||
}
|
||||
@@ -204,7 +206,7 @@ fn failed_script_report_keeps_message_and_adds_origin() {
|
||||
assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}");
|
||||
}
|
||||
// The app's own reference error names the `vc` object; the same text a script threw does not.
|
||||
run(&mut s, "app.activeDocument;").unwrap_err();
|
||||
run(&mut s, "new Window('dialog');").unwrap_err();
|
||||
assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`"));
|
||||
assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in");
|
||||
// An error in code `eval` compiled keeps where its message came from.
|
||||
|
||||
@@ -41,7 +41,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
|
||||
/// The names the host adds that stay inside the document and the run, by the object that has them.
|
||||
/// Reading a file or a folder, a file dialog and a message to the person do not change anything
|
||||
/// outside it.
|
||||
/// outside it. The document model (`app`, its classes and the enumerations) acts on the open
|
||||
/// documents; `Document.saveAs` and `close` throw "not available yet".
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder UnitValue alert confirm localize prompt toSource"),
|
||||
("Object.prototype.", "toSource"),
|
||||
@@ -72,8 +73,70 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \
|
||||
getRelativeURI localizedName modified name parent path relativeURI resolve selectDlg toString",
|
||||
),
|
||||
(
|
||||
"",
|
||||
"activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
|
||||
DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \
|
||||
Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \
|
||||
selection selection= toString typename",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
"DocumentPreset.prototype.",
|
||||
"artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \
|
||||
colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \
|
||||
height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \
|
||||
toString transparencyGrid transparencyGrid= typename units units= width width=",
|
||||
),
|
||||
("Documents.", "prototype"),
|
||||
("Documents.prototype.", "add addDocument constructor getByName index length parent toString typename"),
|
||||
("Document.", "prototype"),
|
||||
(
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
|
||||
groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \
|
||||
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= toString \
|
||||
typename views views= width",
|
||||
),
|
||||
("Layer.", "prototype"),
|
||||
("Layer.prototype.", "constructor name toString typename"),
|
||||
("PageItems.", "prototype"),
|
||||
("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"),
|
||||
("PageItem.", "prototype"),
|
||||
(
|
||||
"PageItem.prototype.",
|
||||
"artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \
|
||||
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \
|
||||
left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
|
||||
position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= toString top top= transform \
|
||||
transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
|
||||
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
|
||||
),
|
||||
("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"),
|
||||
("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"),
|
||||
("DocumentColorSpace.", "CMYK RGB"),
|
||||
("DocumentPresetType.", "BasicCMYK BasicRGB Mobile Print Video Web"),
|
||||
("DocumentPreviewMode.", "DefaultPreview OverprintPreview PixelPreview"),
|
||||
("DocumentRasterResolution.", "HighResolution MediumResolution ScreenResolution"),
|
||||
(
|
||||
"DocumentTransparencyGrid.",
|
||||
"TransparencyGridBlue TransparencyGridDark TransparencyGridGreen TransparencyGridLight TransparencyGridMedium \
|
||||
TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed",
|
||||
),
|
||||
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
|
||||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
];
|
||||
|
||||
/// 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 TextFrame";
|
||||
|
||||
/// 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.
|
||||
const NOT_CHECKED: &str = "vc";
|
||||
@@ -93,6 +156,9 @@ const LIST: &str = r#"(function () {
|
||||
var globals = Object.getOwnPropertyNames(g);
|
||||
add(g, "");
|
||||
for (var i = 0; i < globals.length; i++) {
|
||||
// A global with a getter, such as `activeDocument`, is not read: it throws with no document open.
|
||||
var gd = Object.getOwnPropertyDescriptor(g, globals[i]);
|
||||
if (gd && gd.get) continue;
|
||||
var v = g[globals[i]];
|
||||
if (v !== null && (typeof v == "object" || typeof v == "function")) {
|
||||
add(v, globals[i] + ".");
|
||||
@@ -120,7 +186,8 @@ fn language_names() -> BTreeSet<String> {
|
||||
|
||||
fn table_names() -> BTreeSet<String> {
|
||||
let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}")));
|
||||
OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain([NOT_CHECKED.to_string()]).collect()
|
||||
let bare = BARE_CLASSES.split_whitespace().flat_map(|c| [c.to_string(), format!("{c}.prototype"), format!("{c}.prototype.constructor")]);
|
||||
OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain(bare).chain([NOT_CHECKED.to_string()]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -89,9 +89,9 @@ fn a_script_that_ends_well_passes() {
|
||||
fn a_failure_gives_its_kind_and_place() {
|
||||
let r = result(&mut session(), &source("var a = 1;\nvar = ;"));
|
||||
assert_eq!((r["ok"].clone(), r["kind"].clone(), r["line"].clone()), (json!(false), json!("syntax"), json!(2)));
|
||||
let r = result(&mut session(), &source("var d = app.activeDocument;"));
|
||||
let r = result(&mut session(), &source("var d = undefinedHost.activeDocument;"));
|
||||
assert_eq!(r["kind"], "thrown");
|
||||
assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: app"), "{r}");
|
||||
assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: undefinedHost"), "{r}");
|
||||
let r = result(&mut session(), &source("while (true) {}"));
|
||||
assert_eq!(r["kind"], "limit");
|
||||
assert!(r["fuelUsed"].as_u64().unwrap() <= FUEL);
|
||||
|
||||
@@ -293,7 +293,7 @@ fn get_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<Value> {
|
||||
}
|
||||
|
||||
fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<bool> {
|
||||
interp.has_property(o, &key_of(k))
|
||||
interp.has_property_indexed(o, &key_of(k))
|
||||
}
|
||||
|
||||
/// The estimated bytes a new element adds.
|
||||
@@ -559,7 +559,15 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
|
||||
fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some()))
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || is_host_member_pk(interp, o, &k)?))
|
||||
}
|
||||
|
||||
/// [`Interp::is_host_member`] for either kind of key: a Symbol never names a host member.
|
||||
fn is_host_member_pk(interp: &Interp, o: ObjId, k: &crate::symbol::PropKey) -> JsResult<bool> {
|
||||
match k {
|
||||
crate::symbol::PropKey::Str(name) => interp.is_host_member(o, name),
|
||||
crate::symbol::PropKey::Sym(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -578,7 +586,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
|
||||
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable())))
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || is_host_member_pk(interp, o, &k)?))
|
||||
}
|
||||
|
||||
// ---- Function ----
|
||||
|
||||
@@ -538,7 +538,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K
|
||||
keep(interp, &v);
|
||||
let name = Value::String(Str::from_rc(k.clone()));
|
||||
if let Value::Object(o) = v {
|
||||
let to_json = interp.get_from(o, &key("toJSON"), &v)?;
|
||||
let to_json = interp.get_property_only(o, &key("toJSON"), &v)?;
|
||||
if interp.is_callable(&to_json) {
|
||||
v = interp.call(&to_json, &v, std::slice::from_ref(&name))?;
|
||||
keep(interp, &v);
|
||||
|
||||
@@ -264,6 +264,8 @@ pub(crate) enum Class {
|
||||
},
|
||||
/// A `.( )` filter in progress.
|
||||
XmlFilter(Box<XmlFilterState>),
|
||||
/// An object of a class a host defined ([`crate::host_classes`]).
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
UnitValue(Box<crate::unit_value::Measure>),
|
||||
}
|
||||
@@ -332,7 +334,7 @@ impl Class {
|
||||
Class::XmlFilter(_) => "Object",
|
||||
Class::Math => "Math",
|
||||
Class::Json => "JSON",
|
||||
Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object",
|
||||
Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object",
|
||||
Class::Array { .. } => "Array",
|
||||
Class::Function(_) => "Function",
|
||||
Class::Error(_) => "Error",
|
||||
|
||||
+44
-7
@@ -113,6 +113,10 @@ pub(crate) enum ArgRead {
|
||||
Each(Rc<[Arg]>),
|
||||
/// None: the function is given the [`CallSite`] of the code that calls it, as three numbers.
|
||||
Site,
|
||||
/// A member of a host class ([`crate::host_classes`]): `this` first, then each argument as
|
||||
/// [`Data`], objects of host classes in them as [`crate::host_ref`] gives them; the objects of
|
||||
/// host classes in the result are made from theirs.
|
||||
Hosted,
|
||||
}
|
||||
|
||||
/// A member of an object the host adds to the global environment.
|
||||
@@ -188,6 +192,9 @@ struct Reading {
|
||||
ancestors: Vec<ObjId>,
|
||||
path: Vec<Step>,
|
||||
function: Rc<str>,
|
||||
/// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object
|
||||
/// that has [`crate::HOST_REF_KEY`] is refused.
|
||||
hosted: bool,
|
||||
}
|
||||
|
||||
impl Reading {
|
||||
@@ -258,6 +265,10 @@ impl Interp {
|
||||
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
|
||||
}
|
||||
let shape = match &self.object(id)?.class {
|
||||
Class::Host(_) if r.hosted => {
|
||||
return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into()));
|
||||
}
|
||||
Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")),
|
||||
Class::Array { length, .. } => Shape::Array(*length),
|
||||
Class::Ordinary => {
|
||||
let o = self.object(id)?;
|
||||
@@ -313,6 +324,9 @@ impl Interp {
|
||||
self.use_fuel()?;
|
||||
self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?;
|
||||
let name = String::from_utf16_lossy(&k);
|
||||
if r.hosted && name == crate::HOST_REF_KEY {
|
||||
return Err(self.data_error(r, ErrorType::Type, "is not plain data"));
|
||||
}
|
||||
r.path.push(Step::Name(k));
|
||||
let item = match prop {
|
||||
// A property holding `undefined` reads as one left out.
|
||||
@@ -348,6 +362,9 @@ impl Interp {
|
||||
Data::Array(items) => {
|
||||
self.write_container(items.into_iter().enumerate().map(|(i, d)| (Slot::Index(i), d)).collect(), true, depth, frozen)?
|
||||
}
|
||||
Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => {
|
||||
self.write_host_ref(&Data::Object(items))?
|
||||
}
|
||||
Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?,
|
||||
})
|
||||
}
|
||||
@@ -387,20 +404,32 @@ impl Interp {
|
||||
|
||||
/// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to
|
||||
/// the script.
|
||||
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, args: &[Value], how: &ArgRead) -> JsResult<Value> {
|
||||
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, this: &Value, args: &[Value], how: &ArgRead) -> JsResult<Value> {
|
||||
let data = match how {
|
||||
ArgRead::Site => site_data(self.call_site()),
|
||||
ArgRead::Hosted => {
|
||||
let this = match this {
|
||||
Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined),
|
||||
_ => Data::Undefined,
|
||||
};
|
||||
let mut data = vec![this];
|
||||
data.extend(self.read_args(name, args, how)?);
|
||||
data
|
||||
}
|
||||
_ => 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);
|
||||
match result {
|
||||
Ok(d) if matches!(how, ArgRead::Hosted) => self.write_hosted(d),
|
||||
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)
|
||||
}
|
||||
@@ -478,7 +507,15 @@ impl Interp {
|
||||
|
||||
/// The arguments of host function `name` as [`Data`], read as `how` says.
|
||||
fn read_args(&mut self, name: &Rc<str>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
|
||||
let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() };
|
||||
let mut reading = Reading {
|
||||
limits: self.data_limits,
|
||||
bytes: 0,
|
||||
entries: 0,
|
||||
ancestors: Vec::new(),
|
||||
path: Vec::new(),
|
||||
function: name.clone(),
|
||||
hosted: matches!(how, ArgRead::Hosted),
|
||||
};
|
||||
let args = match how {
|
||||
ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args),
|
||||
_ => args,
|
||||
@@ -486,14 +523,14 @@ impl Interp {
|
||||
let mut data = Vec::with_capacity(args.len());
|
||||
// A conversion can run the script's own `toString`, which may collect garbage.
|
||||
let mark = self.temp_roots.len();
|
||||
if !matches!(how, ArgRead::Data | ArgRead::Frozen) {
|
||||
if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) {
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
}
|
||||
let mut read = Ok(());
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX)));
|
||||
let d = match how {
|
||||
ArgRead::Data | ArgRead::Frozen | ArgRead::Site => self.read_data(a, &mut reading),
|
||||
ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading),
|
||||
ArgRead::Text => self.read_text(a, &mut reading),
|
||||
ArgRead::Each(list) => match list.get(i) {
|
||||
Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined),
|
||||
@@ -518,7 +555,7 @@ impl Interp {
|
||||
/// What host error `e` throws, or the limit it ends the run with. A function that waits
|
||||
/// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal
|
||||
/// error.
|
||||
fn host_error(&mut self, e: HostError) -> JsResult<Abrupt> {
|
||||
pub(crate) fn host_error(&mut self, e: HostError) -> JsResult<Abrupt> {
|
||||
match e {
|
||||
HostError::Wait => Ok(Abrupt::Internal("a host function waited for its result where the run cannot pause".into())),
|
||||
HostError::Abort(message) => {
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Classes a host defines ([`crate::Realm::define_host_classes`]): objects that stand for something
|
||||
//! the host keeps, such as an open document or an object in one, with members the host's functions
|
||||
//! answer.
|
||||
//!
|
||||
//! Each object holds the name of its class and a handle, a list of numbers the host chose, in an
|
||||
//! internal slot that a script cannot read, write or copy onto another object. A host function sees
|
||||
//! such an object as the [`Data`] that [`host_ref`] makes, and gives one back the same way; a plain
|
||||
//! 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. 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
|
||||
//! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each
|
||||
//! array index `i` with it, called with `this` and the index as a number. Other names are looked up
|
||||
//! as usual, and a name that the object and its prototypes lack goes to the indexer as a string (as
|
||||
//! a number when it is the text of one, such as `-1`), so the indexer may throw for a name nothing
|
||||
//! has. Names the engine looks up itself, such as `toJSON` in `JSON.stringify`, do not go to the
|
||||
//! indexer. Assigning to such a name reads it with the indexer first, so the assignment throws what
|
||||
//! the read throws; otherwise the value is not kept. `k in object` calls the indexer with `true` as
|
||||
//! a third argument, and is true when it gives a value other than `undefined`.
|
||||
//!
|
||||
//! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each
|
||||
//! member of its class and of the classes it descends from, apart from the members that are not
|
||||
//! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members,
|
||||
//! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and
|
||||
//! `Object.getOwnPropertyDescriptor` do not report the members.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key};
|
||||
use crate::host::ArgRead;
|
||||
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
|
||||
use crate::value::Value;
|
||||
use crate::{Data, HostError, HostFunction};
|
||||
|
||||
/// The one key of the [`Data`] object that stands for an object of a host class ([`host_ref`]).
|
||||
pub const HOST_REF_KEY: &str = "\u{0}hostRef";
|
||||
|
||||
/// A member of a host class's prototype.
|
||||
#[derive(Clone)]
|
||||
pub enum HostMember {
|
||||
/// A read-only property: the function gives its value each time it is read.
|
||||
Get(HostFunction),
|
||||
/// A property the function `get` reads and `set` assigns.
|
||||
Property { get: HostFunction, set: HostFunction },
|
||||
/// A method.
|
||||
Method(HostFunction),
|
||||
/// A property the class lists that is not available yet: the function answers both a read and
|
||||
/// an assignment, with an error. It is not reported as the object's own, and `for`-`in` skips it.
|
||||
Unavailable(HostFunction),
|
||||
}
|
||||
|
||||
/// A class [`crate::Realm::define_host_classes`] adds.
|
||||
#[derive(Clone)]
|
||||
pub struct HostClass {
|
||||
pub name: String,
|
||||
/// A class defined before this one, or in the same call before it, whose prototype this
|
||||
/// class's prototype inherits from.
|
||||
pub parent: Option<String>,
|
||||
pub members: Vec<(String, HostMember)>,
|
||||
/// What `object[i]` gives for an array index `i`.
|
||||
pub index: Option<HostFunction>,
|
||||
/// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`.
|
||||
pub construct: Option<HostFunction>,
|
||||
}
|
||||
|
||||
/// The internal slot of an object of a host class: its class, as an index into the realm's
|
||||
/// classes, and its handle.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct HostObj {
|
||||
pub(crate) class: u32,
|
||||
pub(crate) handle: Rc<[f64]>,
|
||||
}
|
||||
|
||||
/// A class the realm has.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Entry {
|
||||
name: Rc<str>,
|
||||
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,
|
||||
/// The class this class's prototype inherits from, as an index into the realm's classes.
|
||||
parent: Option<u32>,
|
||||
/// The names of the members `hasOwnProperty` reports: every member but the unavailable ones.
|
||||
own: Rc<HashSet<Key>>,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
pub(crate) fn objects(&self) -> [ObjId; 2] {
|
||||
[self.proto, self.ctor]
|
||||
}
|
||||
}
|
||||
|
||||
/// A family of classes ([`Entry::family`]) and the bits of a handle.
|
||||
type MadeKey = (u32, Box<[u64]>);
|
||||
|
||||
/// 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, classes: &[Entry], id: ObjId, key: &MadeKey) -> bool {
|
||||
heap.object(id).is_some_and(|o| match &o.class {
|
||||
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, 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`.
|
||||
pub fn host_ref(class: &str, handle: &[f64]) -> Data {
|
||||
let mut list = Vec::with_capacity(handle.len() + 1);
|
||||
list.push(Data::String(class.to_string()));
|
||||
list.extend(handle.iter().map(|n| Data::Number(*n)));
|
||||
Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))])
|
||||
}
|
||||
|
||||
/// The class and handle of the object `d` stands for, when it is one [`host_ref`] made.
|
||||
pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec<f64>)> {
|
||||
let Data::Object(items) = d else { return None };
|
||||
let [(k, Data::Array(list))] = items.as_slice() else { return None };
|
||||
if k != HOST_REF_KEY {
|
||||
return None;
|
||||
}
|
||||
let (Data::String(class), rest) = list.split_first()? else { return None };
|
||||
let handle = rest.iter().map(|d| if let Data::Number(n) = d { Some(*n) } else { None }).collect::<Option<Vec<f64>>>()?;
|
||||
Some((class.as_str(), handle))
|
||||
}
|
||||
|
||||
impl Interp {
|
||||
/// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host
|
||||
/// class, and `k` names an available member of that class or of a class it descends from.
|
||||
pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult<bool> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(false) };
|
||||
let mut class = Some(h.class);
|
||||
while let Some(c) = class {
|
||||
let Some(e) = self.host_classes.get(c as usize) else { return Err(Abrupt::Internal("host class out of range".into())) };
|
||||
if e.own.contains(k) {
|
||||
return Ok(true);
|
||||
}
|
||||
class = e.parent;
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// The [`Data`] for the object of a host class `id`, or `None` when it is not one.
|
||||
pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult<Option<Data>> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
|
||||
let name =
|
||||
self.host_classes.get(h.class as usize).map(|e| e.name.clone()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?;
|
||||
Ok(Some(host_ref(&name, &h.handle)))
|
||||
}
|
||||
|
||||
/// The object of a host class that `d`, which a host function gave, stands for.
|
||||
pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult<Value> {
|
||||
let Some((name, handle)) = host_ref_parts(d) else {
|
||||
return Err(self.throw(ErrorType::Type, "a host value names an object of a host class wrongly"));
|
||||
};
|
||||
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, family) = (entry.proto, entry.family);
|
||||
let class = u32::try_from(class).unwrap_or(u32::MAX);
|
||||
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, &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)?;
|
||||
let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto));
|
||||
o.extensible = false;
|
||||
let id = self.heap.alloc_object(o);
|
||||
self.host_objects.insert(made, id);
|
||||
Ok(Value::Object(id))
|
||||
}
|
||||
|
||||
/// Whether `id` is the constructor of a host class (its other functions are not constructors).
|
||||
pub(crate) fn is_host_constructor(&self, id: ObjId) -> bool {
|
||||
self.host_classes.iter().any(|e| e.ctor == id)
|
||||
}
|
||||
|
||||
/// The indexer of the host class of `id`, when it is an object of a host class that has one.
|
||||
pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult<Option<HostFunction>> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
|
||||
Ok(self.host_classes.get(h.class as usize).and_then(|e| e.index.clone()))
|
||||
}
|
||||
|
||||
/// `object[k]` of an object of a host class, which its class's indexer `f` answers: `k` is an
|
||||
/// array index as a number, or a name as a string. With `probe`, for `k in object`, the indexer
|
||||
/// gets `true` as a third argument.
|
||||
pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult<Value> {
|
||||
self.use_fuel()?;
|
||||
let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) };
|
||||
let mut args = vec![this, k];
|
||||
if probe {
|
||||
args.push(Data::Bool(true));
|
||||
}
|
||||
match f(args) {
|
||||
Ok(d) => self.write_hosted(d),
|
||||
Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())),
|
||||
Err(e) => Err(self.host_error(e)?),
|
||||
}
|
||||
}
|
||||
|
||||
/// The key an indexer gets for `k`: a number for an array index and for any other key that is
|
||||
/// the text of a number (`-1`, `1.5`, `NaN`), otherwise the name.
|
||||
pub(crate) fn indexer_key(k: &[u16]) -> Data {
|
||||
if let Some(i) = crate::value::array_index(k) {
|
||||
return Data::Number(f64::from(i));
|
||||
}
|
||||
let name = String::from_utf16_lossy(k);
|
||||
match name.parse::<f64>() {
|
||||
Ok(n) if crate::number_to_string(n) == name => Data::Number(n),
|
||||
_ => Data::String(name),
|
||||
}
|
||||
}
|
||||
|
||||
/// [[HasProperty]] of `k` on `id`: for an object of a host class with an indexer, an array index,
|
||||
/// or a name that the object and its prototypes lack, is there when the indexer gives a value other
|
||||
/// than `undefined` for it.
|
||||
pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult<bool> {
|
||||
let index = crate::value::array_index(k).is_some();
|
||||
if (index || !self.has_property(id, k)?)
|
||||
&& let Some(f) = self.host_indexer(id)?
|
||||
{
|
||||
return Ok(!matches!(self.host_index(&f, id, Self::indexer_key(k), true)?, Value::Undefined));
|
||||
}
|
||||
self.has_property(id, k)
|
||||
}
|
||||
|
||||
/// `d` as a JavaScript value, the objects of host classes in it made from their [`host_ref`].
|
||||
pub(crate) fn write_hosted(&mut self, d: Data) -> JsResult<Value> {
|
||||
let was = std::mem::replace(&mut self.write_hosted, true);
|
||||
let r = self.write_data(d, 0, false);
|
||||
self.write_hosted = was;
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given.
|
||||
pub(crate) fn install(i: &mut Interp, classes: Vec<HostClass>, instances: Vec<(String, Data)>) -> JsResult<()> {
|
||||
for class in classes {
|
||||
install_class(i, class)?;
|
||||
}
|
||||
for (name, d) in instances {
|
||||
let v = i.write_hosted(d)?;
|
||||
let global = i.global;
|
||||
i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds the global properties `globals`, each read with its getter and assigned with its setter as
|
||||
/// a member of a host class is. Assigning one without a setter keeps its value, and throws in strict
|
||||
/// mode code.
|
||||
pub(crate) fn install_globals(i: &mut Interp, globals: Vec<(String, HostFunction, Option<HostFunction>)>) -> JsResult<()> {
|
||||
let global = i.global;
|
||||
for (name, get, set) in globals {
|
||||
let mark = i.temp_roots.len();
|
||||
let get = hosted_function(i, get, &name);
|
||||
i.temp_roots.push(Value::Object(get));
|
||||
let set = set.map(|f| hosted_function(i, f, &name));
|
||||
i.temp_roots.truncate(mark);
|
||||
i.define(global, key(&name), Prop::Accessor { get: Some(get), set, flags: CONFIGURABLE })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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 own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX);
|
||||
let (parent, family, parent_class) = match &class.parent {
|
||||
None => (i.intrinsics.object_proto, own, None),
|
||||
Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) {
|
||||
Some((n, e)) => (e.proto, e.family, u32::try_from(n).ok()),
|
||||
None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))),
|
||||
},
|
||||
};
|
||||
let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent)));
|
||||
let mark = i.temp_roots.len();
|
||||
i.temp_roots.push(Value::Object(proto));
|
||||
let r = fill_class(i, proto, &class);
|
||||
i.temp_roots.truncate(mark);
|
||||
let ctor = r?;
|
||||
let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect();
|
||||
i.host_classes.push(Entry {
|
||||
name: class.name.as_str().into(),
|
||||
proto,
|
||||
ctor,
|
||||
index: class.index,
|
||||
family,
|
||||
parent: parent_class,
|
||||
own: Rc::new(members),
|
||||
});
|
||||
let global = i.global;
|
||||
i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
}
|
||||
|
||||
/// Puts the members of `class` on `proto` and makes its constructor. → the constructor.
|
||||
fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult<ObjId> {
|
||||
let path = &class.name;
|
||||
for (name, member) in &class.members {
|
||||
let full = format!("{path}.{name}");
|
||||
let prop = match member {
|
||||
HostMember::Get(f) => Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: ENUMERABLE },
|
||||
HostMember::Property { get, set } => {
|
||||
let get = hosted_function(i, get.clone(), &full);
|
||||
i.temp_roots.push(Value::Object(get));
|
||||
Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: ENUMERABLE }
|
||||
}
|
||||
HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 },
|
||||
HostMember::Unavailable(f) => {
|
||||
let f = hosted_function(i, f.clone(), &full);
|
||||
Prop::Accessor { get: Some(f), set: Some(f), flags: 0 }
|
||||
}
|
||||
};
|
||||
i.define(proto, key(name), prop)?;
|
||||
}
|
||||
let construct = class.construct.clone().unwrap_or_else(|| {
|
||||
let message = format!("{path} cannot be constructed by a script");
|
||||
Rc::new(move |_| Err(HostError::Type(message.clone())))
|
||||
});
|
||||
let ctor = hosted_function(i, construct, path);
|
||||
i.define(ctor, key("prototype"), Prop::Data { value: Value::Object(proto), flags: 0 })?;
|
||||
i.define(proto, key("constructor"), Prop::Data { value: Value::Object(ctor), flags: 0 })?;
|
||||
i.object_mut(proto)?.extensible = false;
|
||||
i.object_mut(ctor)?.extensible = false;
|
||||
Ok(ctor)
|
||||
}
|
||||
|
||||
fn hosted_function(i: &mut Interp, f: HostFunction, name: &str) -> ObjId {
|
||||
let proto = i.intrinsics.function_proto;
|
||||
i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read: ArgRead::Hosted }), Some(proto)))
|
||||
}
|
||||
@@ -675,6 +675,87 @@ 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 objects_of_a_host_class_report_its_available_members_as_their_own() {
|
||||
let mut r = realm(1_000_000);
|
||||
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
|
||||
let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into())));
|
||||
let base = HostClass {
|
||||
name: "Base".into(),
|
||||
parent: None,
|
||||
members: vec![
|
||||
("size".to_string(), HostMember::Get(value.clone())),
|
||||
("shape".to_string(), HostMember::Property { get: value.clone(), set: value.clone() }),
|
||||
("grow".to_string(), HostMember::Method(value.clone())),
|
||||
("later".to_string(), HostMember::Unavailable(missing)),
|
||||
],
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
let leaf = HostClass {
|
||||
name: "Leaf".into(),
|
||||
parent: Some("Base".into()),
|
||||
members: vec![("leaf".to_string(), HostMember::Get(value))],
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap();
|
||||
r.start(
|
||||
"var own = Object.prototype.hasOwnProperty, keys = [];\
|
||||
for (var k in it) keys.push(k);\
|
||||
[it.hasOwnProperty('size'), it.hasOwnProperty('shape'), it.hasOwnProperty('grow'), it.hasOwnProperty('leaf'),\
|
||||
own.call(it, 'size'), it.propertyIsEnumerable('grow'),\
|
||||
it.hasOwnProperty('later'), it.propertyIsEnumerable('later'), it.hasOwnProperty('nope'),\
|
||||
it.hasOwnProperty('hasOwnProperty'), it.hasOwnProperty('constructor'), 'later' in it,\
|
||||
keys.sort().join(' '), Leaf.prototype.hasOwnProperty('size'), ({}).hasOwnProperty('size')].join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
finish(&mut r, 1_000_000).0.unwrap(),
|
||||
JsValue::String("true,true,true,true,true,true,false,false,false,false,false,true,leaf shape size,false,false".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_converted_function_reads_each_argument_as_its_list_says() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
+77
-5
@@ -279,6 +279,14 @@ pub(crate) struct Interp {
|
||||
pub(crate) install_error: Option<String>,
|
||||
/// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]).
|
||||
pub(crate) files: Option<crate::file_classes::Classes>,
|
||||
/// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them.
|
||||
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 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,
|
||||
/// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the
|
||||
/// operators take no object as a measurement.
|
||||
pub(crate) unit_values: Option<crate::unit_value::Classes>,
|
||||
@@ -302,6 +310,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>,
|
||||
@@ -583,6 +596,9 @@ impl Interp {
|
||||
held_bytes: 0,
|
||||
install_error: None,
|
||||
files: None,
|
||||
host_classes: Vec::new(),
|
||||
write_hosted: false,
|
||||
host_objects: crate::host_classes::Made::default(),
|
||||
unit_values: None,
|
||||
date_host: crate::date_builtins::DateHost::default(),
|
||||
held: Rc::default(),
|
||||
@@ -593,6 +609,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(),
|
||||
@@ -857,6 +875,7 @@ impl Interp {
|
||||
roots.objects.push(self.global);
|
||||
roots.objects.extend(self.intrinsics.all());
|
||||
roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects));
|
||||
roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects));
|
||||
roots.values.extend(self.symbols.root_values());
|
||||
roots.objects.extend(self.symbols.root_objects());
|
||||
roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object));
|
||||
@@ -872,6 +891,7 @@ impl Interp {
|
||||
self.template_objects.retain(|(site, _), (code, _)| Rc::strong_count(code) > sites.get(site).copied().unwrap_or(0));
|
||||
roots.objects.extend(self.template_objects.values().map(|&(_, id)| id));
|
||||
self.heap.collect(&roots);
|
||||
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);
|
||||
@@ -1573,6 +1593,28 @@ impl Interp {
|
||||
|
||||
/// [[Get]] starting at `start`, with `receiver` as `this` for a getter.
|
||||
pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult<Value> {
|
||||
// An array index of an object of a host class with an indexer is the indexer's answer.
|
||||
if let Some(i) = array_index(k)
|
||||
&& let Some(f) = self.host_indexer(start)?
|
||||
{
|
||||
return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false);
|
||||
}
|
||||
match self.find_property(start, k)? {
|
||||
// A name the object and its prototypes lack is the indexer's answer too.
|
||||
None => match self.host_indexer(start)? {
|
||||
Some(f) => self.host_index(&f, start, Self::indexer_key(k), false),
|
||||
None => Ok(Value::Undefined),
|
||||
},
|
||||
Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Some(Prop::Data { value, .. }) => Ok(value),
|
||||
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
|
||||
}
|
||||
}
|
||||
|
||||
/// [[Get]] of a name that is not an array index, without the indexer of an object of a host
|
||||
/// class: a name the object and its prototypes lack is `undefined`. For names the engine looks
|
||||
/// up itself, such as `toJSON`, which a collection's indexer would answer with an error.
|
||||
pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult<Value> {
|
||||
match self.find_property(start, k)? {
|
||||
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Some(Prop::Data { value, .. }) => Ok(value),
|
||||
@@ -1868,10 +1910,17 @@ impl Interp {
|
||||
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"),
|
||||
_ => {}
|
||||
}
|
||||
let o = self.object(id)?;
|
||||
if !o.extensible {
|
||||
if !self.object(id)?.extensible {
|
||||
// A name that an object of a host class with an indexer lacks is read with the indexer
|
||||
// first, so assigning it throws what reading it throws.
|
||||
if array_index(&k).is_none()
|
||||
&& let Some(f) = self.host_indexer(id)?
|
||||
{
|
||||
self.host_index(&f, id, Self::indexer_key(&k), false)?;
|
||||
}
|
||||
return self.reject(throw, &k, "the object is not extensible");
|
||||
}
|
||||
let o = self.object(id)?;
|
||||
if let Class::Array { length, length_writable: false } = o.class
|
||||
&& array_index(&k).is_some_and(|i| i >= length)
|
||||
{
|
||||
@@ -2782,7 +2831,7 @@ impl Interp {
|
||||
Func::Data { f, name, read } => {
|
||||
// The arguments are read before the function runs, and a result being built
|
||||
// keeps itself reachable.
|
||||
return Ok(Prepared::Done(self.call_data(&f, &name, &args, &read)?));
|
||||
return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?));
|
||||
}
|
||||
Func::Eval { f, end, strict_writes, name } => {
|
||||
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?));
|
||||
@@ -2893,6 +2942,25 @@ impl Interp {
|
||||
self.stack.truncate(start);
|
||||
self.push(v)
|
||||
}
|
||||
// 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. 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 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"))?
|
||||
{
|
||||
self.object_mut(*o)?.proto = Some(proto);
|
||||
}
|
||||
self.stack.truncate(start);
|
||||
self.push(v)
|
||||
}
|
||||
_ => Err(self.type_error("the value is not a constructor")),
|
||||
}
|
||||
}
|
||||
@@ -3139,7 +3207,7 @@ impl Interp {
|
||||
self.temp_roots.extend(keep.iter().cloned());
|
||||
let was_waiting = self.waiting;
|
||||
let answer = match self.func_of(&host) {
|
||||
Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read),
|
||||
Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read),
|
||||
_ => self.call(&host, &Value::Undefined, &args),
|
||||
};
|
||||
self.temp_roots.truncate(mark);
|
||||
@@ -3836,7 +3904,11 @@ impl Interp {
|
||||
}
|
||||
let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) };
|
||||
let k = self.to_prop_key(a)?;
|
||||
self.has_pk(*o, &k).map(Value::Bool)
|
||||
match &k {
|
||||
PropKey::Str(name) => self.has_property_indexed(*o, name),
|
||||
PropKey::Sym(_) => self.has_pk(*o, &k),
|
||||
}
|
||||
.map(Value::Bool)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +90,7 @@ mod error;
|
||||
mod file_classes;
|
||||
mod heap;
|
||||
mod host;
|
||||
mod host_classes;
|
||||
mod interp;
|
||||
mod iteration;
|
||||
mod lexer;
|
||||
@@ -117,6 +118,7 @@ pub use ast::{
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
|
||||
pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
pub use number::to_string as number_to_string;
|
||||
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE};
|
||||
|
||||
+29
-1
@@ -271,6 +271,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;
|
||||
@@ -324,6 +326,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;
|
||||
if let Some(es2015) = interp.next_es2015.take() {
|
||||
@@ -442,8 +446,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)
|
||||
});
|
||||
@@ -546,6 +553,27 @@ impl Realm {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose
|
||||
/// prototype holds its members, and the global objects `instances`, each made from the
|
||||
/// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be
|
||||
/// replaced. A heap too small for them ends with the error the realm's next run would give.
|
||||
pub fn define_host_classes(&mut self, classes: Vec<crate::HostClass>, instances: Vec<(String, crate::Data)>) -> Result<(), RunError> {
|
||||
match crate::host_classes::install(&mut self.interp, classes, instances) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => self.outcome(Err(e)).map(drop),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the global properties `globals`: a name, the function that answers a read, and the
|
||||
/// function that answers an assignment, each called with `undefined` as `this` (and the value
|
||||
/// assigned). Assigning one without a setter keeps its value, and throws in strict mode code.
|
||||
pub fn define_host_globals(&mut self, globals: Vec<(String, crate::HostFunction, Option<crate::HostFunction>)>) -> Result<(), RunError> {
|
||||
match crate::host_classes::install_globals(&mut self.interp, globals) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => self.outcome(Err(e)).map(drop),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has
|
||||
/// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its
|
||||
/// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught
|
||||
|
||||
@@ -479,7 +479,7 @@ fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) {
|
||||
Field::new(layout.clone()).show(ui, |ui, _| {
|
||||
let entries: Vec<Entry<ArtboardLayout>> = ArtboardLayout::ALL.iter().map(|l| Entry::new(*l, text(tl!(l.label())))).collect();
|
||||
if let Some(l) = Segmented::new(layout.clone(), Bind::given(s.layout), &entries).enabled(several).show(ui).value().copied() {
|
||||
s.layout = l;
|
||||
choose_layout(s, l);
|
||||
}
|
||||
});
|
||||
let rtl = Checkbox::new(Bind::given(s.right_to_left)).label(right_to_left).enabled(several).show(ui);
|
||||
@@ -494,14 +494,37 @@ fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) {
|
||||
});
|
||||
Field::new(columns.clone()).show(ui, |ui, _| {
|
||||
let n = f64::from(s.artboards.max(1));
|
||||
let shown = f64::from(s.columns.max(1)).min(n);
|
||||
let shown = f64::from(shown_columns(s));
|
||||
let field = NumberField::new(columns.clone(), Bind::given(Some(shown))).range(1.0..=n).step(1.0).commit_decimals(0).enabled(several && grid);
|
||||
if let Some(v) = field.show(ui).value().copied().flatten().filter(|v| v.is_finite()) {
|
||||
// A column count replaces a preset's rows.
|
||||
s.columns = v.round().clamp(1.0, n) as u32;
|
||||
s.rows = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The columns More Settings shows: for a grid by column made with `file.new`'s `rows`, the columns
|
||||
/// those rows give the current number of artboards, as `file.new` lays them out; otherwise the
|
||||
/// stored count. At most one for each artboard.
|
||||
fn shown_columns(s: &DocSettings) -> u32 {
|
||||
let n = s.artboards.max(1);
|
||||
if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { u32::try_from(s.grid_columns()).unwrap_or(n) } else { s.columns.max(1).min(n) }
|
||||
}
|
||||
|
||||
/// Chooses a layout in More Settings. Another layout replaces a preset's rows and keeps the column
|
||||
/// count those rows showed; choosing the layout that is already selected keeps the rows.
|
||||
fn choose_layout(s: &mut DocSettings, l: ArtboardLayout) {
|
||||
if l == s.layout {
|
||||
return;
|
||||
}
|
||||
if s.rows > 0 {
|
||||
s.columns = shown_columns(s);
|
||||
s.rows = 0;
|
||||
}
|
||||
s.layout = l;
|
||||
}
|
||||
|
||||
/// Manage Profiles' pop-up: a row per New Document profile with Edit, which opens the profile as a
|
||||
/// document, and Reset, which brings back the shipped profile. The button pressed is put in `action`.
|
||||
fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option<String>) {
|
||||
@@ -885,6 +908,53 @@ mod tests {
|
||||
assert_eq!((saved.layout, saved.spacing), (ArtboardLayout::Column, 30.0));
|
||||
}
|
||||
|
||||
/// A grid by column with a preset's rows.
|
||||
fn by_rows(artboards: u32, rows: u32) -> DocSettings {
|
||||
DocSettings { artboards, layout: ArtboardLayout::GridByColumn, columns: 2, rows, ..DocSettings::default() }
|
||||
}
|
||||
|
||||
/// Columns shows what a preset's rows give the current number of artboards, and the stored
|
||||
/// count without rows.
|
||||
#[test]
|
||||
fn columns_follow_a_presets_rows_as_artboards_change() {
|
||||
for (artboards, shown) in [(5, 2), (9, 3), (2, 1)] {
|
||||
assert_eq!(shown_columns(&by_rows(artboards, 4)), shown, "{artboards} artboards");
|
||||
}
|
||||
assert_eq!(shown_columns(&by_rows(9, 0)), 2);
|
||||
}
|
||||
|
||||
/// Another layout replaces a preset's rows and keeps the columns they showed, so Create lays out
|
||||
/// what the dialog showed; the layout already selected keeps the rows.
|
||||
#[test]
|
||||
fn a_new_layout_keeps_the_columns_a_presets_rows_showed() {
|
||||
for to in [ArtboardLayout::GridByRow, ArtboardLayout::Row, ArtboardLayout::Column] {
|
||||
let mut s = by_rows(9, 4);
|
||||
choose_layout(&mut s, to);
|
||||
assert_eq!((s.layout, s.columns, s.rows), (to, 3, 0), "{to:?}");
|
||||
}
|
||||
let mut s = by_rows(9, 4);
|
||||
choose_layout(&mut s, ArtboardLayout::GridByColumn);
|
||||
assert_eq!(s, by_rows(9, 4));
|
||||
let mut s = by_rows(9, 0);
|
||||
choose_layout(&mut s, ArtboardLayout::GridByRow);
|
||||
assert_eq!((s.columns, s.rows), (2, 0));
|
||||
}
|
||||
|
||||
/// A preset's rows reach the dialog's fields and Create puts that many artboards in each column.
|
||||
#[test]
|
||||
fn a_presets_rows_reach_the_document_create_makes() {
|
||||
let mut app = app();
|
||||
open(&mut app);
|
||||
set(&app, "artboards", json!(5)).unwrap();
|
||||
set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap();
|
||||
assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4));
|
||||
create(&mut app);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.doc.artboards.len(), 5);
|
||||
let first: Vec<_> = st.doc.artboards.iter().filter(|a| a.rect.x0 == 0.0).map(|a| a.rect.y0).collect();
|
||||
assert_eq!(first.len(), 4, "four artboards in the first column: {first:?}");
|
||||
}
|
||||
|
||||
/// Align New Objects to Pixel Grid reaches a saved preset and the document Create makes.
|
||||
#[test]
|
||||
fn align_new_objects_checkbox_follows_the_preset_and_reaches_the_document() {
|
||||
|
||||
+3
-2
@@ -811,8 +811,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
|
||||
|
||||
+133
-8
@@ -2686,6 +2686,121 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
throws a `RangeError`.
|
||||
- `vc.commands` lists the commands a script may run.
|
||||
- `vc.log(value)` adds a value to the report and a line to the Script Console.
|
||||
- `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/
|
||||
describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one),
|
||||
`app.selection` (assigning it sets the active document's selection), `app.coordinateSystem` and
|
||||
`app.getIsFileOpen(path)`. A script may name the application's members without `app.`, as
|
||||
[Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/)
|
||||
describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules:
|
||||
assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level
|
||||
`var selection = ...` does the same and does not make a variable of the script. Assigning `documents` keeps its
|
||||
value. `app.documents`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)`
|
||||
and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`,
|
||||
which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of
|
||||
columns for the other layouts), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new`
|
||||
with the New Document profile `startupPreset` names (`Print`, `Web`, `Mobile`, `Video`, another profile of
|
||||
`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. 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. A
|
||||
`presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a
|
||||
`TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the
|
||||
automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the
|
||||
profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it
|
||||
that cannot be used, for example) goes to the Script Console as a line `addDocument: <warning>`. A `previewMode` of
|
||||
`DocumentPreviewMode.PixelPreview` throws an error that says it is not available yet, and no document is made.
|
||||
`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/)
|
||||
lists every object in the document's layers, the objects inside groups, compound paths, blends, envelopes, repeats
|
||||
and intertwines included, and has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either
|
||||
collection is true for each
|
||||
entry `[i]` gives. Each page item
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/) has `typename`, `parent`, `name`, `note` (the
|
||||
Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds
|
||||
or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they
|
||||
were), `opacity` (0 to
|
||||
100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the
|
||||
visible bounds), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group,
|
||||
or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`,
|
||||
`move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs
|
||||
`edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same
|
||||
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` throws that error and leaves the documents, the selection and
|
||||
the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or
|
||||
locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an
|
||||
object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`,
|
||||
`locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer
|
||||
throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such
|
||||
an object throws `Cannot edit` too. The one exception is `opacity` given the value the object already has, which
|
||||
changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity, that
|
||||
value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an
|
||||
object that is hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself
|
||||
as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move`
|
||||
or `remove()` takes the last path out of a compound path, the compound path stays, empty, so a script that holds
|
||||
it can still read it (`remove()` runs `edit.clear` with `keepEmpty: true`). An object with nothing in it, such
|
||||
as an empty group or that compound path, reads its bounds, `position`, `width` and `height` as zeros, and
|
||||
assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws
|
||||
`Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws
|
||||
`Reordering a path inside a compound path is not available yet` and leaves the document unchanged. 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"`.
|
||||
`pageItems` lists the art topmost first, as the example on
|
||||
[CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`,
|
||||
and a document's `selection` lists the selected objects in the same order, whatever order they were selected or
|
||||
made in. This is VectorCraft's own rule: the page cited below says the first object in a selection is the one last
|
||||
added to the page, and VectorCraft does not follow that sentence. A collection read with a name, such as
|
||||
`pageItems["Logo"]` or `documents["Untitled-1"]`, gives the object `getByName` gives, as
|
||||
[Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/)
|
||||
shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws
|
||||
`Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too
|
||||
(VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note`
|
||||
take a number or a Boolean as the text `String(value)` gives. `String(object)` gives
|
||||
`[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document <name>]`,
|
||||
`[Layer <name>]`, `[Application]` and `[PageItems]` (VectorCraft's own rule).
|
||||
Documents are listed in tab order; the same page says `documents[0]` is always the active document, and
|
||||
VectorCraft does not follow that yet. VectorCraft's own rules: page items are listed with the
|
||||
objects inside groups and compound paths after their group and without layers and ruler guides. A document's
|
||||
`selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. Script coordinates
|
||||
are points with Y up from the bottom-left corner of the first artboard, or, with
|
||||
`CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename`
|
||||
is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem`
|
||||
for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each
|
||||
changed document. A value that changes nothing runs no command, and a change to another document leaves the active
|
||||
tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers
|
||||
panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was
|
||||
deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that
|
||||
is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()`
|
||||
when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on
|
||||
a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard`
|
||||
and delete nothing. Setting `width` or `height` scales the object along
|
||||
the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw
|
||||
`Not found`; and
|
||||
`app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item,
|
||||
a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` 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,
|
||||
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. Some members the Application,
|
||||
Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and
|
||||
`app.beep`, throw an error that says they are not available yet when they are read or assigned.
|
||||
`hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an
|
||||
object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the
|
||||
other properties but not the methods. `Object.keys`, `Object.getOwnPropertyNames` and
|
||||
`Object.getOwnPropertyDescriptor` do not report any member of the class. Assigning a member that a page item, a
|
||||
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`, 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`.
|
||||
- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and
|
||||
`$.writeln(...values)` does the same and ends the line. Each call counts as a host call.
|
||||
- `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global
|
||||
@@ -3401,7 +3516,8 @@ or unknown id leaves the document unchanged. An empty `ids` array does nothing.
|
||||
are kept, and selecting an ancestor together with its descendants deletes that subtree once.
|
||||
Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior.
|
||||
With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a
|
||||
boolean.
|
||||
boolean. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps it, empty,
|
||||
also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean is rejected.
|
||||
Without `ids`, `keepJoined: true` removes the direct-selected anchors of each path that has no selected segment as
|
||||
`path.removeAnchors` does (see Removing anchor points): the path stays joined, and the next anchor along is selected
|
||||
(the one before at an open path's end). When no subpath that lost an anchor keeps two anchors, the path stays selected
|
||||
@@ -6524,8 +6640,9 @@ itself, and each sublayer has its own colour for the selection highlight. `docum
|
||||
report `color`, `template`, `printable`, `preview`, `dimImages` and `clip`), the `currentLayer` (where new art goes)
|
||||
and `layerRows`, the rows highlighted in the panel.
|
||||
|
||||
- **Clicking rows** (not undo steps): `layer.setCurrent {id}` is a plain click on any row: it alone is highlighted
|
||||
and its layer (the row itself when it is a layer or sublayer) becomes current. `layer.highlight {ids, mode?:
|
||||
- **Clicking rows** (not undo steps): `layer.setCurrent {id, keepRows?}` is a plain click on any row: it alone is
|
||||
highlighted and its layer (the row itself when it is a layer or sublayer) becomes current; with `keepRows` true the
|
||||
highlighted rows stay as they are. `layer.highlight {ids, mode?:
|
||||
set|add|toggle}` is Shift-click (a range) and Ctrl/Cmd-click (toggle). Selecting art makes its layer current.
|
||||
Without `ids`, the panel commands below act on the highlighted rows, else on the current layer.
|
||||
- **Selection column**: `layer.selectAll {id, add?}` selects a row's visible, unlocked art (a layer's sublayers'
|
||||
@@ -7115,7 +7232,9 @@ their facing handles are refitted so one cubic follows the two old segments; two
|
||||
The anchor after each removed one is then selected (the one before at an open path's end), so running
|
||||
`path.removeAnchors` again goes on along the path.
|
||||
`path.removeAnchor {id, subpath?, anchor}` (the Delete Anchor Point tool) removes one anchor the same way, and
|
||||
`path.deleteAnchors {}` (the Delete key) deletes the selected anchors with their segments, opening closed paths there.
|
||||
`path.deleteAnchors {keepEmpty?}` (the Delete key) deletes the selected anchors with their segments, opening closed paths
|
||||
there. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given; `edit.clear` passes its
|
||||
`keepEmpty` on when it deletes direct-selected anchors.
|
||||
With the `deleteKeepsPathsJoined` preference on, the Delete key (`edit.clear`) removes them as `path.removeAnchors`
|
||||
does instead.
|
||||
|
||||
@@ -9191,7 +9310,11 @@ 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, 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),
|
||||
`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,
|
||||
@@ -9374,9 +9497,11 @@ with the defaults.
|
||||
|
||||
The profile is read on every `file.new`, so a replayed journal or a recorded action uses the profile as it is when it
|
||||
runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read.
|
||||
When the file 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. The
|
||||
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
|
||||
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
|
||||
|
||||
+1
-1
@@ -198,7 +198,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
|
||||
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
|
||||
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 |
|
||||
| M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
|
||||
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
|
||||
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
|
||||
|
||||
@@ -1040,6 +1040,7 @@ 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: 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/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
|
||||
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
|
||||
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.
|
||||
|
||||
Reference in new issue
Block a user