mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into fix/dialog-keys-ui-inspect
This commit is contained in:
commit
4e99e7a891
128 files changed
+9862
-539
No files matched your search
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied.
|
||||
|
||||
- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged.
|
||||
|
||||
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
|
||||
@@ -19,6 +19,9 @@ impl PrintService for SystemPrint {
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_printers(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintersFn> {
|
||||
Some(std::sync::Arc::new(system::queues))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e))))
|
||||
}
|
||||
@@ -145,6 +148,10 @@ mod system {
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
craft::print::printers().into_iter().map(Printer::from).collect()
|
||||
}
|
||||
/// The installed queues and the default one, without asking each driver for its capabilities.
|
||||
pub fn queues() -> Vec<Printer> {
|
||||
craft::print::printer_queues().into_iter().map(Printer::from).collect()
|
||||
}
|
||||
/// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings.
|
||||
pub fn papers(printer: &str) -> Vec<Paper> {
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -757,6 +757,16 @@ impl Document {
|
||||
{
|
||||
on_path.rename(&renamed);
|
||||
}
|
||||
// An Image Trace object names the objects its trace made by id: the copy names the copies of
|
||||
// those objects, and no other object.
|
||||
if let Some(made) = node.trace_made() {
|
||||
let mut old = vec![];
|
||||
node.walk(&mut |d| old.push(d.id));
|
||||
let mut new = vec![];
|
||||
n.walk(&mut |d| new.push(d.id));
|
||||
let copies = old.into_iter().zip(new).skip(1).filter(|(o, _)| made.contains(*o)).map(|(_, c)| c);
|
||||
n.set_trace_made(&crate::TraceMade::of(copies));
|
||||
}
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ pub use text::{
|
||||
TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet};
|
||||
pub use trace::TraceView;
|
||||
pub use trace::{TraceMade, TraceView};
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
pub use vectorcraft_geom as geom;
|
||||
|
||||
@@ -822,6 +822,28 @@ fn reid_gives_fresh_ids() {
|
||||
assert!(!ids.contains(&a) && !ids.contains(&b));
|
||||
}
|
||||
|
||||
/// A copy of an Image Trace object records the copies of the objects its trace made, nested ones
|
||||
/// included, and not the copy of an object added to it later.
|
||||
#[test]
|
||||
fn reid_remaps_what_a_tracing_records_it_made() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let na = (*d.remove(a).unwrap()).clone();
|
||||
let nb = (*d.remove(b).unwrap()).clone();
|
||||
let inner = d.alloc_id();
|
||||
let inner = Node::group(inner, vec![Arc::new(na)]);
|
||||
let mut tracing = Node::group(d.alloc_id(), vec![Arc::new(inner.clone()), Arc::new(nb)]);
|
||||
tracing.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"})));
|
||||
tracing.set_trace_made(&crate::TraceMade::of([inner.id, a]));
|
||||
let copy = d.reid(&tracing);
|
||||
let made = copy.trace_made().unwrap();
|
||||
let ch = copy.children().unwrap();
|
||||
let (inner_copy, added_copy) = (&ch[0], &ch[1]);
|
||||
let a_copy = inner_copy.children().unwrap()[0].id;
|
||||
assert!(made.contains(inner_copy.id) && made.contains(a_copy));
|
||||
assert!(!made.contains(added_copy.id) && !made.contains(inner.id) && !made.contains(a) && !made.contains(b));
|
||||
assert_eq!(made, crate::TraceMade::of([inner_copy.id, a_copy]));
|
||||
}
|
||||
|
||||
/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from
|
||||
/// another document with the same id does not.
|
||||
#[test]
|
||||
|
||||
+103
-2
@@ -1,11 +1,64 @@
|
||||
//! Image Trace objects' View: how a live trace draws on screen.
|
||||
//!
|
||||
//! An Image Trace object is a group whose `trace` holds `{preset, params, view}` (see
|
||||
//! An Image Trace object is a group whose `trace` holds `{preset, params, view, made}` (see
|
||||
//! `imageTrace.make`). The view is a viewing aid only: exports, printing and Expand always use the
|
||||
//! tracing result, whatever it is set to.
|
||||
//! tracing result, whatever it is set to. `made` names the objects the trace made ([`TraceMade`]).
|
||||
|
||||
use crate::NodeId;
|
||||
use crate::node::Node;
|
||||
|
||||
/// The key of an Image Trace object's `trace` settings that names the objects its trace made.
|
||||
pub const TRACE_MADE: &str = "made";
|
||||
|
||||
/// The objects the trace of an Image Trace object made, by id: the ranges `[first, last]` of their
|
||||
/// ids, ascending and apart. A trace gives out its ids one after the other, so a trace of any size
|
||||
/// is a few ranges.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TraceMade(Vec<(u64, u64)>);
|
||||
|
||||
impl TraceMade {
|
||||
/// The objects `ids` name.
|
||||
pub fn of(ids: impl IntoIterator<Item = NodeId>) -> Self {
|
||||
let mut ids: Vec<u64> = ids.into_iter().map(|i| i.0).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
let mut ranges: Vec<(u64, u64)> = vec![];
|
||||
for id in ids {
|
||||
match ranges.last_mut() {
|
||||
Some((_, last)) if last.checked_add(1) == Some(id) => *last = id,
|
||||
_ => ranges.push((id, id)),
|
||||
}
|
||||
}
|
||||
Self(ranges)
|
||||
}
|
||||
|
||||
/// Whether the trace made the object `id`.
|
||||
pub fn contains(&self, id: NodeId) -> bool {
|
||||
let i = self.0.partition_point(|(_, last)| *last < id.0);
|
||||
self.0.get(i).is_some_and(|(first, _)| *first <= id.0)
|
||||
}
|
||||
|
||||
/// The ranges as the `trace` settings save them: `[[first, last], ...]`.
|
||||
pub fn to_json(&self) -> serde_json::Value {
|
||||
serde_json::Value::Array(self.0.iter().map(|(a, b)| serde_json::json!([a, b])).collect())
|
||||
}
|
||||
|
||||
/// The ranges `v` saves, or `None` when it is not a list of `[first, last]` pairs of whole
|
||||
/// numbers, ascending and apart.
|
||||
pub fn from_json(v: &serde_json::Value) -> Option<Self> {
|
||||
let mut ranges: Vec<(u64, u64)> = vec![];
|
||||
for r in v.as_array()? {
|
||||
let [a, b] = r.as_array()?.as_slice() else { return None };
|
||||
let (a, b) = (a.as_u64()?, b.as_u64()?);
|
||||
if a > b || ranges.last().is_some_and(|(_, last)| *last >= a) {
|
||||
return None;
|
||||
}
|
||||
ranges.push((a, b));
|
||||
}
|
||||
Some(Self(ranges))
|
||||
}
|
||||
}
|
||||
|
||||
/// Image Trace › View.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum TraceView {
|
||||
@@ -90,6 +143,21 @@ impl Node {
|
||||
pub fn trace_split(&self) -> f64 {
|
||||
self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of)
|
||||
}
|
||||
|
||||
/// The objects the trace of this Image Trace object made ([`TRACE_MADE`]), or `None` when its
|
||||
/// `trace` settings name none, as in a tracing saved before they did, or name them in any other
|
||||
/// form than [`TraceMade::to_json`]'s.
|
||||
pub fn trace_made(&self) -> Option<TraceMade> {
|
||||
self.extras().trace.as_deref().and_then(|t| t.get(TRACE_MADE)).and_then(TraceMade::from_json)
|
||||
}
|
||||
|
||||
/// Records `made` as the objects the trace of this Image Trace object made, when its `trace`
|
||||
/// settings are an object.
|
||||
pub fn set_trace_made(&mut self, made: &TraceMade) {
|
||||
if let Some(t) = self.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(serde_json::Value::as_object_mut) {
|
||||
t.insert(TRACE_MADE.into(), made.to_json());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -110,6 +178,39 @@ mod tests {
|
||||
assert_eq!(g.trace_view(), TraceView::Result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_made_keeps_ranges_and_reads_only_well_formed_ones() {
|
||||
let ids = [7, 3, 4, 5, 9, 3, u64::MAX].map(crate::NodeId);
|
||||
let made = TraceMade::of(ids);
|
||||
assert_eq!(made.to_json(), serde_json::json!([[3, 5], [7, 7], [9, 9], [u64::MAX, u64::MAX]]));
|
||||
for id in 0..12 {
|
||||
assert_eq!(made.contains(crate::NodeId(id)), ids.contains(&crate::NodeId(id)), "{id}");
|
||||
}
|
||||
assert!(made.contains(crate::NodeId(u64::MAX)));
|
||||
assert_eq!(TraceMade::from_json(&made.to_json()), Some(made.clone()));
|
||||
assert_eq!(TraceMade::from_json(&serde_json::json!([])), Some(TraceMade::default()));
|
||||
for bad in [
|
||||
serde_json::json!({}),
|
||||
serde_json::json!([[5, 3]]),
|
||||
serde_json::json!([[1, 4], [4, 6]]),
|
||||
serde_json::json!([[6, 7], [1, 2]]),
|
||||
serde_json::json!([[1]]),
|
||||
serde_json::json!([[1, 2, 3]]),
|
||||
serde_json::json!([[-1, 2]]),
|
||||
serde_json::json!([[1.5, 2]]),
|
||||
serde_json::json!(["1", "2"]),
|
||||
] {
|
||||
assert_eq!(TraceMade::from_json(&bad), None, "{bad}");
|
||||
}
|
||||
let mut g = Node::group(crate::NodeId(1), vec![]);
|
||||
g.set_trace_made(&made);
|
||||
assert_eq!(g.trace_made(), None, "a group with no trace settings records nothing");
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"})));
|
||||
assert_eq!(g.trace_made(), None);
|
||||
g.set_trace_made(&made);
|
||||
assert_eq!(g.trace_made(), Some(made));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() {
|
||||
let mut g = Node::group(crate::NodeId(1), vec![]);
|
||||
|
||||
@@ -964,6 +964,10 @@ pub use retype::{RetypeFound, RetypeRun, RetypeSearch};
|
||||
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
|
||||
pub(crate) use buildcmds::TracePresetChanges;
|
||||
|
||||
/// Whether an object is an Image Trace object, the source image of one, or the seam fills group in
|
||||
/// one.
|
||||
pub(crate) use buildcmds::{TRACE_NAME, is_seam_fills, is_trace_group, is_trace_source};
|
||||
|
||||
/// The shapes a group selected alone gives the Pathfinder panel.
|
||||
pub use pathops::shape_count;
|
||||
|
||||
|
||||
@@ -41,10 +41,10 @@ pub use live_paint::live_paint_gaps;
|
||||
pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation};
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_copy_region, sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
pub use trace::{
|
||||
TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target,
|
||||
};
|
||||
pub(crate) use trace::{TracePresetChanges, is_seam_fills, is_trace_group, is_trace_source};
|
||||
use trace::{
|
||||
trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view,
|
||||
};
|
||||
|
||||
@@ -17,12 +17,17 @@ thread_local! {
|
||||
|
||||
// ---------- Image Trace ----------
|
||||
|
||||
fn is_trace_group(n: &Node) -> bool {
|
||||
pub(crate) fn is_trace_group(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& n.name.as_deref() == Some(TRACE_NAME)
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// Whether object `id` of `d` is the source image an Image Trace object keeps as its first child.
|
||||
pub(crate) fn is_trace_source(d: &Document, id: NodeId) -> bool {
|
||||
d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id))
|
||||
}
|
||||
|
||||
/// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]).
|
||||
const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
|
||||
@@ -32,7 +37,7 @@ const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
/// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made
|
||||
/// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one
|
||||
/// of stroked paths without fills. (Auto Grouping groups hold filled paths.)
|
||||
fn is_seam_fills(n: &Node) -> bool {
|
||||
pub(crate) fn is_seam_fills(n: &Node) -> bool {
|
||||
let path = |m: &Arc<Node>| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
let stroke_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None;
|
||||
let fill_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None;
|
||||
@@ -774,8 +779,12 @@ pub fn image_trace_target(s: &Session, p: &Value) -> Result<NodeId> {
|
||||
fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObject>)> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// The source image an Image Trace object keeps is traced through that object, so it is never
|
||||
// the object traced, and naming only such images is an error.
|
||||
let source = |r: &NodeId| is_trace_source(d, *r);
|
||||
roots
|
||||
.iter()
|
||||
.filter(|r| !source(r))
|
||||
.find_map(|r| {
|
||||
let n = d.node(*r)?;
|
||||
match &n.kind {
|
||||
@@ -787,7 +796,10 @@ fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObj
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))
|
||||
.ok_or_else(|| match roots.iter().find(|r| source(r)) {
|
||||
Some(r) => bad(c, format!("object {} is the source image of an Image Trace object: trace that object", r.0)),
|
||||
None => bad(c, "select an image (or an Image Trace group)"),
|
||||
})
|
||||
}
|
||||
|
||||
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
|
||||
@@ -1076,10 +1088,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let recorded = serde_json::to_value(&q.params).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
s.note_journal("savedPreset", recorded);
|
||||
}
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now. A script's trace
|
||||
// stops when the script is asked to stop.
|
||||
let stop = s.script_in_run.then(|| s.script_interrupt());
|
||||
let Traced { raster, res, seams: seam_fills, .. } = match s.trace_hand_off.take() {
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| true)?,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| stop.as_ref().is_none_or(|i| !i.is_set()))?,
|
||||
};
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let mut warnings = keep_warnings(&trace, &res);
|
||||
@@ -1098,6 +1112,11 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
for (rgb, paint) in &library {
|
||||
by_color.entry(*rgb).or_insert(paint);
|
||||
}
|
||||
// A stop asked for after the trace's last check, or while a handed-in trace is applied, does
|
||||
// not commit the trace.
|
||||
if stop.as_ref().is_some_and(|i| i.is_set()) {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
let id = s.edit(label, |d, sel| {
|
||||
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut image = if is_trace_group(&src) {
|
||||
@@ -1206,6 +1225,18 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
// Tracing again keeps the tracing's own object settings: opacity, blend mode, its
|
||||
// appearance items, visibility and lock.
|
||||
if !expand && is_trace_group(&src) {
|
||||
g.visible = src.visible;
|
||||
g.locked = src.locked;
|
||||
g.opacity = src.opacity;
|
||||
g.blend = src.blend;
|
||||
g.isolate = src.isolate;
|
||||
g.knockout = src.knockout;
|
||||
g.knockout_shape = src.knockout_shape;
|
||||
g.appearance = src.appearance.clone();
|
||||
}
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for, and the Split
|
||||
// view's divider.
|
||||
@@ -1215,6 +1246,10 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
t["split"] = split.clone();
|
||||
}
|
||||
g.extras_mut().trace = Some(Box::new(t));
|
||||
// Records the objects this trace made: every object in the tracing.
|
||||
let mut made = vec![];
|
||||
g.walk(&mut |n| made.push(n.id));
|
||||
g.set_trace_made(&vectorcraft_doc::TraceMade::of(made.into_iter().filter(|i| *i != gid)));
|
||||
}
|
||||
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
|
||||
d.remove(target)?;
|
||||
@@ -1386,7 +1421,8 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.name = None;
|
||||
n.extras_mut().trace = None;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| !matches!(c.kind, NodeKind::Image(_)));
|
||||
let source = ch.first().map(|c| c.id);
|
||||
ch.retain(|c| Some(c.id) != source);
|
||||
}
|
||||
if by_color {
|
||||
let items = d.node(*g).and_then(Node::children).cloned().unwrap_or_default();
|
||||
|
||||
@@ -385,6 +385,16 @@ impl Session {
|
||||
self.prefs.copy_as_svg && !self.clipboard_svg_refused()
|
||||
}
|
||||
|
||||
/// After a Copy or Cut has filled the clipboard: counts it in [`Session::copies`] when it put
|
||||
/// something there, and marks the clipboard as holding a copy ([`Session::clipboard_copied`]).
|
||||
pub(crate) fn note_copy(&mut self) {
|
||||
let filled = !self.clipboard.is_empty();
|
||||
if filled {
|
||||
self.copies = self.copies.wrapping_add(1);
|
||||
}
|
||||
self.clipboard_copied = filled;
|
||||
}
|
||||
|
||||
/// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first
|
||||
/// artboard's centre) → the number of objects.
|
||||
pub(super) fn load_clipboard(&mut self, mut clip: Clipboard, p: &Value) -> Result<usize> {
|
||||
@@ -400,6 +410,7 @@ impl Session {
|
||||
}
|
||||
let count = clip.nodes.len();
|
||||
self.clipboard = clip;
|
||||
self.clipboard_copied = false;
|
||||
Ok(count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; 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",
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), 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 (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; 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
|
||||
),
|
||||
@@ -1221,6 +1221,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
clip.guides = guides;
|
||||
s.clipboard = clip;
|
||||
s.note_copy();
|
||||
Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() }))
|
||||
}
|
||||
|
||||
|
||||
@@ -265,6 +265,17 @@ pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)
|
||||
}
|
||||
|
||||
/// [`may_write`], and an error when something other than a regular file is at `path` (a folder):
|
||||
/// the check each file of a set gets before the first of them is written.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write_file(path: &str) -> Result<()> {
|
||||
may_write(path)?;
|
||||
match std::fs::metadata(path) {
|
||||
Ok(m) if !m.is_file() => Err(EngineError::Other(format!("{path}: not a file"))),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The most a file read during a script command holds, the limit an importer reads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES;
|
||||
|
||||
@@ -23,6 +23,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.plugin_events_batch_settled(open);
|
||||
}
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
|
||||
let (clipboard_copied, copies) = (s.clipboard_copied, s.copies);
|
||||
// The documents as they are now, whole: what a failed step brings back. Their art, history,
|
||||
// file, format and saved state share their data with the open ones until a step changes them.
|
||||
let start = s.docs.clone();
|
||||
@@ -48,6 +49,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.active = active;
|
||||
s.sync_front_profiles();
|
||||
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
|
||||
(s.clipboard_copied, s.copies) = (clipboard_copied, copies);
|
||||
s.pending_paint = None;
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1 {
|
||||
for (p, _) in &files {
|
||||
super::may_write(p)?;
|
||||
super::access::may_write_file(p)?;
|
||||
}
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
|
||||
@@ -1072,14 +1072,14 @@ impl SaveJob {
|
||||
return Ok(stopped);
|
||||
}
|
||||
// Every path is checked against the file access in force before the first file is
|
||||
// written. A refused file is not handed to `write`, so a writer that does not check the
|
||||
// file access writes none of the files; the error is the file access's own refusal, as
|
||||
// the writers that check it give.
|
||||
// written. A refused file, or a folder at a file's path, is not handed to `write`, so a
|
||||
// writer that does not check the file access writes none of the files; the error is the
|
||||
// file access's own refusal, as the writers that check it give.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1
|
||||
&& let Some(refused) = files
|
||||
.iter()
|
||||
.find_map(|(p, _)| super::may_write(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e }))
|
||||
&& let Some(refused) = files.iter().find_map(|(p, _)| {
|
||||
super::access::may_write_file(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })
|
||||
})
|
||||
{
|
||||
return Err(refused);
|
||||
}
|
||||
|
||||
@@ -1040,6 +1040,31 @@ fn a_save_canceled_after_its_first_file_writes_them_all() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save that writes several files, through a writer that does not check the file access in
|
||||
/// force, writes none of them when that access refuses one: the save refuses it itself.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_save_of_several_files_refused_by_the_file_access_writes_none_through_any_writer() {
|
||||
let d = tmp_dir("refused-files");
|
||||
let mut s = session(100.0, 100.0, 2);
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
let path = d.join("logo.eps").to_string_lossy().to_string();
|
||||
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
let mut written = vec![];
|
||||
let r = crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || {
|
||||
job.write(|p, b| {
|
||||
std::fs::write(p, b).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
written.push(p.to_string());
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("write authority is absent")), "{r:?}");
|
||||
assert!(written.is_empty(), "{written:?}");
|
||||
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "nothing written");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them.
|
||||
#[test]
|
||||
fn a_failed_save_does_not_stamp_the_documents_dates() {
|
||||
|
||||
@@ -415,6 +415,10 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option<Found> {
|
||||
Some(f)
|
||||
}
|
||||
|
||||
pub(crate) fn located_path(link: &LinkInfo, base: LinkBase) -> Option<String> {
|
||||
locate(link, base).map(|f| f.path)
|
||||
}
|
||||
|
||||
/// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`]
|
||||
/// finds each linked image's and placed document's file from `base` and from no document (as
|
||||
/// output reads them, [`full_linked_images`]), the plate files of their own of images placed from
|
||||
|
||||
@@ -858,6 +858,18 @@ pub fn find(s: &Session, name: &str) -> Option<DocSettings> {
|
||||
.or_else(|| CATEGORIES.iter().flat_map(|c| builtin(c, s.default_units())).find(|p| p.name.eq_ignore_ascii_case(name)))
|
||||
}
|
||||
|
||||
/// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names
|
||||
/// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without
|
||||
/// `preset`.
|
||||
fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<DocSettings> {
|
||||
let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) };
|
||||
let found = match str_param(p, "presetCategory") {
|
||||
Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))),
|
||||
None => find(s, name),
|
||||
};
|
||||
found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)")))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// New Document's starting settings: Letter in Preferences ▸ Units ▸ General.
|
||||
fn default_settings(&self) -> DocSettings {
|
||||
@@ -871,10 +883,7 @@ const RECENT: usize = 12;
|
||||
/// `file.new`: a new document from a preset and/or explicit settings.
|
||||
pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.new";
|
||||
let base = match str_param(p, "preset") {
|
||||
Some(name) => find(s, name).ok_or_else(|| bad(C, format!("no preset called `{name}` (see file.newPresets)")))?,
|
||||
None => s.default_settings(),
|
||||
};
|
||||
let base = preset_param(s, p, C)?;
|
||||
// A preset keeps its name in Recent unless its size changed (turning it doesn't count).
|
||||
let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
|
||||
let size = str_param(p, "preset").map(|_| sorted(&base));
|
||||
@@ -964,10 +973,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(str::trim)
|
||||
.filter(|n| !n.is_empty() && n.chars().count() <= 64)
|
||||
.ok_or_else(|| bad(C, "give the preset a name (1–64 characters)"))?;
|
||||
let base = match str_param(p, "preset") {
|
||||
Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?,
|
||||
None => s.default_settings(),
|
||||
};
|
||||
let base = preset_param(s, p, C)?;
|
||||
let mut preset = base.with_params_inner(p, C, s.replaying())?;
|
||||
preset.name = name.to_string();
|
||||
let saved = &mut s.prefs.new_doc_presets;
|
||||
|
||||
@@ -384,6 +384,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val
|
||||
}
|
||||
}
|
||||
s.clipboard = clip;
|
||||
s.note_copy();
|
||||
Ok(json!({"copied": copied}))
|
||||
}
|
||||
|
||||
|
||||
@@ -639,6 +639,8 @@ struct Saved {
|
||||
draw_mode: crate::DrawMode,
|
||||
draw_inside: Option<vectorcraft_doc::NodeId>,
|
||||
clipboard: crate::Clipboard,
|
||||
clipboard_copied: bool,
|
||||
copies: u64,
|
||||
untitled_counter: u32,
|
||||
explicit_undo_group: Option<Option<String>>,
|
||||
prefs: crate::Prefs,
|
||||
@@ -664,6 +666,8 @@ impl Saved {
|
||||
draw_mode: s.draw_mode,
|
||||
draw_inside: s.draw_inside,
|
||||
clipboard: s.clipboard.clone(),
|
||||
clipboard_copied: s.clipboard_copied,
|
||||
copies: s.copies,
|
||||
untitled_counter: s.untitled_counter,
|
||||
explicit_undo_group: s.explicit_undo_group.clone(),
|
||||
prefs: s.prefs.clone(),
|
||||
@@ -688,6 +692,8 @@ impl Saved {
|
||||
s.draw_mode = self.draw_mode;
|
||||
s.draw_inside = self.draw_inside;
|
||||
s.clipboard = self.clipboard;
|
||||
s.clipboard_copied = self.clipboard_copied;
|
||||
s.copies = self.copies;
|
||||
s.untitled_counter = self.untitled_counter;
|
||||
s.explicit_undo_group = self.explicit_undo_group;
|
||||
s.prefs = self.prefs;
|
||||
|
||||
@@ -419,8 +419,9 @@ impl FolderStore {
|
||||
|
||||
/// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on
|
||||
/// Windows they must be the same file (volume serial number and file index); elsewhere `path`
|
||||
/// must exist. When either file can't be read, it does not.
|
||||
fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool {
|
||||
/// must exist. A link at `path` is not followed, so it names the link and not `file`. When
|
||||
/// either file can't be read, it does not.
|
||||
pub(crate) fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
@@ -431,8 +432,19 @@ impl FolderStore {
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::OpenOptionsExt as _;
|
||||
// FILE_FLAG_OPEN_REPARSE_POINT opens a link itself rather than its target, and
|
||||
// FILE_FLAG_BACKUP_SEMANTICS lets a folder be opened, as `same_file::Handle::from_path`
|
||||
// opens one.
|
||||
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
|
||||
let opened = file.try_clone().and_then(same_file::Handle::from_file);
|
||||
match (opened, same_file::Handle::from_path(path)) {
|
||||
let named = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
|
||||
.open(path)
|
||||
.and_then(same_file::Handle::from_file);
|
||||
match (opened, named) {
|
||||
(Ok(a), Ok(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, contai
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, contai
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
|
||||
@@ -66,6 +66,10 @@ pub struct Session {
|
||||
pub fill_active: bool,
|
||||
/// Internal clipboard: the copied objects and the document resources they use.
|
||||
pub clipboard: Clipboard,
|
||||
/// How many times Copy or Cut has put art, guides or artboards on [`Self::clipboard`].
|
||||
pub(crate) copies: u64,
|
||||
/// [`Self::clipboard`] holds what the last Copy or Cut put there, not what an import put there.
|
||||
pub(crate) clipboard_copied: bool,
|
||||
/// Executed commands (for actions and debugging), the most recent ones kept ([`Journal`]).
|
||||
pub journal: Journal,
|
||||
/// About the most memory the undo steps of all the open documents may keep together
|
||||
@@ -541,7 +545,7 @@ use history::history_budget_for;
|
||||
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
|
||||
pub(crate) use interaction::{HeldInteraction, PreviewCopies};
|
||||
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
|
||||
pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs};
|
||||
pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs, ScriptPreference};
|
||||
pub use sanity::TOO_DEEP;
|
||||
pub(crate) use sanity::{deselect_hidden, is_guide_path};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -463,6 +463,34 @@ pub struct Prefs {
|
||||
/// preferences keeps it.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub import_matches: Vec<cmd::importmatches::ImportMatch>,
|
||||
/// The values scripts store with `app.preferences` under keys that are not VectorCraft
|
||||
/// preferences. Not a Preferences dialog field: it has no [`cmd::prefscmds::PREF_SPECS`] row,
|
||||
/// and resetting the preferences keeps it.
|
||||
#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub script_preferences: std::collections::BTreeMap<String, ScriptPreference>,
|
||||
}
|
||||
|
||||
/// A value a script stored with `app.preferences`, with the type it was stored as. Two real
|
||||
/// values are equal when their bits are, so 0 and -0 differ.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScriptPreference {
|
||||
Boolean(bool),
|
||||
Integer(i64),
|
||||
Real(f64),
|
||||
String(String),
|
||||
}
|
||||
|
||||
impl PartialEq for ScriptPreference {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Boolean(a), Self::Boolean(b)) => a == b,
|
||||
(Self::Integer(a), Self::Integer(b)) => a == b,
|
||||
(Self::Real(a), Self::Real(b)) => a.to_bits() == b.to_bits(),
|
||||
(Self::String(a), Self::String(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The default Hold Shortcut Delay, in seconds (VectorCraft's own value).
|
||||
@@ -712,6 +740,7 @@ impl Default for Prefs {
|
||||
blend_options: None,
|
||||
perspective_widget: Default::default(),
|
||||
import_matches: vec![],
|
||||
script_preferences: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -200,6 +200,13 @@ fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the app does when the person answers Yes to a confirm it opens for a script ([`Dialogs::ask`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum OnYes {
|
||||
/// Turn off the warning before a script picked with File › Scripts › Other Script… runs.
|
||||
ExternalScriptWarningOff,
|
||||
}
|
||||
|
||||
/// The dialogs of one run: the answers left for a run with nobody to ask, the dialog that waits
|
||||
/// for the person's answer, and the list the report gives.
|
||||
pub(crate) struct Dialogs {
|
||||
@@ -209,6 +216,10 @@ pub(crate) struct Dialogs {
|
||||
can_wait: Rc<Cell<bool>>,
|
||||
answers: RefCell<VecDeque<DialogAnswer>>,
|
||||
waiting: RefCell<Option<ScriptDialog>>,
|
||||
/// What Yes to the waiting dialog does, when the app opened it with [`Dialogs::ask`].
|
||||
on_yes: Cell<Option<OnYes>>,
|
||||
/// What the person approved with Yes, until [`Dialogs::take_approved`] takes it.
|
||||
approved: Cell<Option<OnYes>>,
|
||||
/// The error that ended the run when an answer could not reach the script.
|
||||
failed: RefCell<Option<RunError>>,
|
||||
records: RefCell<Vec<Value>>,
|
||||
@@ -233,6 +244,8 @@ impl Dialogs {
|
||||
can_wait: realm.wait_flag(),
|
||||
answers: RefCell::new(answers.into()),
|
||||
waiting: RefCell::default(),
|
||||
on_yes: Cell::new(None),
|
||||
approved: Cell::new(None),
|
||||
failed: RefCell::default(),
|
||||
records: RefCell::default(),
|
||||
record_bytes: Cell::new(0),
|
||||
@@ -444,14 +457,45 @@ impl Dialogs {
|
||||
let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false };
|
||||
self.record(d, answer.json());
|
||||
*waiting = None;
|
||||
if let Err(e) = realm.answer(answer.data()) {
|
||||
let on_yes = self.on_yes.take();
|
||||
// A confirm the app opened returns `undefined` to the call that opened it.
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { answer.data() };
|
||||
if answer == DialogAnswer::Confirm(true) {
|
||||
self.approved.set(on_yes);
|
||||
}
|
||||
if let Err(e) = realm.answer(data) {
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens `dialog`, a confirm the app shows for the script, whose Yes does `on_yes`; the call
|
||||
/// that opens it then waits ([`HostError::Wait`]) and returns `undefined`. Only a person answers
|
||||
/// it, never `script.run`'s `answers`. → false when it cannot open: the run has nobody to ask,
|
||||
/// or the call comes from a callback, a getter, a conversion or a file `$.evalFile` runs.
|
||||
pub(crate) fn ask(&self, dialog: ScriptDialog, on_yes: OnYes) -> bool {
|
||||
if !self.framed || !self.can_wait.get() {
|
||||
return false;
|
||||
}
|
||||
*self.waiting.borrow_mut() = Some(dialog);
|
||||
self.on_yes.set(Some(on_yes));
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the waiting dialog is the confirm [`Dialogs::ask`] opened to turn off the external
|
||||
/// script warning, whatever a script's own dialogs say.
|
||||
pub(crate) fn asks_warning_off(&self) -> bool {
|
||||
self.waiting.borrow().is_some() && self.on_yes.get() == Some(OnYes::ExternalScriptWarningOff)
|
||||
}
|
||||
|
||||
/// What the person approved with Yes to a confirm from [`Dialogs::ask`], once.
|
||||
pub(crate) fn take_approved(&self) -> Option<OnYes> {
|
||||
self.approved.take()
|
||||
}
|
||||
|
||||
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`.
|
||||
pub(crate) fn stopped(&self) {
|
||||
self.on_yes.set(None);
|
||||
if let Some(d) = self.waiting.borrow_mut().take() {
|
||||
self.record(&d, json!("stop"));
|
||||
}
|
||||
|
||||
+278
-49
@@ -52,8 +52,8 @@
|
||||
//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at
|
||||
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
|
||||
//! error. A run that fails leaves the tool as it was.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
//! in the object.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the anchors and direction points of
|
||||
//! the paths in the object; a clipping group counts its clipping path only.
|
||||
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
|
||||
//! in view-number order, and none without one. View objects keep their window's identity when
|
||||
//! windows are renumbered. The screen mode is the app's:
|
||||
@@ -97,10 +97,16 @@ use vectorcraft_js::{
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod clipboard;
|
||||
mod images;
|
||||
mod matrix;
|
||||
pub mod preferences;
|
||||
mod print;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
mod tracing;
|
||||
mod transform;
|
||||
mod variables;
|
||||
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
@@ -127,6 +133,10 @@ pub(crate) use paths::POINT_LOOKS;
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
/// The error for an object that was deleted, or that came from an earlier run.
|
||||
pub const STALE_ITEM: &str = "Stale page item";
|
||||
/// The error for a new name given to a `PluginItem`.
|
||||
const TRACING_NAME: &str = "The name of a tracing cannot be changed";
|
||||
/// The error for the tracing's name given to a group that holds an image first.
|
||||
const NOT_A_TRACING: &str = "Only Image Trace can make a tracing";
|
||||
/// The error for a document that was closed, or that came from an earlier run.
|
||||
pub const STALE_DOCUMENT: &str = "Stale document";
|
||||
/// The error of `index` and `getByName` when nothing matches.
|
||||
@@ -158,6 +168,7 @@ const ITEM_CLASSES: &[&str] = &[
|
||||
"RepeatItem",
|
||||
"PlacedDocumentItem",
|
||||
"IntertwineItem",
|
||||
"PluginItem",
|
||||
];
|
||||
|
||||
/// `app.coordinateSystem`.
|
||||
@@ -217,6 +228,10 @@ pub(super) struct State {
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
vars: variables::Handles,
|
||||
/// What the placed and raster items keep ([`images::State`]).
|
||||
images: images::State,
|
||||
/// What the tracings keep ([`tracing::State`]).
|
||||
tracing: tracing::State,
|
||||
tool: Cell<Option<&'static str>>,
|
||||
}
|
||||
|
||||
@@ -443,7 +458,7 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
|
||||
"Document" => {
|
||||
doc_of(&h, arg(&a, 0), "Document")?;
|
||||
}
|
||||
"PageItem" | "PathItem" | "TextFrame" => {
|
||||
"PageItem" | "PathItem" | "TextFrame" | "PlacedItem" | "RasterItem" => {
|
||||
item_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
"PathPoint" => {
|
||||
@@ -583,16 +598,25 @@ fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> {
|
||||
Some((doc, id_of(high, low)?))
|
||||
}
|
||||
|
||||
/// The page item `d` names, which must still be in its document.
|
||||
/// The page item `d` names, which must still be in its document and still be of its class (an
|
||||
/// embedded `PlacedItem` is a `RasterItem` after, and its old object is stale).
|
||||
fn item_of(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) };
|
||||
if handle.len() != 5 {
|
||||
let Some((class, handle)) = host_ref_parts(d).filter(|(c, _)| ITEM_CLASSES.contains(c)) else {
|
||||
return Err(HostError::Type("this is not a page item".into()));
|
||||
}
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
};
|
||||
let (doc, id) = match handle.as_slice() {
|
||||
[_, _, _, _, _] => node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?,
|
||||
&[run, uid, _, _, _, slot] => {
|
||||
let id = images::pending_id(h, run, uid, slot)?;
|
||||
(find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?, id)
|
||||
}
|
||||
_ => return Err(HostError::Type("this is not a page item".into())),
|
||||
};
|
||||
let original = id;
|
||||
let id = if class == "PluginItem" { tracing::follow(h, doc.uid, id) } else { id };
|
||||
let s = h.session.borrow();
|
||||
let st = &s.documents()[doc.index];
|
||||
if st.doc.node(id).is_none_or(|n| typename(n).is_none()) {
|
||||
if st.doc.node(id).is_none_or(|n| typename(n) != Some(class) || (class == "PluginItem" && !tracing::same_source(h, doc.uid, original, n))) {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
}
|
||||
Ok(Item { doc, id })
|
||||
@@ -603,6 +627,7 @@ fn typename(n: &crate::doc::Node) -> Option<&'static str> {
|
||||
Some(match &n.kind {
|
||||
NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None,
|
||||
NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem",
|
||||
NodeKind::Group { .. } if crate::cmd::is_trace_group(n) => "PluginItem",
|
||||
NodeKind::Group { .. } => "GroupItem",
|
||||
NodeKind::Path { .. } => "PathItem",
|
||||
NodeKind::Compound { .. } => "CompoundPathItem",
|
||||
@@ -626,6 +651,11 @@ fn doc_ref(h: &Host, uid: u64) -> Data {
|
||||
fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
match st.doc.node(id) {
|
||||
Some(n) => match typename(n) {
|
||||
Some("PlacedItem") => images::bound_ref(h, st, id).unwrap_or_else(|| host_ref("PlacedItem", &node_handle(h, st, id))),
|
||||
Some("PluginItem") => {
|
||||
tracing::remember_source(h, st.uid, n);
|
||||
host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id)))
|
||||
}
|
||||
Some(t) => host_ref(t, &node_handle(h, st, id)),
|
||||
None => host_ref("Layer", &node_handle(h, st, id)),
|
||||
},
|
||||
@@ -649,7 +679,10 @@ fn page_items(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, H
|
||||
_ => {
|
||||
out.push(n.id);
|
||||
if let Some(children) = n.children() {
|
||||
walk(children, out);
|
||||
// The source image an Image Trace object keeps hidden as its first child is
|
||||
// reached through that object's `tracing`.
|
||||
let source = usize::from(crate::cmd::is_trace_group(n));
|
||||
walk(children.get(source..).unwrap_or_default(), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -686,9 +719,11 @@ fn top_items(d: &Document) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `n` and every object inside it are shown and unlocked.
|
||||
/// Whether `n` and every object inside it are shown and unlocked. The source image an Image Trace
|
||||
/// object keeps hidden as its first child is part of that object and is not counted.
|
||||
fn all_editable(n: &crate::doc::Node) -> bool {
|
||||
n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c)))
|
||||
let source = usize::from(crate::cmd::is_trace_group(n));
|
||||
n.visible && !n.locked && n.children().is_none_or(|c| c.iter().skip(source).all(|c| all_editable(c)))
|
||||
}
|
||||
|
||||
/// Whether the object and every layer and group it is in are shown and unlocked.
|
||||
@@ -881,7 +916,8 @@ fn restore_layer(h: &Host, uid: u64, layer: Option<NodeId>, rows: &[NodeId]) ->
|
||||
/// commands changed it (commands given ids select them first), direct-selected anchors, segments,
|
||||
/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic
|
||||
/// symbol instance or an Objects on Path group included, less the objects that are now deleted,
|
||||
/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together
|
||||
/// hidden or locked; the current layer, which selecting art changes, is put back too while it is
|
||||
/// still a layer that can be edited. `f`'s commands and the steps that put things back succeed or fail together
|
||||
/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s
|
||||
/// changes are undone as well.
|
||||
fn on_doc<T>(
|
||||
@@ -2307,6 +2343,28 @@ fn item_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
// An Image Trace object is known by its name, so renaming one would end the tracing, and giving
|
||||
// an ordinary group that holds an image first the tracing's name would make it one.
|
||||
let item = this_item(h, a)?;
|
||||
let refused = with_doc(h, item.doc, |_, st| {
|
||||
st.doc.node(item.id).and_then(|n| {
|
||||
let tracing = crate::cmd::is_trace_group(n);
|
||||
let would_trace = !tracing
|
||||
&& name == crate::cmd::TRACE_NAME
|
||||
&& matches!(n.kind, crate::doc::NodeKind::Group { clip: false, .. })
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, crate::doc::NodeKind::Image(_))));
|
||||
if tracing && n.name.as_deref() != Some(&**name) {
|
||||
Some(TRACING_NAME)
|
||||
} else if would_trace {
|
||||
Some(NOT_A_TRACING)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
});
|
||||
if let Some(msg) = refused {
|
||||
return Err(HostError::Error(msg.into()));
|
||||
}
|
||||
set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name}))
|
||||
}
|
||||
|
||||
@@ -2502,24 +2560,26 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
|
||||
bounds(h, a, true)
|
||||
}
|
||||
|
||||
/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in
|
||||
/// the object.
|
||||
/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an
|
||||
/// object with nothing in it.
|
||||
fn item_control(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
// An object with nothing in it reads zeros, as its other bounds do.
|
||||
let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) };
|
||||
let r = with_doc(h, item.doc, |_, st| {
|
||||
let mut r = r;
|
||||
if let Some(n) = st.doc.node(item.id) {
|
||||
n.walk(&mut |c| {
|
||||
if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) {
|
||||
r = r.union(handles);
|
||||
}
|
||||
});
|
||||
}
|
||||
r
|
||||
});
|
||||
Ok(f.bounds(h.dom.coords.get(), r))
|
||||
let (r, f) = item_rect(h, item, true)?;
|
||||
let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds));
|
||||
match r.into_iter().chain(handles).reduce(|a, b| a.union(b)) {
|
||||
Some(r) => Ok(f.bounds(h.dom.coords.get(), r)),
|
||||
None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown
|
||||
/// paths in its children (a clip group's from its clipping path).
|
||||
fn handle_bounds(n: &crate::doc::Node) -> Option<Rect> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.control_bounds(),
|
||||
NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)),
|
||||
_ => n.children().and_then(|children| children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b))),
|
||||
}
|
||||
}
|
||||
|
||||
fn item_position(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -2688,6 +2748,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
// An image left first in an ordinary group named as a tracing would make that group one.
|
||||
if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
// A compound path whose last path this is stays, empty, as it does after `move`.
|
||||
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?;
|
||||
Ok(Data::Undefined)
|
||||
@@ -2741,14 +2805,20 @@ struct Destination {
|
||||
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
|
||||
let how = placement_of(how)?;
|
||||
let beside = matches!(how, Placement::Above | Placement::Below);
|
||||
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
|
||||
let Some(handle) = handle.filter(|parts| parts.len() == 5) else {
|
||||
if handle_of(target, "Document").is_some() {
|
||||
return Err(HostError::Error("a document as the relative object is not available yet".into()));
|
||||
}
|
||||
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
|
||||
// A page item is looked up as its class names it (a wrapper whose object changed class is
|
||||
// stale), a layer by its handle.
|
||||
let (doc, target) = if handle_of(target, "PageItem").is_some() {
|
||||
let t = item_of(h, target)?;
|
||||
(t.doc, t.id)
|
||||
} else {
|
||||
let Some(handle) = handle_of(target, "Layer").filter(|parts| parts.len() == 5) else {
|
||||
if handle_of(target, "Document").is_some() {
|
||||
return Err(HostError::Error("a document as the relative object is not available yet".into()));
|
||||
}
|
||||
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
|
||||
};
|
||||
node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?
|
||||
};
|
||||
let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
if doc.uid != item.doc.uid {
|
||||
return Err(HostError::Error(CROSS_DOCUMENT.into()));
|
||||
}
|
||||
@@ -2788,17 +2858,64 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
|
||||
let name = d.node(item.id).and_then(typename).unwrap_or("page item");
|
||||
return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0)));
|
||||
}
|
||||
// Checked here as well as in `place`, so `duplicate` refuses before it makes the copy. A
|
||||
// tracing's source image moved out keeps the error `place` gives it.
|
||||
let image = d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)));
|
||||
if image && (copy || !crate::cmd::is_trace_source(d, item.id)) && named_as_tracing(d, parent) {
|
||||
// Where the image comes from: its index in `parent` when it is already there.
|
||||
let own = d.position(item.id).and_then(|(p, i, _)| (p == Some(parent)).then_some(i)).filter(|_| !copy);
|
||||
let count = d.children(Some(parent)).map_or(0, Vec::len);
|
||||
let first = match how {
|
||||
Placement::Bottom => true,
|
||||
Placement::Top => count == usize::from(own.is_some()),
|
||||
Placement::Below => beside.and_then(|b| d.position(b)).is_some_and(|(_, i, _)| i == 0 || (i == 1 && own == Some(0))),
|
||||
Placement::Above => false,
|
||||
};
|
||||
if first {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
}
|
||||
Ok(Destination { parent, beside, how })
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `id` is an ordinary group named as an Image Trace object that is not one: an image put
|
||||
/// first in it would make it a tracing.
|
||||
fn named_as_tracing(d: &Document, id: NodeId) -> bool {
|
||||
d.node(id).is_some_and(|p| {
|
||||
!crate::cmd::is_trace_group(p) && matches!(p.kind, NodeKind::Group { clip: false, .. }) && p.name.as_deref() == Some(crate::cmd::TRACE_NAME)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether taking the object `id` out of `parent` and, with `at`, putting it back at that index of
|
||||
/// what is left would make `parent`, an ordinary group named as a tracing, one: an image first in it.
|
||||
fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option<usize>) -> bool {
|
||||
if !named_as_tracing(d, parent) {
|
||||
return false;
|
||||
}
|
||||
let image = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Image(_));
|
||||
let rest = d.children(Some(parent)).map(|c| c.iter().filter(|n| n.id != id).collect::<Vec<_>>()).unwrap_or_default();
|
||||
match at {
|
||||
Some(0) => d.node(id).is_some_and(image),
|
||||
_ => rest.first().is_some_and(|n| image(n)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place.
|
||||
fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> {
|
||||
let index = with_doc(h, doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let from = d.position(id);
|
||||
let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent)));
|
||||
let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0;
|
||||
// A clip group's first child is its clipping path, and an Image Trace object's its source
|
||||
// image: both stay first, and the source image moved within its own tracing stays where it is.
|
||||
if crate::cmd::is_trace_source(d, id) {
|
||||
if d.parent_of(id) == Some(to.parent) {
|
||||
return Ok(0);
|
||||
}
|
||||
return Err(HostError::Error("a tracing's source image cannot leave its tracing".into()));
|
||||
}
|
||||
let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0;
|
||||
let at = match (to.how, to.beside) {
|
||||
(Placement::Top, _) => count,
|
||||
(Placement::Bottom, _) => 0,
|
||||
@@ -2814,7 +2931,22 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
|
||||
}
|
||||
(_, None) => count,
|
||||
};
|
||||
Ok::<_, HostError>(if clips { at.max(1) } else { at })
|
||||
let at = if clips { at.max(1) } else { at };
|
||||
// The index `node.move` puts the object at: art stays below the ruler guides.
|
||||
// This is `Node::insert_index` on the parent's children without the object, read in place
|
||||
// so that no list of them is copied.
|
||||
let node = d.node(id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let rest = || d.children(Some(to.parent)).into_iter().flatten().filter(|n| n.id != id);
|
||||
let start = rest().enumerate().filter(|(_, n)| !n.is_ruler_guide()).last().map_or(0, |(i, _)| i + 1);
|
||||
let i = at.min(rest().count());
|
||||
let at = if node.is_ruler_guide() { i.max(start) } else { i.min(start) };
|
||||
// An image left or put first in an ordinary group named as a tracing would make that group
|
||||
// one, in the group it leaves as in the group it goes into.
|
||||
let left = from.and_then(|(p, ..)| p).filter(|p| *p != to.parent);
|
||||
if makes_tracing(d, to.parent, id, Some(at)) || left.is_some_and(|p| makes_tracing(d, p, id, None)) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
Ok::<_, HostError>(at)
|
||||
})?;
|
||||
let now = with_doc(h, doc, |_, st| st.doc.position(id));
|
||||
if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) {
|
||||
@@ -2909,22 +3041,50 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
// The Arrange commands keep a clipping path at the bottom of its parent and the art below the
|
||||
// parent's ruler guides, so the item's place is counted among the art above the clipping path.
|
||||
let (before, floor, art) = with_doc(h, item.doc, |_, st| {
|
||||
// The source image an Image Trace object keeps first stays first, and the other objects in it
|
||||
// stay above it.
|
||||
let (before, floor, art, parent, source, in_trace) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let at = d.position(item.id);
|
||||
let parent = at.and_then(|(p, ..)| p);
|
||||
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips));
|
||||
let in_trace = parent.and_then(|p| d.node(p)).is_some_and(crate::cmd::is_trace_group);
|
||||
let clips = parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips);
|
||||
let floor = usize::from(clips || in_trace);
|
||||
let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c));
|
||||
(at.map(|(_, i, _)| i), floor, art)
|
||||
(at.map(|(_, i, _)| i), floor, art, parent, crate::cmd::is_trace_source(d, item.id), in_trace)
|
||||
});
|
||||
let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) };
|
||||
if source {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let unchanged = i < floor
|
||||
|| match id {
|
||||
"object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art,
|
||||
_ => i <= floor,
|
||||
};
|
||||
if !unchanged {
|
||||
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
|
||||
if unchanged {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
// Where the Arrange command puts the item among its parent's art, worked out as
|
||||
// `object.arrange` works it out for one object. An image put first, or another object moved
|
||||
// from above an image that becomes first, in an ordinary group named as a tracing would make
|
||||
// that group one.
|
||||
let to = match id {
|
||||
"object.arrange.bringToFront" => art - 1,
|
||||
"object.arrange.bringForward" => i + 1,
|
||||
"object.arrange.sendBackward" => i - 1,
|
||||
_ => floor,
|
||||
};
|
||||
if parent.is_some_and(|p| with_doc(h, item.doc, |_, st| makes_tracing(&st.doc, p, item.id, Some(to)))) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
match parent {
|
||||
Some(p) if in_trace && id == "object.arrange.sendToBack" => {
|
||||
edit_item(h, item, "node.move", &json!({"id": item.id.0, "parent": p.0, "index": floor}))?;
|
||||
}
|
||||
_ => {
|
||||
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
|
||||
}
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -3004,6 +3164,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]),
|
||||
("DocumentColorSpace", &["CMYK", "RGB"]),
|
||||
("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]),
|
||||
("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]),
|
||||
("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]),
|
||||
("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]),
|
||||
("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]),
|
||||
@@ -3029,7 +3190,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) {
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
@@ -3067,6 +3228,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(preferences::app_members());
|
||||
application.extend(matrix::app_members(l));
|
||||
application.extend(clipboard::app_members(l));
|
||||
application.extend(save_open::application_members(l));
|
||||
application.extend(print::application_members(l));
|
||||
application.extend(super::actions::app_members(l));
|
||||
@@ -3086,6 +3250,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
};
|
||||
let mut classes = vec![
|
||||
class("Application", None, application, None),
|
||||
preferences::class(l),
|
||||
preset,
|
||||
class(
|
||||
"Documents",
|
||||
@@ -3151,6 +3316,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(print::document_members(l));
|
||||
document.extend(images::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
@@ -3225,6 +3391,69 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("remove", method(l, item_remove), returns("undefined", &[])),
|
||||
("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
|
||||
("toString", method(l, item_to_string), returns("string", &[])),
|
||||
(
|
||||
"translate",
|
||||
method(l, transform::translate),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("deltaX", "number"),
|
||||
("deltaY", "number"),
|
||||
("transformObjects", "boolean"),
|
||||
("transformFillPatterns", "boolean"),
|
||||
("transformFillGradients", "boolean"),
|
||||
("transformStrokePatterns", "boolean"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"rotate",
|
||||
method(l, transform::rotate),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("angle", "number"),
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
("rotateAbout", "Transformation"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"resize",
|
||||
method(l, transform::resize),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("scaleX", "number"),
|
||||
("scaleY", "number"),
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
("changeLineWidths", "number"),
|
||||
("scaleAbout", "Transformation"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"transform",
|
||||
method(l, transform::transform),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("transformationMatrix", "Matrix"),
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
("changeLineWidths", "number"),
|
||||
("transformAbout", "Transformation"),
|
||||
],
|
||||
),
|
||||
),
|
||||
]);
|
||||
page_item.extend(
|
||||
[
|
||||
@@ -3239,17 +3468,14 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
"wrapOffset",
|
||||
"wrapped",
|
||||
"bringInPerspective",
|
||||
"resize",
|
||||
"rotate",
|
||||
"transform",
|
||||
"translate",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "PageItem", m)),
|
||||
);
|
||||
page_item.extend(variables::page_item_members(l));
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| {
|
||||
let own = |c: &&&str| **c == "TextFrame" || images::CLASSES.contains(c) || tracing::CLASSES.contains(c);
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| {
|
||||
let mut members = variables::item_members(l, c);
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
@@ -3260,6 +3486,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(images::classes(l));
|
||||
tracing::add_trace(&mut classes, l);
|
||||
classes.extend(tracing::classes(l));
|
||||
classes.extend(save_open::classes(l));
|
||||
classes.extend(print::classes(l));
|
||||
classes.push(class(
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//! `app.copy()`, `app.cut()` and `app.paste()`, as the help page
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> describes them: Edit › Copy, Cut
|
||||
//! and Paste on the active document, run as `edit.copy`, `edit.cut` and `edit.paste` in the run's
|
||||
//! transaction.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help page does not state: with nothing selected, or no
|
||||
//! document open, `copy` and `cut` do nothing; with the clipboard empty `paste` does nothing; and
|
||||
//! `paste` with no document open throws `No active document`. `paste` takes the session's
|
||||
//! clipboard, not art another app copied since. A run that finishes after a Copy or Cut, by any
|
||||
//! command, with the clipboard still holding what it copied, reports `copied`, and the desktop app
|
||||
//! then offers the clipboard to other apps.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostError};
|
||||
|
||||
use super::{Answer, Described, Host, Link, NO_ACTIVE_DOCUMENT, command, method, named, returns};
|
||||
|
||||
/// The clipboard functions of `Application`.
|
||||
pub(super) fn app_members(link: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("copy", method(link, copy), returns("undefined", &[])),
|
||||
("cut", method(link, cut), returns("undefined", &[])),
|
||||
("paste", method(link, paste), returns("undefined", &[])),
|
||||
])
|
||||
}
|
||||
|
||||
/// Runs `id` when the active document has something it acts on.
|
||||
fn on_selection(h: &Host, id: &str) -> Answer {
|
||||
let ready = crate::cmd::has_selection_guides_or_artboard_tool(&h.session.borrow()).is_ok();
|
||||
if ready {
|
||||
command(h, id, &json!({}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn copy(h: &Host, _: &[Data]) -> Answer {
|
||||
on_selection(h, "edit.copy")
|
||||
}
|
||||
|
||||
fn cut(h: &Host, _: &[Data]) -> Answer {
|
||||
on_selection(h, "edit.cut")
|
||||
}
|
||||
|
||||
fn paste(h: &Host, _: &[Data]) -> Answer {
|
||||
let ready = {
|
||||
let s = h.session.borrow();
|
||||
if s.active().is_none() {
|
||||
return Err(HostError::Error(NO_ACTIVE_DOCUMENT.into()));
|
||||
}
|
||||
!s.clipboard.is_empty()
|
||||
};
|
||||
if ready {
|
||||
command(h, "edit.paste", &json!({}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
//! Placed and raster art in the script object model: `Document.placedItems` and
|
||||
//! `Document.rasterItems`, and the members of `PlacedItem` and `RasterItem`, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/> describe them.
|
||||
//!
|
||||
//! A `PlacedItem` is an image linked to its file, and a `RasterItem` an image whose pixels are in
|
||||
//! the document. Placing runs `file.place` with `link`, relinking `links.relink` and embedding
|
||||
//! `links.embed`, so each joins the run's transaction.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `PlacedItems.add()` gives a placed item with no file. Its `file` may be assigned once, which
|
||||
//! places the file linked; after that, and on every other placed item, `file` is read-only and
|
||||
//! `relink(file)` changes it. Every other member of an item with no file throws
|
||||
//! [`FILE_REQUIRED`]; an item with no file is not in the document and is dropped when the run
|
||||
//! ends.
|
||||
//! - A file to place or relink is a `File` the script may read ([`crate::file_access::ScriptGate`])
|
||||
//! that holds an image, of at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is.
|
||||
//! - `PlacedItem.file` throws `Script file access denied`, without the path, when the script may
|
||||
//! not read the linked file.
|
||||
//! - `embed()` turns the placed item into a raster item with the same id: the placed item is stale
|
||||
//! after it, and `rasterItems` lists the raster item. An image whose file is missing throws
|
||||
//! [`MISSING_LINK`] and stays linked.
|
||||
//! - `bitsPerChannel`, `channels`, `imageColorSpace` and `transparent` come from the header of the
|
||||
//! image's encoded pixels; `transparent` is true for an image with an alpha channel or a
|
||||
//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only
|
||||
//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file.
|
||||
//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of
|
||||
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a
|
||||
//! matrix with no area or one that puts a corner of the image outside the canvas is refused.
|
||||
//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, file_ref, file_ref_path, host_ref, host_ref_parts};
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, command_value,
|
||||
doc_of, doc_ref, edit_item, editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property,
|
||||
returns, text, typed, typename_of, variables, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
|
||||
/// The error of a member of a `PlacedItems.add()` result whose `file` was not assigned.
|
||||
pub const FILE_REQUIRED: &str = "PlacedItem.file is required";
|
||||
/// The error of assigning `file` to a placed item that has one.
|
||||
pub const FILE_READ_ONLY: &str = "PlacedItem.file is read-only: use relink";
|
||||
/// The error of embedding an image whose linked file cannot be found.
|
||||
pub const MISSING_LINK: &str = "Linked image is missing";
|
||||
/// The error of placing or relinking a file that is not an image.
|
||||
pub const NOT_AN_IMAGE: &str = "The file is not an image";
|
||||
/// The largest file a script places or relinks, in bytes.
|
||||
pub const MAX_PLACED_BYTES: u64 = 256 << 20;
|
||||
/// The most `PlacedItems.add()` results one run keeps.
|
||||
pub const MAX_PENDING: usize = 1024;
|
||||
/// The error of the `matrix` of an image drawn distorted.
|
||||
const DISTORTED: &str = "the image is distorted and has no matrix";
|
||||
/// The smallest determinant a `matrix` takes, in square points a square pixel.
|
||||
const MIN_DETERMINANT: f64 = 1e-12;
|
||||
/// The members of a `Matrix` record, in the order of an affine matrix's six numbers.
|
||||
const MATRIX_KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"];
|
||||
|
||||
/// The enumerations the members here give values of, as the help page
|
||||
/// <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/> lists them.
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("ImageColorSpace", &["CMYK", "DeviceN", "Grayscale", "Indexed", "LAB", "RGB", "Separation"]),
|
||||
("RasterLinkState", &["DATAFROMFILE", "DATAMODIFIED", "NODATA"]),
|
||||
];
|
||||
|
||||
/// The classes this module defines, in place of the plain page item classes.
|
||||
pub(super) const CLASSES: &[&str] = &["PlacedItem", "RasterItem"];
|
||||
|
||||
/// A document's uid, the document as it was, and the ids of its linked and embedded images then.
|
||||
type Lists = (u64, Arc<Document>, Rc<Vec<NodeId>>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// What a run keeps for placed and raster items: the `PlacedItems.add()` results and the last
|
||||
/// lists of a document's images.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
pending: RefCell<Vec<Pending>>,
|
||||
lists: RefCell<Option<Lists>>,
|
||||
}
|
||||
|
||||
/// A `PlacedItems.add()` result: its document, how many times that document had been reverted then,
|
||||
/// and its image once `file` placed one.
|
||||
struct Pending {
|
||||
uid: u64,
|
||||
reverts: u64,
|
||||
bound: Option<NodeId>,
|
||||
}
|
||||
|
||||
pub(super) fn bound_ref(h: &Host, st: &DocState, id: NodeId) -> Option<Data> {
|
||||
let pending = h.dom.images.pending.borrow();
|
||||
let slot = pending.iter().position(|p| p.uid == st.uid && p.reverts == st.reverts && p.bound == Some(id))?;
|
||||
Some(host_ref("PlacedItem", &[float(h.run), float(st.uid), 0.0, 0.0, float(st.reverts), float(slot as u64)]))
|
||||
}
|
||||
|
||||
/// The slot of a `PlacedItems.add()` result in this run, from its handle. A result whose document
|
||||
/// was closed or reverted since is stale.
|
||||
fn slot_of(h: &Host, run: f64, uid: f64, slot: f64) -> Result<usize, HostError> {
|
||||
let stale = || HostError::Error(STALE_ITEM.into());
|
||||
let doc = find_doc(h, run, uid).ok_or_else(stale)?;
|
||||
let reverts = h.session.borrow().documents().get(doc.index).map(|st| st.reverts);
|
||||
let k = whole(slot).and_then(|k| usize::try_from(k).ok()).ok_or_else(stale)?;
|
||||
match h.dom.images.pending.borrow().get(k) {
|
||||
Some(p) if p.uid == doc.uid && Some(p.reverts) == reverts => Ok(k),
|
||||
_ => Err(stale()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The id of the image a `PlacedItems.add()` result placed.
|
||||
pub(super) fn pending_id(h: &Host, run: f64, uid: f64, slot: f64) -> Result<NodeId, HostError> {
|
||||
let k = slot_of(h, run, uid, slot)?;
|
||||
match h.dom.images.pending.borrow().get(k).and_then(|p| p.bound) {
|
||||
Some(id) => Ok(id),
|
||||
None => Err(HostError::Error(FILE_REQUIRED.into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle's run, uid and slot when `d` is a `PlacedItems.add()` result. Its handle has six
|
||||
/// numbers, where a page item's has five.
|
||||
fn pending_handle(d: &Data) -> Option<[f64; 3]> {
|
||||
match host_ref_parts(d) {
|
||||
Some(("PlacedItem", handle)) => match handle.as_slice() {
|
||||
[run, uid, _, _, _, slot] => Some([*run, *uid, *slot]),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of a document's linked (`placed`) or embedded images, topmost first as [`page_items`]
|
||||
/// lists them.
|
||||
fn images(h: &Host, st: &DocState, placed: bool) -> Result<Rc<Vec<NodeId>>, HostError> {
|
||||
let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() };
|
||||
if let Some(l) = &*h.dom.images.lists.borrow()
|
||||
&& l.0 == st.uid
|
||||
&& Arc::ptr_eq(&l.1, &st.doc)
|
||||
{
|
||||
return Ok(pick(l));
|
||||
}
|
||||
let all = page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let (mut linked, mut embedded) = (Vec::new(), Vec::new());
|
||||
for id in all.iter() {
|
||||
if let Some(NodeKind::Image(im)) = st.doc.node(*id).map(|n| &n.kind) {
|
||||
if im.link.is_some() { linked.push(*id) } else { embedded.push(*id) }
|
||||
}
|
||||
}
|
||||
let l = (st.uid, st.doc.clone(), Rc::new(linked), Rc::new(embedded));
|
||||
let out = pick(&l);
|
||||
*h.dom.images.lists.borrow_mut() = Some(l);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> {
|
||||
match d {
|
||||
Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- PlacedItems and RasterItems ----
|
||||
|
||||
fn collection(placed: bool) -> &'static str {
|
||||
if placed { "PlacedItems" } else { "RasterItems" }
|
||||
}
|
||||
|
||||
fn list_doc(h: &Host, a: &[Data], placed: bool) -> Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), collection(placed))
|
||||
}
|
||||
|
||||
fn list_length(h: &Host, a: &[Data], placed: bool) -> Answer {
|
||||
let doc = list_doc(h, a, placed)?;
|
||||
let n = with_doc(h, doc, |_, st| images(h, st, placed).map(|l| l.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
fn list_at(h: &Host, a: &[Data], placed: bool) -> Answer {
|
||||
let doc = list_doc(h, a, placed)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(images(h, st, placed)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn list_by_name(h: &Host, a: &[Data], placed: bool) -> Answer {
|
||||
let doc = list_doc(h, a, placed)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = images(h, st, placed)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
})
|
||||
}
|
||||
|
||||
fn list_index(h: &Host, a: &[Data], placed: bool) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => list_by_name(h, a, placed),
|
||||
Data::Number(_) => match list_at(h, a, placed)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every image of the collection in one command. A hidden or locked one, or
|
||||
/// one in a hidden or locked layer or group, stops it before anything is deleted, and so does one on
|
||||
/// a locked artboard.
|
||||
fn list_remove_all(h: &Host, a: &[Data], placed: bool) -> Answer {
|
||||
let doc = list_doc(h, a, placed)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = images(h, st, placed)?;
|
||||
let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
|
||||
let locks = st.doc.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
Ok::<_, HostError>((ids, refused, on_locked))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}")));
|
||||
}
|
||||
if !on_locked.is_empty() {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `PlacedItems.add()`: a placed item with no file yet, which assigning `file` places.
|
||||
fn placed_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = list_doc(h, a, true)?;
|
||||
let reverts = h.session.borrow().documents().get(doc.index).map_or(0, |st| st.reverts);
|
||||
let mut pending = h.dom.images.pending.borrow_mut();
|
||||
if pending.len() >= MAX_PENDING {
|
||||
return Err(HostError::Range(format!("a run makes at most {MAX_PENDING} placed items with PlacedItems.add")));
|
||||
}
|
||||
pending.push(Pending { uid: doc.uid, reverts, bound: None });
|
||||
Ok(host_ref("PlacedItem", &[float(h.run), float(doc.uid), 0.0, 0.0, float(reverts), float(pending.len() as u64 - 1)]))
|
||||
}
|
||||
|
||||
macro_rules! both {
|
||||
($($placed:ident, $raster:ident => $f:ident;)*) => {
|
||||
$(
|
||||
fn $placed(h: &Host, a: &[Data]) -> Answer {
|
||||
$f(h, a, true)
|
||||
}
|
||||
fn $raster(h: &Host, a: &[Data]) -> Answer {
|
||||
$f(h, a, false)
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
both! {
|
||||
placed_length, raster_length => list_length;
|
||||
placed_at, raster_at => list_at;
|
||||
placed_by_name, raster_by_name => list_by_name;
|
||||
placed_index, raster_index => list_index;
|
||||
placed_remove_all, raster_remove_all => list_remove_all;
|
||||
}
|
||||
|
||||
fn placed_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(doc_ref(h, list_doc(h, a, true)?.uid))
|
||||
}
|
||||
|
||||
fn raster_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(doc_ref(h, list_doc(h, a, false)?.uid))
|
||||
}
|
||||
|
||||
fn doc_placed(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("PlacedItems", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_raster(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("RasterItems", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
// ---- files ----
|
||||
|
||||
/// Whether the script may read `path` now by its own read scope and the read roots
|
||||
/// ([`crate::file_access::ScriptGate`]), without the open documents' files a command may also read.
|
||||
fn may_read(h: &Host, path: &str) -> bool {
|
||||
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
|
||||
crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok()
|
||||
}
|
||||
|
||||
/// The real path of the `File` `d` gives as an image to place or relink: one the script may read
|
||||
/// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of
|
||||
/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no
|
||||
/// error names the path.
|
||||
fn image_path(h: &Host, d: &Data, what: &str) -> Result<String, HostError> {
|
||||
let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?;
|
||||
if path.len() > super::super::files::MAX_PATH_CHARS {
|
||||
return Err(HostError::Range(super::super::files::PATH_TOO_LONG.into()));
|
||||
}
|
||||
let unc = path.starts_with("\\\\") || path.starts_with("//");
|
||||
if path.is_empty() || path.contains('\0') || unc || path.split(['/', '\\']).any(|c| c == "..") {
|
||||
return Err(HostError::Error(super::super::files::ACCESS_DENIED.into()));
|
||||
}
|
||||
let real = h.disk.borrow().open_target(path).map_err(|m| HostError::Error(m.into()))?;
|
||||
let meta = std::fs::metadata(&real).map_err(|_| HostError::Error(super::super::files::NOT_FOUND.into()))?;
|
||||
if !meta.is_file() {
|
||||
return Err(HostError::Error(super::super::files::NOT_REGULAR.into()));
|
||||
}
|
||||
if meta.len() > MAX_PLACED_BYTES {
|
||||
return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20)));
|
||||
}
|
||||
let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned();
|
||||
// What the file holds, read the way `file.place` reads it, before the document changes.
|
||||
let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?;
|
||||
if field(&info, "pixelWidth").is_none() {
|
||||
return Err(HostError::Error(NOT_AN_IMAGE.into()));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
// ---- PlacedItem ----
|
||||
|
||||
/// The item `this` names when it is a `cls` (`PlacedItem` or `RasterItem`).
|
||||
fn this_of(h: &Host, a: &[Data], cls: &str) -> Result<Item, HostError> {
|
||||
match host_ref_parts(arg(a, 0)) {
|
||||
Some((c, _)) if c == cls => item_of(h, arg(a, 0)),
|
||||
_ => Err(HostError::Type(format!("this is not a {cls}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the image of the `cls` `this` names with `f`.
|
||||
fn read_image(h: &Host, a: &[Data], cls: &str, f: impl FnOnce(&DocState, &crate::doc::Node, &crate::doc::ImageObject) -> Answer) -> Answer {
|
||||
let item = this_of(h, a, cls)?;
|
||||
with_doc(h, item.doc, |_, st| match st.doc.node(item.id) {
|
||||
Some(n) => match &n.kind {
|
||||
NodeKind::Image(im) => f(st, n, im),
|
||||
_ => Err(HostError::Error(STALE_ITEM.into())),
|
||||
},
|
||||
None => Err(HostError::Error(STALE_ITEM.into())),
|
||||
})
|
||||
}
|
||||
|
||||
fn placed_file(h: &Host, a: &[Data]) -> Answer {
|
||||
if let Some([run, uid, slot]) = pending_handle(arg(a, 0)) {
|
||||
let k = slot_of(h, run, uid, slot)?;
|
||||
if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_none()) {
|
||||
// Null while its document is open; stale once that document is closed.
|
||||
find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
return Ok(Data::Null);
|
||||
}
|
||||
}
|
||||
let path = read_image(h, a, "PlacedItem", |st, _, im| {
|
||||
let path = im.link.as_ref().and_then(|link| {
|
||||
let base = crate::cmd::links::LinkBase::of(st);
|
||||
crate::cmd::links::located_path(link, base).or_else(|| crate::cmd::fileio::document_path(&link.path, base.doc).ok())
|
||||
});
|
||||
let path = path.ok_or_else(|| HostError::Error(super::super::files::ACCESS_DENIED.into()))?;
|
||||
Ok(text(path))
|
||||
})?;
|
||||
let Data::String(path) = path else { return Ok(Data::Null) };
|
||||
if !may_read(h, &path) {
|
||||
return Err(HostError::Error(super::super::files::ACCESS_DENIED.into()));
|
||||
}
|
||||
Ok(file_ref(&path))
|
||||
}
|
||||
|
||||
/// `file = File`: places the file, linked, for a `PlacedItems.add()` result that has none.
|
||||
fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some([run, uid, slot]) = pending_handle(arg(a, 0)) else {
|
||||
if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PlacedItem") {
|
||||
this_of(h, a, "PlacedItem")?;
|
||||
return Err(HostError::Error(FILE_READ_ONLY.into()));
|
||||
}
|
||||
return Err(HostError::Type("this is not a PlacedItem".into()));
|
||||
};
|
||||
let k = slot_of(h, run, uid, slot)?;
|
||||
if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_some()) {
|
||||
this_of(h, a, "PlacedItem")?;
|
||||
return Err(HostError::Error(FILE_READ_ONLY.into()));
|
||||
}
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let path = image_path(h, arg(a, 1), "PlacedItem.file")?;
|
||||
// The ids are read from the command's own result, where every id is exact (a script number
|
||||
// holds integers exactly only up to 2^53).
|
||||
// The placement and its check run under one savepoint, so an error after the place leaves
|
||||
// no linked image behind.
|
||||
let id = super::atomically(h, |h| {
|
||||
let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?;
|
||||
let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64));
|
||||
let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId);
|
||||
let linked =
|
||||
|id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some()));
|
||||
id.filter(|id| linked(*id)).ok_or_else(|| HostError::Error(NOT_AN_IMAGE.into()))
|
||||
})?;
|
||||
if let Some(p) = h.dom.images.pending.borrow_mut().get_mut(k) {
|
||||
p.bound = Some(id);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `relink(file)`: `links.relink` of the item to the image in `file`.
|
||||
fn placed_relink(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_of(h, a, "PlacedItem")?;
|
||||
let path = image_path(h, arg(a, 1), "relink's file")?;
|
||||
edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `embed()`: `links.embed` of the item, which becomes a raster item.
|
||||
fn placed_embed(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_of(h, a, "PlacedItem")?;
|
||||
let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?;
|
||||
if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") {
|
||||
return Err(HostError::Error(MISSING_LINK.into()));
|
||||
}
|
||||
edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?;
|
||||
let embedded = with_doc(h, item.doc, |_, st| matches!(st.doc.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()));
|
||||
if !embedded {
|
||||
return Err(HostError::Error(MISSING_LINK.into()));
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- both ----
|
||||
|
||||
/// `matrix`: the image's pixels to script coordinates.
|
||||
fn matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
|
||||
read_image(h, a, cls, |st, n, im| {
|
||||
if n.is_distorted_image() {
|
||||
return Err(HostError::Error(DISTORTED.into()));
|
||||
}
|
||||
let f = frame(st)?;
|
||||
let [a0, b0, c0, d0, e0, f0] = im.xf.as_coeffs();
|
||||
let m = match h.dom.coords.get() {
|
||||
Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0],
|
||||
Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top],
|
||||
};
|
||||
let mut items = vec![("typename".to_string(), text("Matrix"))];
|
||||
items.extend(MATRIX_KEYS.iter().zip(m).map(|(k, v)| (k.to_string(), num(v))));
|
||||
Ok(Data::Object(items))
|
||||
})
|
||||
}
|
||||
|
||||
/// The six numbers of the `Matrix` record `d`, `mValueA` to `mValueTY`, each finite.
|
||||
fn matrix_value(d: &Data) -> Result<[f64; 6], HostError> {
|
||||
let mut m = [0.0; 6];
|
||||
for (k, out) in MATRIX_KEYS.iter().zip(m.iter_mut()) {
|
||||
*out = match field(d, k) {
|
||||
Some(Data::Number(n)) if n.is_finite() => *n,
|
||||
_ => return Err(HostError::Type(format!("matrix must be a Matrix with a finite {k}"))),
|
||||
};
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// Whether `m` gives a pixel an area of at least [`MIN_DETERMINANT`].
|
||||
fn area_of(m: Affine) -> bool {
|
||||
let det = m.determinant();
|
||||
!det.is_nan() && det.abs() >= MIN_DETERMINANT
|
||||
}
|
||||
|
||||
/// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix.
|
||||
/// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted
|
||||
/// image is refused before anything changes; the matrix the image has already changes nothing.
|
||||
fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
|
||||
let item = this_of(h, a, cls)?;
|
||||
let m = matrix_value(arg(a, 1))?;
|
||||
let delta = with_doc(h, item.doc, |_, st| {
|
||||
let Some((n, im)) = st.doc.node(item.id).and_then(|n| if let NodeKind::Image(im) = &n.kind { Some((n, im)) } else { None }) else {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
};
|
||||
if n.is_distorted_image() {
|
||||
return Err(HostError::Error(DISTORTED.into()));
|
||||
}
|
||||
let f = frame(st)?;
|
||||
let target = Affine::new(match h.dom.coords.get() {
|
||||
Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]],
|
||||
Coords::Artboard => [m[0], m[1], m[2], m[3], m[4] + f.left, m[5] + f.top],
|
||||
});
|
||||
if !area_of(target) {
|
||||
return Err(HostError::Range("the matrix gives the image no area".into()));
|
||||
}
|
||||
let (w, ht) = (f64::from(im.width), f64::from(im.height));
|
||||
let limit = crate::MAX_COORD * 2.0;
|
||||
let corners = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].map(|(x, y)| target * Point::new(x, y));
|
||||
if corners.iter().any(|p| !(p.x.abs() <= limit && p.y.abs() <= limit)) {
|
||||
return Err(HostError::Range("the matrix puts the image outside the canvas".into()));
|
||||
}
|
||||
let old = im.xf;
|
||||
// The coordinate frame only changes the signs of the linear part, so any change to it
|
||||
// counts; the offsets compare in points, which absorbs the rounding of the frame.
|
||||
let same = old.as_coeffs().iter().zip(target.as_coeffs()).enumerate().all(|(k, (o, t))| if k < 4 { *o == t } else { (o - t).abs() <= 1e-9 });
|
||||
if same {
|
||||
return Ok(None);
|
||||
}
|
||||
if !area_of(old) {
|
||||
return Err(HostError::Error("the image has no area to transform".into()));
|
||||
}
|
||||
Ok(Some((target * old.inverse()).as_coeffs()))
|
||||
})?;
|
||||
if let Some(d) = delta {
|
||||
edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `boundingBox`: the pixel rectangle at one point a pixel, `[left, top, right, bottom]`.
|
||||
fn bounding_box(h: &Host, a: &[Data], cls: &str) -> Answer {
|
||||
read_image(h, a, cls, |_, _, im| {
|
||||
let (w, ht) = (f64::from(im.width), f64::from(im.height));
|
||||
Ok(Data::Array(match h.dom.coords.get() {
|
||||
Coords::Document => vec![num(0.0), num(ht), num(w), num(0.0)],
|
||||
Coords::Artboard => vec![num(0.0), num(0.0), num(w), num(ht)],
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fn placed_matrix(h: &Host, a: &[Data]) -> Answer {
|
||||
matrix(h, a, "PlacedItem")
|
||||
}
|
||||
|
||||
fn raster_matrix(h: &Host, a: &[Data]) -> Answer {
|
||||
matrix(h, a, "RasterItem")
|
||||
}
|
||||
|
||||
fn placed_set_matrix(h: &Host, a: &[Data]) -> Answer {
|
||||
set_matrix(h, a, "PlacedItem")
|
||||
}
|
||||
|
||||
fn raster_set_matrix(h: &Host, a: &[Data]) -> Answer {
|
||||
set_matrix(h, a, "RasterItem")
|
||||
}
|
||||
|
||||
fn placed_box(h: &Host, a: &[Data]) -> Answer {
|
||||
bounding_box(h, a, "PlacedItem")
|
||||
}
|
||||
|
||||
fn raster_box(h: &Host, a: &[Data]) -> Answer {
|
||||
bounding_box(h, a, "RasterItem")
|
||||
}
|
||||
|
||||
// ---- RasterItem ----
|
||||
|
||||
/// The header of the raster item's encoded pixels.
|
||||
fn header(h: &Host, a: &[Data], f: impl FnOnce(&craft_image_codecs::RasterInspection) -> Data) -> Answer {
|
||||
read_image(h, a, "RasterItem", |st, _, im| {
|
||||
let blob = st.doc.images.get(&im.key).ok_or_else(|| HostError::Error("the image's pixels are not in the document".into()))?;
|
||||
match craft_image_codecs::inspect_raster(&blob.bytes) {
|
||||
Ok(Some(i)) => Ok(f(&i)),
|
||||
_ => Err(HostError::Error("the image's header does not describe its pixels".into())),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn raster_bits(h: &Host, a: &[Data]) -> Answer {
|
||||
header(h, a, |i| num(f64::from(i.bits_per_sample)))
|
||||
}
|
||||
|
||||
fn raster_channels(h: &Host, a: &[Data]) -> Answer {
|
||||
header(h, a, |i| num(f64::from(i.channels)))
|
||||
}
|
||||
|
||||
fn raster_transparent(h: &Host, a: &[Data]) -> Answer {
|
||||
use craft_image_codecs::RasterColorType as T;
|
||||
header(h, a, |i| Data::Bool(matches!(i.color_type, T::GrayAlpha | T::Rgba | T::CmykAlpha) || i.transparent_index.is_some()))
|
||||
}
|
||||
|
||||
fn raster_color_space(h: &Host, a: &[Data]) -> Answer {
|
||||
use craft_image_codecs::RasterColorType as T;
|
||||
let space = header(h, a, |i| {
|
||||
text(match i.color_type {
|
||||
T::Bitmap | T::Gray | T::GrayAlpha => "ImageColorSpace.Grayscale",
|
||||
T::Rgb | T::Rgba => "ImageColorSpace.RGB",
|
||||
T::Cmyk | T::CmykAlpha => "ImageColorSpace.CMYK",
|
||||
T::Indexed => "ImageColorSpace.Indexed",
|
||||
T::Lab => "ImageColorSpace.LAB",
|
||||
T::Other => "",
|
||||
})
|
||||
})?;
|
||||
match space {
|
||||
Data::String(s) if s.is_empty() => Err(HostError::Error("the image's header does not describe its color space".into())),
|
||||
d => Ok(d),
|
||||
}
|
||||
}
|
||||
|
||||
fn raster_colorized(h: &Host, a: &[Data]) -> Answer {
|
||||
read_image(h, a, "RasterItem", |st, n, im| {
|
||||
let gray = st.doc.images.get(&im.key).is_some_and(|b| b.gray_source().is_some());
|
||||
Ok(Data::Bool(gray && n.extras().colorize.is_some()))
|
||||
})
|
||||
}
|
||||
|
||||
fn raster_embedded(h: &Host, a: &[Data]) -> Answer {
|
||||
this_of(h, a, "RasterItem")?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `embedded = true` changes nothing; a raster item cannot be linked by assigning `false`.
|
||||
fn raster_set_embedded(h: &Host, a: &[Data]) -> Answer {
|
||||
this_of(h, a, "RasterItem")?;
|
||||
match arg(a, 1) {
|
||||
Data::Bool(true) => Ok(Data::Undefined),
|
||||
Data::Bool(false) => Err(HostError::Error("a raster item cannot be linked by setting embedded to false".into())),
|
||||
_ => Err(HostError::Type("embedded must be true or false".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn raster_file(h: &Host, a: &[Data]) -> Answer {
|
||||
this_of(h, a, "RasterItem")?;
|
||||
Ok(Data::Null)
|
||||
}
|
||||
|
||||
fn raster_status(h: &Host, a: &[Data]) -> Answer {
|
||||
this_of(h, a, "RasterItem")?;
|
||||
Ok(text("RasterLinkState.NODATA"))
|
||||
}
|
||||
|
||||
/// `Document.placedItems` and `Document.rasterItems`.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("placedItems", get(l, doc_placed), MemberInfo { collection: true, ..typed("PlacedItems") }),
|
||||
("rasterItems", get(l, doc_raster), MemberInfo { collection: true, ..typed("RasterItems") }),
|
||||
])
|
||||
}
|
||||
|
||||
/// The collections, `PlacedItem` and `RasterItem`, after `PageItem`.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let placed_list = named(vec![
|
||||
("typename", typename_of("PlacedItems"), typed("string")),
|
||||
("length", get(l, placed_length), typed("number")),
|
||||
("parent", get(l, placed_parent), typed("Document")),
|
||||
("index", method(l, placed_index), returns("PlacedItem", &[("itemKey", "*")])),
|
||||
("getByName", method(l, placed_by_name), returns("PlacedItem", &[("name", "string")])),
|
||||
("removeAll", method(l, placed_remove_all), returns("undefined", &[])),
|
||||
("add", method(l, placed_add), returns("PlacedItem", &[])),
|
||||
]);
|
||||
let raster_list = named(vec![
|
||||
("typename", typename_of("RasterItems"), typed("string")),
|
||||
("length", get(l, raster_length), typed("number")),
|
||||
("parent", get(l, raster_parent), typed("Document")),
|
||||
("index", method(l, raster_index), returns("RasterItem", &[("itemKey", "*")])),
|
||||
("getByName", method(l, raster_by_name), returns("RasterItem", &[("name", "string")])),
|
||||
("removeAll", method(l, raster_remove_all), returns("undefined", &[])),
|
||||
]);
|
||||
let mut placed = named(vec![
|
||||
("file", property(l, placed_file, placed_set_file), typed("File")),
|
||||
("relink", method(l, placed_relink), returns("undefined", &[("relinkFile", "File")])),
|
||||
("embed", method(l, placed_embed), returns("undefined", &[])),
|
||||
("matrix", property(l, placed_matrix, placed_set_matrix), typed("Matrix")),
|
||||
("boundingBox", get(l, placed_box), typed("Array")),
|
||||
]);
|
||||
placed.extend(variables::item_members(l, "PlacedItem"));
|
||||
let mut raster = named(vec![
|
||||
("bitsPerChannel", get(l, raster_bits), typed("number")),
|
||||
("channels", get(l, raster_channels), typed("number")),
|
||||
("colorizedGrayscale", get(l, raster_colorized), typed("boolean")),
|
||||
("embedded", property(l, raster_embedded, raster_set_embedded), typed("boolean")),
|
||||
("file", get(l, raster_file), typed("File")),
|
||||
("imageColorSpace", get(l, raster_color_space), typed("ImageColorSpace")),
|
||||
("matrix", property(l, raster_matrix, raster_set_matrix), typed("Matrix")),
|
||||
("status", get(l, raster_status), typed("RasterLinkState")),
|
||||
("transparent", get(l, raster_transparent), typed("boolean")),
|
||||
("boundingBox", get(l, raster_box), typed("Array")),
|
||||
]);
|
||||
raster.extend(variables::item_members(l, "RasterItem"));
|
||||
raster.extend(["colorants", "colorize", "overprint"].into_iter().map(|m| later(l, "RasterItem", m)));
|
||||
vec![
|
||||
class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))),
|
||||
class("RasterItems", None, raster_list, Some(super::function(l, raster_at))),
|
||||
class("PlacedItem", Some("PageItem"), placed, None),
|
||||
class("RasterItem", Some("PageItem"), raster, None),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
//! The matrix functions of `app`, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> describe them. A matrix is a plain
|
||||
//! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the
|
||||
//! `typename` `"Matrix"`; each function other than `isEqualMatrix` and `isSingularMatrix` gives a
|
||||
//! new record, those two give a boolean, and none changes the records passed to it.
|
||||
//!
|
||||
//! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix
|
||||
//! does (ISO 32000-1, 8.3.4), in script coordinates with Y up.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `concatenateMatrix(m, n)` gives the matrix that applies `m` and then `n`; the other
|
||||
//! `concatenate…` functions apply `m` and then the rotation, scale or translation they make.
|
||||
//! - Left-out arguments are 0 for a translation and an angle, and 100 for a horizontal scale; a
|
||||
//! left-out vertical scale is the horizontal one.
|
||||
//! - Angles are degrees, positive counterclockwise, and quarter turns are exact.
|
||||
//! - A matrix whose determinant is 0 is singular, and `invertMatrix` of one throws.
|
||||
//! - `isEqualMatrix` compares the six values exactly.
|
||||
//! - An argument that is not a finite number, or a matrix with a value that is not one, throws a
|
||||
//! `TypeError`; a result with a value too large for a number throws a `RangeError`.
|
||||
|
||||
use vectorcraft_js::{Data, HostError};
|
||||
|
||||
use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text};
|
||||
|
||||
/// A matrix's six values: `[a, b, c, d, tx, ty]`.
|
||||
pub(super) type Matrix = [f64; 6];
|
||||
|
||||
const KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"];
|
||||
|
||||
const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
|
||||
/// The matrix functions of `Application`.
|
||||
pub(super) fn app_members(link: &Link) -> Vec<Described> {
|
||||
let l = link;
|
||||
named(vec![
|
||||
("getIdentityMatrix", method(l, identity), returns("Matrix", &[])),
|
||||
("getTranslationMatrix", method(l, translation), returns("Matrix", &[("deltaX", "number"), ("deltaY", "number")])),
|
||||
("getScaleMatrix", method(l, scale), returns("Matrix", &[("scaleX", "number"), ("scaleY", "number")])),
|
||||
("getRotationMatrix", method(l, rotation), returns("Matrix", &[("angle", "number")])),
|
||||
("concatenateMatrix", method(l, concatenate), returns("Matrix", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])),
|
||||
(
|
||||
"concatenateTranslationMatrix",
|
||||
method(l, concatenate_translation),
|
||||
returns("Matrix", &[("matrix", "Matrix"), ("deltaX", "number"), ("deltaY", "number")]),
|
||||
),
|
||||
(
|
||||
"concatenateScaleMatrix",
|
||||
method(l, concatenate_scale),
|
||||
returns("Matrix", &[("matrix", "Matrix"), ("scaleX", "number"), ("scaleY", "number")]),
|
||||
),
|
||||
("concatenateRotationMatrix", method(l, concatenate_rotation), returns("Matrix", &[("matrix", "Matrix"), ("angle", "number")])),
|
||||
("invertMatrix", method(l, invert), returns("Matrix", &[("matrix", "Matrix")])),
|
||||
("isEqualMatrix", method(l, is_equal), returns("boolean", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])),
|
||||
("isSingularMatrix", method(l, is_singular), returns("boolean", &[("matrix", "Matrix")])),
|
||||
])
|
||||
}
|
||||
|
||||
/// The record for `m`, or a `RangeError` when a value is not finite.
|
||||
fn record(m: Matrix) -> Answer {
|
||||
if m.iter().any(|v| !v.is_finite()) {
|
||||
return Err(HostError::Range("the matrix has a value too large for a number".into()));
|
||||
}
|
||||
let mut items: Vec<(String, Data)> = KEYS.iter().zip(m).map(|(k, v)| ((*k).to_string(), num(v))).collect();
|
||||
items.push(("typename".into(), text("Matrix")));
|
||||
Ok(Data::Object(items))
|
||||
}
|
||||
|
||||
/// The matrix argument `d`.
|
||||
pub(super) fn matrix(d: &Data, what: &str) -> std::result::Result<Matrix, HostError> {
|
||||
let bad = || HostError::Type(format!("{what} must be a Matrix"));
|
||||
let Data::Object(items) = d else { return Err(bad()) };
|
||||
let mut m = [0.0; 6];
|
||||
for (slot, k) in m.iter_mut().zip(KEYS) {
|
||||
match items.iter().find(|(n, _)| n == k) {
|
||||
Some((_, Data::Number(v))) if v.is_finite() => *slot = *v,
|
||||
_ => return Err(bad()),
|
||||
}
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// A number argument, `default` when it is left out.
|
||||
fn number(d: &Data, what: &str, default: f64) -> std::result::Result<f64, HostError> {
|
||||
match d {
|
||||
Data::Undefined => Ok(default),
|
||||
Data::Number(n) if n.is_finite() => Ok(*n),
|
||||
_ => Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The matrix that applies `m` and then `n`. Adding 0 turns -0 into 0.
|
||||
fn then(m: Matrix, n: Matrix) -> Matrix {
|
||||
let [a, b, c, d, e, f] = m;
|
||||
let [a2, b2, c2, d2, e2, f2] = n;
|
||||
[
|
||||
products_sum(a, a2, b, c2, 0.0) + 0.0,
|
||||
products_sum(a, b2, b, d2, 0.0) + 0.0,
|
||||
products_sum(c, a2, d, c2, 0.0) + 0.0,
|
||||
products_sum(c, b2, d, d2, 0.0) + 0.0,
|
||||
products_sum(e, a2, f, c2, e2) + 0.0,
|
||||
products_sum(e, b2, f, d2, f2) + 0.0,
|
||||
]
|
||||
}
|
||||
|
||||
/// `x·y + z·w + t`. When at most one of the three terms is not 0 and it is finite, that term is the
|
||||
/// sum, rounded once. When both products and their sum are exact numbers, adding `t` rounds once.
|
||||
/// Otherwise the products are summed past the range of a number and rounded at
|
||||
/// the end, so a finite value is not lost to a product too large or too small for a number, to a
|
||||
/// sum that rounds twice, or to a rounding error that a later term cancels down to.
|
||||
fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 {
|
||||
let (p, q) = (x * y, z * w);
|
||||
let terms = [x != 0.0 && y != 0.0, z != 0.0 && w != 0.0, t != 0.0];
|
||||
let total = p + q + t;
|
||||
if terms.iter().filter(|&&on| on).count() <= 1 && total.is_finite() {
|
||||
return total;
|
||||
}
|
||||
// A product at or above 2^-969 that rounds drops a part a number can hold, so a zero
|
||||
// remainder shows the product is exact.
|
||||
let exact = |v: f64, a: f64, b: f64| a == 0.0 || b == 0.0 || (v.abs() >= f64::MIN_POSITIVE * 2f64.powi(53) && a.mul_add(b, -v) == 0.0);
|
||||
let plain = p + q;
|
||||
if total.is_finite() && exact(p, x, y) && exact(q, z, w) && plain - p == q && plain - q == p {
|
||||
return total;
|
||||
}
|
||||
// Each product is split into its rounded value and the part that rounding drops, both exact.
|
||||
// The five parts are added one at a time into a list of values that do not overlap, smallest
|
||||
// first, whose sum is exact (Shewchuk's expansion).
|
||||
let product = |a: f64, b: f64| {
|
||||
let (a, b) = (Wide::of(a), Wide::of(b));
|
||||
let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e));
|
||||
[Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)]
|
||||
};
|
||||
let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w));
|
||||
let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow);
|
||||
nearest(exact)
|
||||
}
|
||||
|
||||
/// Values that do not overlap, smallest first, held without allocating. Each value added keeps at
|
||||
/// most one more, so the five parts of a sum and the two of a comparison fit.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Parts {
|
||||
v: [Wide; 8],
|
||||
n: usize,
|
||||
}
|
||||
|
||||
impl Parts {
|
||||
const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 8], n: 0 };
|
||||
|
||||
fn as_slice(&self) -> &[Wide] {
|
||||
&self.v[..self.n]
|
||||
}
|
||||
}
|
||||
|
||||
/// `sums` with `part` added: values that do not overlap, smallest first, whose sum is exactly the
|
||||
/// sum of `sums` and `part`. The last value is the largest and has the sign of the sum.
|
||||
fn grow(sums: Parts, part: Wide) -> Parts {
|
||||
let mut carry = part;
|
||||
let mut kept = Parts::EMPTY;
|
||||
let mut keep = |w: Wide| {
|
||||
if w.m != 0.0 && kept.n < kept.v.len() {
|
||||
kept.v[kept.n] = w;
|
||||
kept.n += 1;
|
||||
}
|
||||
};
|
||||
for &h in sums.as_slice() {
|
||||
let (sum, rest) = carry.two_sum(h);
|
||||
keep(rest);
|
||||
carry = sum;
|
||||
}
|
||||
keep(carry);
|
||||
kept
|
||||
}
|
||||
|
||||
/// The sign of the exact sum of `sums`, `0.0 - v` and `offset`: 1, -1 or 0.
|
||||
fn sign_past(sums: Parts, v: f64, offset: Wide) -> i32 {
|
||||
let rest = [Wide::of(0.0 - v), offset].into_iter().fold(sums, grow);
|
||||
match rest.as_slice().last() {
|
||||
Some(w) if w.m > 0.0 => 1,
|
||||
Some(w) if w.m < 0.0 => -1,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The number nearest the exact sum of `sums`, ties to the even one, and infinite when the sum
|
||||
/// rounds to 2^1024 or past it. The sum of the values from the smallest up comes within a step of
|
||||
/// it; the halfway points to the neighbors of that number are then compared with the exact sum, so
|
||||
/// the result is rounded once.
|
||||
fn nearest(sums: Parts) -> f64 {
|
||||
let even = |v: f64| v.to_bits() & 1 == 0;
|
||||
let mut v = sums.as_slice().iter().fold(Wide::of(0.0), |total, &h| total.two_sum(h).0).value().clamp(f64::MIN, f64::MAX);
|
||||
for _ in 0..4 {
|
||||
// Half the step to the next number up, and to the next number down. Past the largest
|
||||
// number the step is to 2^1024, which is 2^971 away.
|
||||
let up = if v == f64::MAX { f64::INFINITY } else { v.next_up() };
|
||||
let down = if v == f64::MIN { f64::NEG_INFINITY } else { v.next_down() };
|
||||
let half_up = if up.is_finite() { Wide::new(up - v, -1) } else { Wide::new(1.0, 970) };
|
||||
let half_down = if down.is_finite() { Wide::new(v - down, -1) } else { Wide::new(1.0, 970) };
|
||||
match sign_past(sums, v, Wide { m: 0.0 - half_up.m, e: half_up.e }) {
|
||||
1 => {
|
||||
v = up;
|
||||
if !v.is_finite() {
|
||||
return v;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
0 => return if even(v) { v } else { up },
|
||||
_ => {}
|
||||
}
|
||||
match sign_past(sums, v, half_down) {
|
||||
-1 => {
|
||||
v = down;
|
||||
if !v.is_finite() {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
0 => return if even(v) { v } else { down },
|
||||
_ => return v,
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub(super) fn translate(dx: f64, dy: f64) -> Matrix {
|
||||
[1.0, 0.0, 0.0, 1.0, dx, dy]
|
||||
}
|
||||
|
||||
/// A scale by `sx` and `sy` percent.
|
||||
pub(super) fn scaled(sx: f64, sy: f64) -> Matrix {
|
||||
[sx / 100.0, 0.0, 0.0, sy / 100.0, 0.0, 0.0]
|
||||
}
|
||||
|
||||
/// A turn of `degrees` counterclockwise, exact at quarter turns. The remainder keeps the sign of
|
||||
/// `degrees` and is exact, so an angle next to a quarter turn is not rounded onto it.
|
||||
pub(super) fn rotate(degrees: f64) -> Matrix {
|
||||
let turn = degrees % 360.0;
|
||||
let (sin, cos) = match turn {
|
||||
0.0 => (0.0, 1.0),
|
||||
90.0 | -270.0 => (1.0, 0.0),
|
||||
180.0 | -180.0 => (0.0, -1.0),
|
||||
270.0 | -90.0 => (-1.0, 0.0),
|
||||
_ => turn.to_radians().sin_cos(),
|
||||
};
|
||||
// `0.0 - sin` rather than `-sin`, so a turn of 0 gives 0 and not -0.
|
||||
[cos, sin, 0.0 - sin, cos, 0.0, 0.0]
|
||||
}
|
||||
|
||||
fn translation_of(a: &[Data], at: usize) -> std::result::Result<Matrix, HostError> {
|
||||
Ok(translate(number(arg(a, at), "deltaX", 0.0)?, number(arg(a, at + 1), "deltaY", 0.0)?))
|
||||
}
|
||||
|
||||
fn scale_of(a: &[Data], at: usize) -> std::result::Result<Matrix, HostError> {
|
||||
let sx = number(arg(a, at), "scaleX", 100.0)?;
|
||||
Ok(scaled(sx, number(arg(a, at + 1), "scaleY", sx)?))
|
||||
}
|
||||
|
||||
fn rotation_of(a: &[Data], at: usize) -> std::result::Result<Matrix, HostError> {
|
||||
Ok(rotate(number(arg(a, at), "angle", 0.0)?))
|
||||
}
|
||||
|
||||
fn identity(_: &Host, _: &[Data]) -> Answer {
|
||||
record(IDENTITY)
|
||||
}
|
||||
|
||||
fn translation(_: &Host, a: &[Data]) -> Answer {
|
||||
record(translation_of(a, 1)?)
|
||||
}
|
||||
|
||||
fn scale(_: &Host, a: &[Data]) -> Answer {
|
||||
record(scale_of(a, 1)?)
|
||||
}
|
||||
|
||||
fn rotation(_: &Host, a: &[Data]) -> Answer {
|
||||
record(rotation_of(a, 1)?)
|
||||
}
|
||||
|
||||
fn concatenate(_: &Host, a: &[Data]) -> Answer {
|
||||
record(then(matrix(arg(a, 1), "matrix")?, matrix(arg(a, 2), "secondMatrix")?))
|
||||
}
|
||||
|
||||
fn concatenate_translation(_: &Host, a: &[Data]) -> Answer {
|
||||
record(then(matrix(arg(a, 1), "matrix")?, translation_of(a, 2)?))
|
||||
}
|
||||
|
||||
fn concatenate_scale(_: &Host, a: &[Data]) -> Answer {
|
||||
record(then(matrix(arg(a, 1), "matrix")?, scale_of(a, 2)?))
|
||||
}
|
||||
|
||||
fn concatenate_rotation(_: &Host, a: &[Data]) -> Answer {
|
||||
record(then(matrix(arg(a, 1), "matrix")?, rotation_of(a, 2)?))
|
||||
}
|
||||
|
||||
/// A number as `m · 2^e` with `m` 0 or in `[0.5, 1)`, so products and quotients of such numbers
|
||||
/// keep their value however far they go past the range of an `f64`.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Wide {
|
||||
m: f64,
|
||||
e: i32,
|
||||
}
|
||||
|
||||
/// `2^e`, for `e` from -1022 to 1023.
|
||||
fn pow2(e: i32) -> f64 {
|
||||
f64::from_bits(u64::from((e + 1023).clamp(1, 2046).unsigned_abs()) << 52)
|
||||
}
|
||||
|
||||
impl Wide {
|
||||
/// `x`, a finite number.
|
||||
fn of(x: f64) -> Self {
|
||||
if x == 0.0 {
|
||||
return Self { m: 0.0, e: 0 };
|
||||
}
|
||||
if x.abs() < f64::MIN_POSITIVE {
|
||||
let w = Self::of(x * pow2(54));
|
||||
return Self { m: w.m, e: w.e - 54 };
|
||||
}
|
||||
let bits = x.to_bits();
|
||||
let e = i32::try_from((bits >> 52) & 0x7ff).unwrap_or(0) - 1022;
|
||||
Self { m: f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), e }
|
||||
}
|
||||
|
||||
/// `m · 2^e`, with `m` any finite number.
|
||||
fn new(m: f64, e: i32) -> Self {
|
||||
let w = Self::of(m);
|
||||
Self { m: w.m, e: w.e.saturating_add(e) }
|
||||
}
|
||||
|
||||
fn div(self, o: Self) -> Self {
|
||||
Self::new(self.m / o.m, self.e.saturating_sub(o.e))
|
||||
}
|
||||
|
||||
/// The sum and the part of it that rounding drops, so that `self + o` is exactly their sum. A
|
||||
/// number more than 2^110 times smaller than the other is returned whole as the dropped part.
|
||||
fn two_sum(self, o: Self) -> (Self, Self) {
|
||||
let (big, small) = if self.m == 0.0 || (o.m != 0.0 && o.e > self.e) { (o, self) } else { (self, o) };
|
||||
let gap = small.e.saturating_sub(big.e);
|
||||
if small.m == 0.0 || gap < -110 {
|
||||
return (big, small);
|
||||
}
|
||||
// Knuth's two-sum: `small` scaled to `big`'s power of 2 is exact, and so is the error.
|
||||
let s = small.m * pow2(gap);
|
||||
let sum = big.m + s;
|
||||
let back = sum - big.m;
|
||||
let rest = (big.m - (sum - back)) + (s - back);
|
||||
(Self::new(sum, big.e), Self::new(rest, big.e))
|
||||
}
|
||||
|
||||
/// The nearest `f64`: infinite past its range, and 0 or a subnormal number below it.
|
||||
fn value(self) -> f64 {
|
||||
let (mut m, mut e) = (self.m, self.e);
|
||||
while e > 1000 && m.is_finite() {
|
||||
m *= pow2(1000);
|
||||
e -= 1000;
|
||||
}
|
||||
while e < -1000 && m != 0.0 {
|
||||
m *= pow2(-1000);
|
||||
e += 1000;
|
||||
}
|
||||
m * pow2(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// `a·d − b·c` with no product passing the range of a number; its `m` is 0 only when the two
|
||||
/// products are equal. The products are taken whole with fused multiply-adds (Kahan's method), so
|
||||
/// a difference that is small next to them keeps its value.
|
||||
fn products_difference(a: f64, d: f64, b: f64, c: f64) -> Wide {
|
||||
let [a, b, c, d] = [a, b, c, d].map(Wide::of);
|
||||
let (ad, bc) = (a.e.saturating_add(d.e), b.e.saturating_add(c.e));
|
||||
if b.m == 0.0 || c.m == 0.0 {
|
||||
return Wide::new(a.m * d.m, ad);
|
||||
}
|
||||
if a.m == 0.0 || d.m == 0.0 {
|
||||
return Wide::new(0.0 - b.m * c.m, bc);
|
||||
}
|
||||
// `a·d` and `b·c` both lie in [0.25, 1) times a power of 2; one more than 2^120 times the other
|
||||
// decides the sign and size alone.
|
||||
let gap = bc.saturating_sub(ad);
|
||||
if gap < -120 {
|
||||
return Wide::new(a.m * d.m, ad);
|
||||
}
|
||||
if gap > 120 {
|
||||
return Wide::new(0.0 - b.m * c.m, bc);
|
||||
}
|
||||
let b = b.m * pow2(gap);
|
||||
let w = b * c.m;
|
||||
let err = (0.0 - b).mul_add(c.m, w);
|
||||
Wide::new(a.m.mul_add(d.m, 0.0 - w) + err, ad)
|
||||
}
|
||||
|
||||
/// The determinant of `m`'s linear part.
|
||||
fn determinant(m: Matrix) -> Wide {
|
||||
products_difference(m[0], m[3], m[1], m[2])
|
||||
}
|
||||
|
||||
/// The square root of the size of `m`'s determinant: the factor by which `m` scales lengths on
|
||||
/// average. It is infinite only when that factor is too large for a number.
|
||||
pub(super) fn area_scale(m: Matrix) -> f64 {
|
||||
let d = determinant(m);
|
||||
let (mut v, mut e) = (d.m.abs(), d.e);
|
||||
if e % 2 != 0 {
|
||||
v *= 2.0;
|
||||
e -= 1;
|
||||
}
|
||||
Wide::new(v.sqrt(), e / 2).value()
|
||||
}
|
||||
|
||||
pub(super) fn singular(m: Matrix) -> bool {
|
||||
determinant(m).m == 0.0
|
||||
}
|
||||
|
||||
fn invert(_: &Host, a: &[Data]) -> Answer {
|
||||
let m = matrix(arg(a, 1), "matrix")?;
|
||||
let det = determinant(m);
|
||||
if det.m == 0.0 {
|
||||
return Err(HostError::Error("the matrix is singular and cannot be inverted".into()));
|
||||
}
|
||||
let [a, b, c, d, e, f] = m;
|
||||
// Each value is divided by the determinant before it is brought back into the range of a
|
||||
// number, and the translations are taken whole, so a finite inverse is not lost to an
|
||||
// intermediate value. Adding 0 turns -0 into 0.
|
||||
let over = |w: Wide| w.div(det).value() + 0.0;
|
||||
let plain = |v: f64| over(Wide::of(v));
|
||||
record([plain(d), plain(0.0 - b), plain(0.0 - c), plain(a), over(products_difference(c, f, d, e)), over(products_difference(b, e, a, f))])
|
||||
}
|
||||
|
||||
fn is_equal(_: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Bool(matrix(arg(a, 1), "matrix")? == matrix(arg(a, 2), "secondMatrix")?))
|
||||
}
|
||||
|
||||
fn is_singular(_: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Bool(singular(matrix(arg(a, 1), "matrix")?)))
|
||||
}
|
||||
@@ -70,8 +70,8 @@ use vectorcraft_tools::params::gradient_params;
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, command_value,
|
||||
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method,
|
||||
named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, later, method, named, num,
|
||||
number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -1139,131 +1139,37 @@ fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer {
|
||||
set_overprint(h, a, false)
|
||||
}
|
||||
|
||||
// ---- PathItem transforms ----
|
||||
// ---- PathItem stroke weights for `resize` ----
|
||||
|
||||
/// The member of `Transformation` that `d` names (left out: `CENTER`).
|
||||
fn about_name(d: &Data) -> std::result::Result<&'static str, HostError> {
|
||||
let name = match d {
|
||||
Data::Undefined => "Transformation.CENTER",
|
||||
Data::String(s) => s.as_str(),
|
||||
_ => return Err(HostError::Type("give a Transformation value".into())),
|
||||
};
|
||||
let members = ENUMS.iter().find(|(e, _)| *e == "Transformation").map_or(&[][..], |(_, m)| *m);
|
||||
let member = name.strip_prefix("Transformation.").and_then(|m| members.iter().find(|x| **x == m));
|
||||
member.copied().ok_or_else(|| HostError::Type("give a Transformation value".into()))
|
||||
}
|
||||
|
||||
/// The point of the path's geometric bounds `r`, in document coordinates, that the `Transformation`
|
||||
/// member `name` ([`about_name`]) names.
|
||||
fn about(h: &super::Host, item: Item, name: &str, r: Rect) -> std::result::Result<Point, HostError> {
|
||||
let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
|
||||
Ok(match name {
|
||||
"CENTER" => Point::new(cx, cy),
|
||||
"TOP" => Point::new(cx, r.y0),
|
||||
"BOTTOM" => Point::new(cx, r.y1),
|
||||
"LEFT" => Point::new(r.x0, cy),
|
||||
"RIGHT" => Point::new(r.x1, cy),
|
||||
"TOPLEFT" => Point::new(r.x0, r.y0),
|
||||
"TOPRIGHT" => Point::new(r.x1, r.y0),
|
||||
"BOTTOMLEFT" => Point::new(r.x0, r.y1),
|
||||
"BOTTOMRIGHT" => Point::new(r.x1, r.y1),
|
||||
"DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(Coords::Document, [0.0, 0.0])))?,
|
||||
_ => return Err(HostError::Type("give a Transformation value".into())),
|
||||
})
|
||||
}
|
||||
|
||||
/// The `objects` and `patterns` options of a transform command from the four flags from `i`:
|
||||
/// objects, fill patterns, fill gradients and stroke patterns, each left out or true or false.
|
||||
fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::Result<(), HostError> {
|
||||
let names = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"];
|
||||
let mut flags = [None; 4];
|
||||
for (k, name) in names.iter().enumerate() {
|
||||
flags[k] = given(arg(a, i + k)).map(|d| boolean(d, name)).transpose()?;
|
||||
}
|
||||
if flags[2] == Some(false) {
|
||||
return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2])));
|
||||
}
|
||||
if let (Some(f), Some(s)) = (flags[1], flags[3])
|
||||
&& f != s
|
||||
{
|
||||
return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3])));
|
||||
}
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
if let Some(b) = flags[0] {
|
||||
o.insert("objects".into(), json!(b));
|
||||
}
|
||||
if let Some(b) = flags[1].or(flags[3]) {
|
||||
o.insert("patterns".into(), json!(b));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `translate(deltaX = 0, deltaY = 0, transformObjects?, transformFillPatterns?, ...)`.
|
||||
fn path_translate(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let dx = given(arg(a, 1)).map_or(Ok(0.0), |d| coordinate(d, "deltaX"))?;
|
||||
let dy = given(arg(a, 2)).map_or(Ok(0.0), |d| coordinate(d, "deltaY"))?;
|
||||
let item = this_path(h, a)?;
|
||||
let mut params = json!({"dx": dx, "dy": if h.dom.coords.get() == Coords::Document { -dy } else { dy }});
|
||||
transform_options(a, 3, &mut params)?;
|
||||
if dx != 0.0 || dy != 0.0 {
|
||||
edit_path(h, item, "object.move", params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `rotate(angle, changePositions?, ..., rotateAbout?)`: counterclockwise on the page for a
|
||||
/// positive angle.
|
||||
fn path_rotate(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let angle = number(arg(a, 1), "angle")?;
|
||||
let item = this_path(h, a)?;
|
||||
let place = about_name(arg(a, 6))?;
|
||||
let mut params = json!({"angle": angle});
|
||||
transform_options(a, 2, &mut params)?;
|
||||
if angle.rem_euclid(360.0) != 0.0
|
||||
&& let (Some(r), _) = item_rect(h, item, false)?
|
||||
{
|
||||
let origin = about(h, item, place, r)?;
|
||||
params["origin"] = json!([origin.x, origin.y]);
|
||||
edit_path(h, item, "object.rotate", params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `resize(scaleX, scaleY, changePositions?, ..., changeLineWidths?, scaleAbout?)`: 100 is 100%;
|
||||
/// `changeLineWidths` scales the stroke weight by that percent.
|
||||
fn path_resize(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let sx = number(arg(a, 1), "scaleX")?;
|
||||
let sy = number(arg(a, 2), "scaleY")?;
|
||||
if sx == 0.0 || sy == 0.0 || sx.abs() > 100_000.0 || sy.abs() > 100_000.0 {
|
||||
return Err(HostError::Range("scaleX and scaleY must not be 0 and at most 100000 percent".into()));
|
||||
}
|
||||
let widths = given(arg(a, 7)).map(|d| number(d, "changeLineWidths")).transpose()?;
|
||||
if widths.is_some_and(|w| !(0.0..=100_000.0).contains(&w)) {
|
||||
/// The stroke weight `resize`'s `changeLineWidths` of `percent` gives the path `item`, or `None`
|
||||
/// when the weight stays. A `custom` percent, one other than the resize's own scale, is at most
|
||||
/// 100000.
|
||||
pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, custom: bool) -> std::result::Result<Option<f64>, HostError> {
|
||||
if custom && !(0.0..=100_000.0).contains(&percent) {
|
||||
return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into()));
|
||||
}
|
||||
let item = this_path(h, a)?;
|
||||
let place = about_name(arg(a, 8))?;
|
||||
let mut params = json!({"sx": sx, "sy": sy, "basis": "page", "strokes": false});
|
||||
transform_options(a, 3, &mut params)?;
|
||||
let width = look(h, item)?.width;
|
||||
let new_width = widths.map(|w| width * w / 100.0);
|
||||
if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) {
|
||||
let new_width = width * percent / 100.0;
|
||||
if new_width > MAX_STROKE_WIDTH {
|
||||
return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into()));
|
||||
}
|
||||
if (sx != 100.0 || sy != 100.0)
|
||||
&& let (Some(r), _) = item_rect(h, item, false)?
|
||||
{
|
||||
let origin = about(h, item, place, r)?;
|
||||
params["origin"] = json!([origin.x, origin.y]);
|
||||
edit_path(h, item, "object.scale", params)?;
|
||||
}
|
||||
if let Some(w) = new_width
|
||||
&& (w - width).abs() > 1e-9
|
||||
{
|
||||
edit_path(h, item, "stroke.set", json!({"weight": w}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
Ok(((new_width - width).abs() > 1e-9).then_some(new_width))
|
||||
}
|
||||
|
||||
/// Whether `item` is a path, so [`resized_stroke_weight`] applies to it.
|
||||
pub(super) fn is_path(h: &super::Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))
|
||||
}
|
||||
|
||||
/// Whether the path `item` is a member of a compound path or compound shape, whose stroke the
|
||||
/// compound holds.
|
||||
pub(super) fn paint_held_by_compound(h: &super::Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| paint_owner(&st.doc, item.id, n).id != item.id))
|
||||
}
|
||||
|
||||
/// Sets the stroke weight of the path `item` to `weight` points.
|
||||
pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std::result::Result<(), HostError> {
|
||||
edit_path(h, item, "stroke.set", json!({"weight": weight})).map(|_| ())
|
||||
}
|
||||
|
||||
// ---- PathPoints ----
|
||||
@@ -1862,28 +1768,7 @@ fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: u
|
||||
|
||||
/// The members `PathItem` adds to `PageItem`'s.
|
||||
pub(super) fn path_item_members(l: &Link) -> Vec<Described> {
|
||||
let transform = |first: &[(&'static str, &'static str)]| {
|
||||
let mut args: Vec<(&str, &str)> = first.to_vec();
|
||||
args.extend([
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
]);
|
||||
args
|
||||
};
|
||||
let mut resize = transform(&[("scaleX", "number"), ("scaleY", "number")]);
|
||||
resize.extend([("changeLineWidths", "number"), ("scaleAbout", "Transformation")]);
|
||||
let mut rotate = transform(&[("angle", "number")]);
|
||||
rotate.push(("rotateAbout", "Transformation"));
|
||||
let translate = [
|
||||
("deltaX", "number"),
|
||||
("deltaY", "number"),
|
||||
("transformObjects", "boolean"),
|
||||
("transformFillPatterns", "boolean"),
|
||||
("transformFillGradients", "boolean"),
|
||||
("transformStrokePattern", "boolean"),
|
||||
];
|
||||
// `translate`, `rotate` and `resize` are `PageItem`'s ([`super::transform`]).
|
||||
let mut m = named(vec![
|
||||
("pathPoints", point_get(l, path_points), MemberInfo { collection: true, ..typed("PathPoints") }),
|
||||
("closed", point_property(l, path_closed, path_set_closed), typed("boolean")),
|
||||
@@ -1909,9 +1794,6 @@ pub(super) fn path_item_members(l: &Link) -> Vec<Described> {
|
||||
("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")),
|
||||
("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")),
|
||||
("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")),
|
||||
("translate", method(l, path_translate), returns("undefined", &translate)),
|
||||
("rotate", method(l, path_rotate), returns("undefined", &rotate)),
|
||||
("resize", method(l, path_resize), returns("undefined", &resize)),
|
||||
("selectedPathPoints", get(l, path_selected_points), typed("Array")),
|
||||
]);
|
||||
m.extend(["polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n)));
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
//! `app.preferences`, as the help page <https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/>
|
||||
//! describes it: values a script reads and stores by key with a getter and a setter for each type.
|
||||
//!
|
||||
//! `ShowExternalJSXWarning` is the preference `showExternalScriptWarning`, the warning before a
|
||||
//! script picked with File › Scripts › Other Script… runs. A script turns it on at once; turning it
|
||||
//! off waits for the person to answer Yes to a confirm, and throws when the run cannot ask anyone
|
||||
//! (VectorCraft's own rule). Every other key is kept in
|
||||
//! [`crate::Prefs::script_preferences`], with the preferences, so it lasts across runs and restarts
|
||||
//! and a failed or stopped run puts it back as it was.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help page does not state:
|
||||
//! - A key that was never stored reads as `false`, `0`, `0` or `""`.
|
||||
//! - A getter of another type converts the stored value as `Boolean`, `Number` or `String` do;
|
||||
//! `getIntegerPreference` drops the fraction, and gives `0` for a value that is not a number.
|
||||
//! - A key is a string of 1 to [`MAX_KEY_UNITS`] UTF-16 units without control characters, a string
|
||||
//! value has at most [`MAX_STRING_BYTES`] bytes, and at most [`MAX_KEYS`] keys and
|
||||
//! [`MAX_TOTAL_BYTES`] bytes are stored. A set that would pass a limit throws and stores nothing.
|
||||
//! - A setter's value must have its type: `setIntegerPreference` takes a whole number within
|
||||
//! ±2^53, and `setRealPreference` a finite number.
|
||||
//! - Removing a key that is not stored does nothing; removing `ShowExternalJSXWarning` turns the
|
||||
//! warning back on.
|
||||
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts};
|
||||
|
||||
use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text, typed, typename_of};
|
||||
use crate::ScriptPreference;
|
||||
use crate::script::dialogs::{DialogKind, OnYes, ScriptDialog};
|
||||
|
||||
/// The key that stands for the preference `showExternalScriptWarning`.
|
||||
pub const EXTERNAL_SCRIPT_WARNING: &str = "ShowExternalJSXWarning";
|
||||
/// The longest key, in UTF-16 units.
|
||||
pub const MAX_KEY_UNITS: usize = 256;
|
||||
/// The longest string value, in bytes.
|
||||
pub const MAX_STRING_BYTES: usize = 64 * 1024;
|
||||
/// The most keys stored.
|
||||
pub const MAX_KEYS: usize = 4096;
|
||||
/// The most bytes stored, keys and values together; a value that is not a string counts 8.
|
||||
pub const MAX_TOTAL_BYTES: usize = 1024 * 1024;
|
||||
|
||||
/// The confirm a run shows before a script turns off [`EXTERNAL_SCRIPT_WARNING`]; No is its default.
|
||||
pub const WARNING_OFF_QUESTION: &str = "The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off?";
|
||||
/// The error when a script turns off [`EXTERNAL_SCRIPT_WARNING`] in a run that cannot ask the person.
|
||||
pub const WARNING_OFF_NEEDS_A_PERSON: &str =
|
||||
"ShowExternalJSXWarning can be turned off only after the person at the computer agrees, in a run that can show a dialog";
|
||||
|
||||
/// The largest whole number `setIntegerPreference` takes.
|
||||
const MAX_INTEGER: f64 = 9_007_199_254_740_992.0;
|
||||
|
||||
/// The `app.preferences` member of `Application`.
|
||||
pub(super) fn app_members() -> Vec<Described> {
|
||||
named(vec![("preferences", HostMember::Get(std::rc::Rc::new(|_| Ok(host_ref("Preferences", &[])))), typed("Preferences"))])
|
||||
}
|
||||
|
||||
/// The `Preferences` class.
|
||||
pub(super) fn class(link: &Link) -> HostClass {
|
||||
let l = link;
|
||||
let key = [("key", "string")];
|
||||
super::class(
|
||||
"Preferences",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", typename_of("Preferences"), typed("string")),
|
||||
("getBooleanPreference", method(l, |h, a| get(h, a, Kind::Boolean)), returns("boolean", &key)),
|
||||
("getIntegerPreference", method(l, |h, a| get(h, a, Kind::Integer)), returns("number", &key)),
|
||||
("getRealPreference", method(l, |h, a| get(h, a, Kind::Real)), returns("number", &key)),
|
||||
("getStringPreference", method(l, |h, a| get(h, a, Kind::String)), returns("string", &key)),
|
||||
("setBooleanPreference", method(l, |h, a| set(h, a, Kind::Boolean)), returns("undefined", &[("key", "string"), ("value", "boolean")])),
|
||||
("setIntegerPreference", method(l, |h, a| set(h, a, Kind::Integer)), returns("undefined", &[("key", "string"), ("value", "number")])),
|
||||
("setRealPreference", method(l, |h, a| set(h, a, Kind::Real)), returns("undefined", &[("key", "string"), ("value", "number")])),
|
||||
("setStringPreference", method(l, |h, a| set(h, a, Kind::String)), returns("undefined", &[("key", "string"), ("value", "string")])),
|
||||
("removePreference", method(l, remove), returns("undefined", &key)),
|
||||
]),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Kind {
|
||||
Boolean,
|
||||
Integer,
|
||||
Real,
|
||||
String,
|
||||
}
|
||||
|
||||
/// The key of a call on `app.preferences`: `this` must be that object, and the key a string within
|
||||
/// the limits.
|
||||
fn key_of(a: &[Data]) -> std::result::Result<&str, HostError> {
|
||||
if !matches!(host_ref_parts(arg(a, 0)), Some(("Preferences", _))) {
|
||||
return Err(HostError::Type("this is not a Preferences object".into()));
|
||||
}
|
||||
let Data::String(key) = arg(a, 1) else { return Err(HostError::Type("a preference's key must be a string".into())) };
|
||||
if key.is_empty() || key.encode_utf16().count() > MAX_KEY_UNITS {
|
||||
return Err(HostError::Range(format!(
|
||||
"a preference's key must have a length of 1 to {MAX_KEY_UNITS} (UTF-16 code units, as `length` counts)"
|
||||
)));
|
||||
}
|
||||
if key.chars().any(char::is_control) {
|
||||
return Err(HostError::Error("a preference's key cannot hold control characters".into()));
|
||||
}
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
/// The value stored under `key`, if any.
|
||||
fn stored(h: &Host, key: &str) -> Option<ScriptPreference> {
|
||||
let s = h.session.borrow();
|
||||
if key == EXTERNAL_SCRIPT_WARNING {
|
||||
return Some(ScriptPreference::Boolean(s.prefs.show_external_script_warning));
|
||||
}
|
||||
s.prefs.script_preferences.get(key).cloned()
|
||||
}
|
||||
|
||||
/// `Number(text)`: blank text is 0, `0x`, `0o` and `0b` start a whole number in base 16, 8 or 2,
|
||||
/// and text that is not a number is NaN. The whitespace trimmed is JavaScript's: Unicode's
|
||||
/// `White_Space` without U+0085 (NEXT LINE), and U+FEFF.
|
||||
fn text_number(t: &str) -> f64 {
|
||||
let t = t.trim_matches(|c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}');
|
||||
if t.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let radix = match t.get(..2) {
|
||||
Some("0x" | "0X") => 16,
|
||||
Some("0o" | "0O") => 8,
|
||||
Some("0b" | "0B") => 2,
|
||||
_ => 0,
|
||||
};
|
||||
if radix != 0 {
|
||||
return radix_number(t.get(2..).unwrap_or(""), radix).unwrap_or(f64::NAN);
|
||||
}
|
||||
match t.strip_prefix(['+', '-']).unwrap_or(t) {
|
||||
"Infinity" => {
|
||||
if t.starts_with('-') {
|
||||
f64::NEG_INFINITY
|
||||
} else {
|
||||
f64::INFINITY
|
||||
}
|
||||
}
|
||||
rest if rest.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-')) => t.parse().unwrap_or(f64::NAN),
|
||||
_ => f64::NAN,
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole number `digits` writes in base `radix` (16, 8 or 2), rounded once to the nearest
|
||||
/// number, ties to the even one, and infinite past the largest; `None` when it is empty or holds a
|
||||
/// character that is not a digit of that base.
|
||||
fn radix_number(digits: &str, radix: u32) -> Option<f64> {
|
||||
if digits.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let width = radix.trailing_zeros();
|
||||
// The first 64 bits from the leading 1, how many bits come after them, and whether any of
|
||||
// those is 1.
|
||||
let (mut top, mut taken, mut past, mut sticky) = (0u64, 0u32, 0u64, false);
|
||||
for c in digits.chars() {
|
||||
let d = c.to_digit(radix)?;
|
||||
for bit in (0..width).rev().map(|i| (d >> i) & 1 == 1) {
|
||||
if taken == 0 && !bit {
|
||||
continue;
|
||||
}
|
||||
if taken < 64 {
|
||||
top = (top << 1) | u64::from(bit);
|
||||
taken += 1;
|
||||
} else {
|
||||
past = past.saturating_add(1);
|
||||
sticky |= bit;
|
||||
}
|
||||
}
|
||||
}
|
||||
if taken <= 53 {
|
||||
return Some(top as f64);
|
||||
}
|
||||
// Keep 53 bits; the dropped ones round them to the nearest, ties to even.
|
||||
let drop = taken - 53;
|
||||
let (kept, rest, half) = (top >> drop, top & ((1u64 << drop) - 1), 1u64 << (drop - 1));
|
||||
let up = rest > half || (rest == half && (sticky || kept & 1 == 1));
|
||||
let kept = kept + u64::from(up);
|
||||
let exp = i32::try_from(u64::from(drop).saturating_add(past)).unwrap_or(i32::MAX).min(2000);
|
||||
Some(kept as f64 * 2f64.powi(exp))
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
fn as_number(v: &ScriptPreference) -> f64 {
|
||||
match v {
|
||||
ScriptPreference::Boolean(b) => f64::from(u8::from(*b)),
|
||||
ScriptPreference::Integer(n) => *n as f64,
|
||||
ScriptPreference::Real(n) => *n,
|
||||
ScriptPreference::String(t) => text_number(t),
|
||||
}
|
||||
}
|
||||
|
||||
fn get(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let key = key_of(a)?;
|
||||
let v = stored(h, key);
|
||||
Ok(match (kind, v) {
|
||||
(Kind::Boolean, None) => Data::Bool(false),
|
||||
(Kind::Integer | Kind::Real, None) => num(0.0),
|
||||
(Kind::String, None) => text(""),
|
||||
(Kind::Boolean, Some(v)) => Data::Bool(match v {
|
||||
ScriptPreference::Boolean(b) => b,
|
||||
ScriptPreference::String(t) => !t.is_empty(),
|
||||
v => {
|
||||
let n = as_number(&v);
|
||||
n != 0.0 && !n.is_nan()
|
||||
}
|
||||
}),
|
||||
(Kind::Real, Some(v)) => num(as_number(&v)),
|
||||
(Kind::Integer, Some(v)) => {
|
||||
let n = as_number(&v).trunc();
|
||||
num(if n.is_finite() { n } else { 0.0 })
|
||||
}
|
||||
(Kind::String, Some(v)) => text(match v {
|
||||
ScriptPreference::Boolean(b) => b.to_string(),
|
||||
ScriptPreference::String(t) => t,
|
||||
v => vectorcraft_js::number_to_string(as_number(&v)),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// The bytes `key` and `v` count toward [`MAX_TOTAL_BYTES`].
|
||||
fn size(key: &str, v: &ScriptPreference) -> usize {
|
||||
key.len() + if let ScriptPreference::String(t) = v { t.len() } else { 8 }
|
||||
}
|
||||
|
||||
/// Whether `store` holds at most [`MAX_KEYS`] keys and [`MAX_TOTAL_BYTES`] bytes.
|
||||
pub fn within_limits(store: &std::collections::BTreeMap<String, ScriptPreference>) -> bool {
|
||||
store.len() <= MAX_KEYS && store.iter().map(|(k, v)| size(k, v)).sum::<usize>() <= MAX_TOTAL_BYTES
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
fn set(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let key = key_of(a)?.to_string();
|
||||
let v = arg(a, 2);
|
||||
let value = match (kind, v) {
|
||||
(Kind::Boolean, Data::Bool(b)) => ScriptPreference::Boolean(*b),
|
||||
(Kind::Integer, Data::Number(n)) if n.fract() == 0.0 && n.abs() <= MAX_INTEGER => ScriptPreference::Integer(*n as i64),
|
||||
(Kind::Real, Data::Number(n)) if n.is_finite() => ScriptPreference::Real(*n),
|
||||
(Kind::String, Data::String(t)) if t.len() <= MAX_STRING_BYTES => ScriptPreference::String(t.clone()),
|
||||
(Kind::String, Data::String(_)) => return Err(HostError::Range(format!("a preference's text has at most {MAX_STRING_BYTES} bytes"))),
|
||||
(Kind::Boolean, _) => return Err(HostError::Type("setBooleanPreference needs true or false".into())),
|
||||
(Kind::Integer, _) => return Err(HostError::Type("setIntegerPreference needs a whole number".into())),
|
||||
(Kind::Real, _) => return Err(HostError::Type("setRealPreference needs a finite number".into())),
|
||||
(Kind::String, _) => return Err(HostError::Type("setStringPreference needs a string".into())),
|
||||
};
|
||||
if key == EXTERNAL_SCRIPT_WARNING {
|
||||
let ScriptPreference::Boolean(on) = value else {
|
||||
return Err(HostError::Type(format!("{EXTERNAL_SCRIPT_WARNING} is set with setBooleanPreference")));
|
||||
};
|
||||
return set_warning(h, on);
|
||||
}
|
||||
let mut s = h.session.borrow_mut();
|
||||
let store = &mut s.prefs.script_preferences;
|
||||
if store.get(&key) == Some(&value) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let total: usize = store.iter().filter(|(k, _)| **k != key).map(|(k, v)| size(k, v)).sum();
|
||||
let count = store.len() + usize::from(!store.contains_key(&key));
|
||||
if count > MAX_KEYS {
|
||||
return Err(HostError::Range(format!("app.preferences holds at most {MAX_KEYS} keys")));
|
||||
}
|
||||
if total + size(&key, &value) > MAX_TOTAL_BYTES {
|
||||
return Err(HostError::Range(format!("app.preferences holds at most {MAX_TOTAL_BYTES} bytes")));
|
||||
}
|
||||
store.insert(key, value);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// Sets `showExternalScriptWarning` in the run's preferences: on at once, and off only after the
|
||||
/// person answers Yes to [`WARNING_OFF_QUESTION`] ([`crate::Session::script_answer`] sets it). With
|
||||
/// nobody to ask, turning it off throws and changes nothing. Scripts cannot run `prefs.set`; the
|
||||
/// run's preferences are put back when the run fails and merged into the app's when it ends.
|
||||
fn set_warning(h: &Host, on: bool) -> Answer {
|
||||
if on || !h.session.borrow().prefs.show_external_script_warning {
|
||||
h.session.borrow_mut().prefs.show_external_script_warning = on;
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let question = ScriptDialog {
|
||||
kind: DialogKind::Confirm,
|
||||
message: WARNING_OFF_QUESTION.into(),
|
||||
title: None,
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
};
|
||||
if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) {
|
||||
return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into()));
|
||||
}
|
||||
Err(HostError::Wait)
|
||||
}
|
||||
|
||||
fn remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let key = key_of(a)?;
|
||||
if key == EXTERNAL_SCRIPT_WARNING {
|
||||
h.session.borrow_mut().prefs.show_external_script_warning = true;
|
||||
} else if h.session.borrow().prefs.script_preferences.contains_key(key) {
|
||||
h.session.borrow_mut().prefs.script_preferences.remove(key);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -196,6 +196,8 @@ enum Default {
|
||||
Member(&'static str, &'static str),
|
||||
/// The help page gives no default: any value throws.
|
||||
Unset,
|
||||
/// White as an `RGBColor`: red, green and blue each 255.
|
||||
White,
|
||||
}
|
||||
|
||||
impl Default {
|
||||
@@ -205,6 +207,11 @@ impl Default {
|
||||
(Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9,
|
||||
(Default::Text(a), Data::String(b)) => a == b,
|
||||
(Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m),
|
||||
(Default::White, Data::Object(items)) => {
|
||||
let get = |k: &str| items.iter().find(|(name, _)| name == k).map(|(_, v)| v);
|
||||
matches!(get("typename"), Some(Data::String(t)) if t == "RGBColor")
|
||||
&& ["red", "green", "blue"].iter().all(|k| matches!(get(k), Some(Data::Number(n)) if *n == 255.0))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -560,7 +567,7 @@ fn png24_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::R
|
||||
raster_map("ExportOptionsPNG24", name, d, p)
|
||||
}
|
||||
|
||||
const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))];
|
||||
const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))];
|
||||
|
||||
fn png24_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
@@ -588,7 +595,7 @@ fn jpeg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Re
|
||||
}
|
||||
|
||||
const JPEG_KEPT: &[(&str, Default)] =
|
||||
&[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))];
|
||||
&[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))];
|
||||
|
||||
fn jpeg_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
@@ -733,7 +740,7 @@ pub(super) fn refused(message: &str, path: &str) -> HostError {
|
||||
|
||||
/// Runs `f` with the commands' reads and writes held to the script's own grants
|
||||
/// ([`super::super::files::Disk::exact`]).
|
||||
pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
|
||||
pub(super) fn exactly<T>(h: &Host, f: impl FnOnce() -> Result<T, HostError>) -> Result<T, HostError> {
|
||||
h.disk.borrow_mut().exact = true;
|
||||
let r = f();
|
||||
h.disk.borrow_mut().exact = false;
|
||||
|
||||
@@ -0,0 +1,928 @@
|
||||
//! Tracing in the script object model: `PlacedItem.trace()` and `RasterItem.trace()`, the
|
||||
//! `PluginItem` an Image Trace object is, its `TracingObject` and its `TracingOptions`, as the help
|
||||
//! pages <https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/> describe them.
|
||||
//!
|
||||
//! An Image Trace object is a group that holds its source image, hidden, as its first object.
|
||||
//! Tracing runs `imageTrace.make`, expanding `imageTrace.expand`, releasing `imageTrace.release`
|
||||
//! and a change of view `imageTrace.setView`, so each joins the run's transaction and its work
|
||||
//! counts against the run's limits.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `trace()` returns once the trace is made, so the counts can be read at once. It traces with
|
||||
//! the Default preset.
|
||||
//! - The traced image stays the same object: `sourceArt` gives it, and `releaseTracing()` gives it
|
||||
//! back. `trace()` on an image that is the source of a tracing throws [`ALREADY_TRACED`], and on
|
||||
//! a linked image whose file is missing throws `Linked image is missing`.
|
||||
//! - `pathCount` counts the traced paths, without the seam fills an Abutting trace adds,
|
||||
//! `anchorCount` their anchor points and `usedColorCount` the different paints they are filled
|
||||
//! and stroked with, as the tracing is when they are read. `areaCount` throws. `imageResolution`
|
||||
//! is the source image's pixels per inch as it is placed; an image placed at a different
|
||||
//! resolution across and down has none.
|
||||
//! - Assigning an option, or `loadFromPreset(name)`, traces again unless the options are already
|
||||
//! so. Tracing again makes a new object: the `PluginItem`, its `TracingObject` and its
|
||||
//! `TracingOptions` follow it. A tracing that another command traced again, expanded or
|
||||
//! released, or whose source image was deleted, is stale.
|
||||
//! - Tracing again throws [`ADDED_ARTWORK`], with nothing changed, when the tracing holds an object
|
||||
//! its trace did not make, whether this run, an earlier run or a command added it, and
|
||||
//! `releaseTracing()` throws [`ADDED_ARTWORK_RELEASE`] in the same case. The tracing records the
|
||||
//! objects its trace made ([`crate::doc::TraceMade`]), and a copy of it records their copies. A
|
||||
//! tracing saved without that record is checked only for objects added in this run.
|
||||
//! - `palette` is `""` for the automatic palette, or `"Limited"`, `"Full Tone"` or
|
||||
//! `"Document Library"`. `minArea` is the Noise setting in pixels: an area smaller than it is not
|
||||
//! traced. `tracingMode` has no value for the Flat Logo mode. The options with no VectorCraft
|
||||
//! setting throw [`not_implemented`].
|
||||
//! - `viewRaster` and `viewVector` take only the pairs of the Image Trace views
|
||||
//! ([`VIEWS`]); the Split view has neither.
|
||||
//! - `storeToPreset(name)` gives `false` for a built-in preset and `Custom`; a script cannot change
|
||||
//! the saved presets, so any other name throws. A preset name has at most [`MAX_PRESET_NAME`]
|
||||
//! bytes and none of `/`, `\`, `:` or control characters.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostMember, MemberInfo, host_ref, host_ref_parts};
|
||||
|
||||
use super::{
|
||||
Answer, Described, Host, Item, Link, STALE_ITEM, arg, boolean, class, command, command_value, edit_item, float, get, item_of, item_ref, method,
|
||||
named, node_of, num, number, on_doc, property, returns, text, typed, typename_of, whole, with_doc,
|
||||
};
|
||||
use crate::doc::{Node, TraceView};
|
||||
use crate::{NodeId, NodeKind};
|
||||
|
||||
/// The error of `trace()` on an image that is the source of a tracing.
|
||||
pub const ALREADY_TRACED: &str = "The image is the source art of a tracing";
|
||||
/// The error of tracing again a tracing that holds an object its trace did not make.
|
||||
pub const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork";
|
||||
/// The error of releasing a tracing that holds an object its trace did not make.
|
||||
pub const ADDED_ARTWORK_RELEASE: &str = "Cannot release a tracing containing added artwork";
|
||||
/// The error of options that trace with neither fills nor strokes.
|
||||
pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes";
|
||||
/// The error of `expandTracing(true)`.
|
||||
pub const VIEWED_EXPAND: &str = "TracingObject.expandTracing(true) is not implemented";
|
||||
/// The longest preset name `loadFromPreset` and `storeToPreset` take, in bytes.
|
||||
pub const MAX_PRESET_NAME: usize = 256;
|
||||
/// The most times one run traces a tracing again through its options.
|
||||
pub const MAX_RETRACES: usize = 10_000;
|
||||
/// The largest `minArea`: the most pixels the tracer traces ([`vectorcraft_trace::MAX_PIXELS`]).
|
||||
pub const MAX_MIN_AREA: u64 = vectorcraft_trace::MAX_PIXELS;
|
||||
|
||||
/// The enumerations the members here give values of, as the help page
|
||||
/// <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/> lists them.
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("TracingModeType", &["TRACINGMODEBLACKANDWHITE", "TRACINGMODECOLOR", "TRACINGMODEGRAY"]),
|
||||
(
|
||||
"ViewRasterType",
|
||||
&["TRACINGVIEWRASTERADJUSTEDIMAGE", "TRACINGVIEWRASTERNOIMAGE", "TRACINGVIEWRASTERORIGINALIMAGE", "TRACINGVIEWRASTERTRANSPARENTIMAGE"],
|
||||
),
|
||||
(
|
||||
"ViewVectorType",
|
||||
&["TRACINGVIEWVECTORNOTRACINGRESULT", "TRACINGVIEWVECTOROUTLINES", "TRACINGVIEWVECTOROUTLINESWITHTRACING", "TRACINGVIEWVECTORTRACINGRESULT"],
|
||||
),
|
||||
];
|
||||
|
||||
/// The classes this module defines.
|
||||
pub(super) const CLASSES: &[&str] = &["PluginItem"];
|
||||
|
||||
/// Each Image Trace view with the `viewRaster` and `viewVector` that give it.
|
||||
const VIEWS: &[(TraceView, &str, &str)] = &[
|
||||
(TraceView::Result, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"),
|
||||
(TraceView::ResultWithOutlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINESWITHTRACING"),
|
||||
(TraceView::Outlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"),
|
||||
(TraceView::OutlinesWithSource, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"),
|
||||
(TraceView::Source, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTORNOTRACINGRESULT"),
|
||||
];
|
||||
|
||||
/// Each `tracingMode` with its Image Trace mode.
|
||||
const MODES: &[(&str, &str)] = &[
|
||||
("TracingModeType.TRACINGMODEBLACKANDWHITE", "blackAndWhite"),
|
||||
("TracingModeType.TRACINGMODEGRAY", "grayscale"),
|
||||
("TracingModeType.TRACINGMODECOLOR", "color"),
|
||||
];
|
||||
|
||||
/// Each `palette` name with its Image Trace palette.
|
||||
const PALETTES: &[(&str, &str)] = &[("", "automatic"), ("Limited", "limited"), ("Full Tone", "fullTone"), ("Document Library", "documentLibrary")];
|
||||
|
||||
/// The options with no VectorCraft setting.
|
||||
const NOT_IMPLEMENTED: &[&str] = &[
|
||||
"cornerAngle",
|
||||
"livePaintOutput",
|
||||
"maxStrokeWeight",
|
||||
"minStrokeLength",
|
||||
"outputToSwatches",
|
||||
"pathFitting",
|
||||
"preprocessBlur",
|
||||
"resample",
|
||||
"resampleResolution",
|
||||
];
|
||||
|
||||
/// What a run keeps for tracings: for each document uid and Image Trace object a script traced
|
||||
/// again through its options, the id of the object that replaced it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
next: RefCell<HashMap<(u64, u64), u64>>,
|
||||
/// `next` the other way round: for each replacing object, the object it replaced.
|
||||
prev: RefCell<HashMap<(u64, u64), u64>>,
|
||||
sources: RefCell<HashMap<(u64, u64), NodeId>>,
|
||||
descendants: RefCell<HashMap<(u64, u64), HashSet<NodeId>>>,
|
||||
retraces: Cell<usize>,
|
||||
}
|
||||
|
||||
/// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put
|
||||
/// it back put back the same object), else the first object the document holds among those that
|
||||
/// replaced it, one after the other, when this run traced it again (an Undo can put back one of
|
||||
/// them), else the last of them, else `id`.
|
||||
pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId {
|
||||
let s = h.session.borrow();
|
||||
let doc = s.documents().iter().find(|d| d.uid == uid);
|
||||
let held = |id: NodeId| doc.is_some_and(|d| d.doc.node(id).is_some());
|
||||
let next = h.dom.tracing.next.borrow();
|
||||
let mut id = id;
|
||||
// Each object is replaced by one made later, so the steps end; the bound holds them anyway.
|
||||
for _ in 0..=next.len() {
|
||||
if held(id) {
|
||||
return id;
|
||||
}
|
||||
match next.get(&(uid, id.0)) {
|
||||
Some(n) => id = NodeId(*n),
|
||||
None => return id,
|
||||
}
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// The first object of the run's chain of replacements that leads to `id` in the document `uid`,
|
||||
/// so every handle to a tracing traced again names the same object; `id` when no earlier object
|
||||
/// in the chain resolves to it.
|
||||
pub(super) fn origin(h: &Host, uid: u64, id: NodeId) -> NodeId {
|
||||
let first = {
|
||||
let prev = h.dom.tracing.prev.borrow();
|
||||
let mut first = id;
|
||||
// Each object replaces one made before it, so the steps end; the bound holds them anyway.
|
||||
for _ in 0..prev.len() {
|
||||
match prev.get(&(uid, first.0)) {
|
||||
Some(old) => first = NodeId(*old),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
first
|
||||
};
|
||||
if first != id && follow(h, uid, first) == id { first } else { id }
|
||||
}
|
||||
|
||||
/// Records that `new` replaced `old` in the document `uid`.
|
||||
fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) {
|
||||
let mut prev = h.dom.tracing.prev.borrow_mut();
|
||||
// A second replacement of `old` takes the place of the first in both directions.
|
||||
if let Some(earlier) = h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0)
|
||||
&& prev.get(&(uid, earlier)) == Some(&old.0)
|
||||
{
|
||||
prev.remove(&(uid, earlier));
|
||||
}
|
||||
prev.insert((uid, new.0), old.0);
|
||||
}
|
||||
|
||||
pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) {
|
||||
let mut first = true;
|
||||
if let Some(source) = group.children().and_then(|c| c.first()) {
|
||||
let mut sources = h.dom.tracing.sources.borrow_mut();
|
||||
first = !sources.contains_key(&(uid, group.id.0));
|
||||
sources.entry((uid, group.id.0)).or_insert(source.id);
|
||||
}
|
||||
// Only a tracing saved without the record of the objects its trace made needs the snapshot,
|
||||
// taken the first time this run sees it.
|
||||
if !first || group.trace_made().is_some() {
|
||||
return;
|
||||
}
|
||||
h.dom.tracing.descendants.borrow_mut().entry((uid, group.id.0)).or_insert_with(|| {
|
||||
let mut ids = HashSet::new();
|
||||
group.walk(&mut |n| {
|
||||
if n.id != group.id {
|
||||
ids.insert(n.id);
|
||||
}
|
||||
});
|
||||
ids
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool {
|
||||
let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied();
|
||||
source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source))
|
||||
}
|
||||
|
||||
/// The error of a member with no VectorCraft setting.
|
||||
pub fn not_implemented(class: &str, name: &str) -> String {
|
||||
format!("{class}.{name} is not implemented")
|
||||
}
|
||||
|
||||
fn out_of_range(name: &str, range: &str) -> HostError {
|
||||
HostError::Range(format!("TracingOptions.{name} is out of range: {range}"))
|
||||
}
|
||||
|
||||
fn invalid(name: &str) -> HostError {
|
||||
HostError::Error(format!("TracingOptions.{name} has an invalid value"))
|
||||
}
|
||||
|
||||
fn stale() -> HostError {
|
||||
HostError::Error(STALE_ITEM.into())
|
||||
}
|
||||
|
||||
fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> {
|
||||
match d {
|
||||
Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first id of a command's result `key`: a number or a list of them, read exactly.
|
||||
fn result_id(v: &Value, key: &str) -> Option<NodeId> {
|
||||
match &v[key] {
|
||||
Value::Array(a) => a.first().and_then(Value::as_u64).map(NodeId),
|
||||
n => n.as_u64().map(NodeId),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Image Trace object, its document and the id its handle holds, of the `cls` (`TracingObject`
|
||||
/// or `TracingOptions`) `d` names. It must still be an Image Trace object of its document.
|
||||
fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 5]), HostError> {
|
||||
let Some((c, handle)) = host_ref_parts(d).filter(|(c, _)| *c == cls) else {
|
||||
return Err(HostError::Type(format!("this is not a {cls}")));
|
||||
};
|
||||
let &[run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) };
|
||||
let (doc, original) = node_of(h, &handle).ok_or_else(stale)?;
|
||||
let id = follow(h, doc.uid, original);
|
||||
let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|g| crate::cmd::is_trace_group(g) && same_source(h, doc.uid, original, g)));
|
||||
if !live {
|
||||
return Err(stale());
|
||||
}
|
||||
Ok((Item { doc, id }, [run, uid, high, low, reverts]))
|
||||
}
|
||||
|
||||
/// The `PluginItem` `this` names, with the handle numbers its `tracing` keeps.
|
||||
fn plugin_of(h: &Host, a: &[Data]) -> Result<(Item, [f64; 5]), HostError> {
|
||||
match host_ref_parts(arg(a, 0)) {
|
||||
Some(("PluginItem", handle)) => {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
match handle.as_slice() {
|
||||
&[run, uid, high, low, reverts] => Ok((item, [run, uid, high, low, reverts])),
|
||||
_ => Err(HostError::Type("this is not a PluginItem".into())),
|
||||
}
|
||||
}
|
||||
_ => Err(HostError::Type("this is not a PluginItem".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the Image Trace object of `item` with `f`.
|
||||
fn read_group<T>(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) -> Result<T, HostError>) -> Result<T, HostError> {
|
||||
with_doc(h, item.doc, |_, st| match st.doc.node(item.id) {
|
||||
Some(n) => f(st, n),
|
||||
None => Err(stale()),
|
||||
})
|
||||
}
|
||||
|
||||
fn refuse_uneditable(h: &Host, item: Item) -> Result<(), HostError> {
|
||||
let editable = with_doc(h, item.doc, |_, st| super::editable(&st.doc, item.id) && !super::on_locked_artboard(h, st, item.id));
|
||||
if !editable {
|
||||
return Err(HostError::Error(format!("Cannot edit page item {}", item.id.0)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs command `id` with `params` on `item`'s document → the object its result names under `key`.
|
||||
/// The selection stays as it was, with that object in place of `item`.
|
||||
fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result<NodeId, HostError> {
|
||||
refuse_uneditable(h, item)?;
|
||||
let mut before = with_doc(h, item.doc, |_, st| st.selection.clone());
|
||||
on_doc(h, item.doc.uid, false, |h| {
|
||||
let (_, r) = command_value(h, id, params)?;
|
||||
for w in r.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
super::super::each_line(&format!("{id}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
|
||||
}
|
||||
let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?;
|
||||
let remap = |i: NodeId| if i == item.id { new } else { i };
|
||||
before.objects = before.objects.into_iter().map(remap).collect();
|
||||
let mut seen = HashSet::new();
|
||||
before.objects.retain(|i| seen.insert(*i));
|
||||
before.key = before.key.map(remap);
|
||||
before.target = before.target.map(remap);
|
||||
before.on_path_member = before.on_path_member.map(remap);
|
||||
let restore = {
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
(st.selection != before).then(|| st.doc.clone())
|
||||
};
|
||||
if let Some(doc) = restore {
|
||||
super::restore_selection(h, &doc, &before)?;
|
||||
}
|
||||
Ok(new)
|
||||
})
|
||||
}
|
||||
|
||||
/// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make,
|
||||
/// and "Cannot edit page item" when it holds a locked object other than its source image, which
|
||||
/// the replacement would discard. The objects looked at are charged to the run either way.
|
||||
fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
|
||||
let (visited, result) = read_group(h, item, |_, group| {
|
||||
remember_source(h, item.doc.uid, group);
|
||||
// The objects the trace made, as the tracing records them; a tracing saved without that
|
||||
// record is checked against the objects it held when this run first saw it.
|
||||
let made = group.trace_made();
|
||||
let descendants = h.dom.tracing.descendants.borrow();
|
||||
let ids = match made {
|
||||
Some(_) => None,
|
||||
None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?),
|
||||
};
|
||||
let source = group.children().and_then(|c| c.first()).map(|n| n.id);
|
||||
let mut visited = 0u64;
|
||||
let mut locked = None;
|
||||
let mut todo: Vec<&Arc<Node>> = group.children().map(|c| c.iter().collect()).unwrap_or_default();
|
||||
while let Some(n) = todo.pop() {
|
||||
visited += 1;
|
||||
let added = match (&made, ids) {
|
||||
(Some(m), _) => !m.contains(n.id),
|
||||
(None, Some(ids)) => !ids.contains(&n.id),
|
||||
(None, None) => false,
|
||||
};
|
||||
// Added artwork is reported before a locked object, whichever comes first.
|
||||
if added {
|
||||
return Ok((visited, Err(HostError::Error(refusal.into()))));
|
||||
}
|
||||
if n.locked && Some(n.id) != source && locked.is_none() {
|
||||
locked = Some(n.id);
|
||||
}
|
||||
todo.extend(n.children().into_iter().flatten());
|
||||
}
|
||||
Ok((visited, locked.map_or(Ok(()), |id| Err(HostError::Error(format!("Cannot edit page item {}", id.0))))))
|
||||
})?;
|
||||
h.charge_call(visited)?;
|
||||
result
|
||||
}
|
||||
|
||||
/// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its
|
||||
/// script objects follow the new one.
|
||||
fn retrace(h: &Host, item: Item, mut params: Map<String, Value>) -> Result<(), HostError> {
|
||||
if h.dom.tracing.retraces.get() >= MAX_RETRACES {
|
||||
return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times")));
|
||||
}
|
||||
refuse_added(h, item, ADDED_ARTWORK)?;
|
||||
params.insert("id".into(), json!(item.id.0));
|
||||
// One savepoint covers the trace and the selection's restore, so a failed restore undoes the trace.
|
||||
let new = super::atomically(h, |h| replace(h, item, "imageTrace.make", &Value::Object(params), "id"))?;
|
||||
read_group(h, Item { id: new, ..item }, |_, group| {
|
||||
remember_source(h, item.doc.uid, group);
|
||||
Ok(())
|
||||
})?;
|
||||
h.dom.tracing.retraces.set(h.dom.tracing.retraces.get() + 1);
|
||||
replaced(h, item.doc.uid, item.id, new);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- PlacedItem and RasterItem ----
|
||||
|
||||
/// `trace()`: `imageTrace.make` of the image with the Default preset → its `PluginItem`.
|
||||
fn image_trace(h: &Host, a: &[Data], cls: &str) -> Answer {
|
||||
let item = match host_ref_parts(arg(a, 0)) {
|
||||
Some((c, _)) if c == cls => item_of(h, arg(a, 0))?,
|
||||
_ => return Err(HostError::Type(format!("this is not a {cls}"))),
|
||||
};
|
||||
let (source, linked) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let source = crate::cmd::is_trace_source(d, item.id);
|
||||
let linked = matches!(d.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some());
|
||||
(source, linked)
|
||||
});
|
||||
if source {
|
||||
return Err(HostError::Error(ALREADY_TRACED.into()));
|
||||
}
|
||||
if linked {
|
||||
let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?;
|
||||
if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") {
|
||||
return Err(HostError::Error(super::images::MISSING_LINK.into()));
|
||||
}
|
||||
}
|
||||
let id = replace(h, item, "imageTrace.make", &json!({"id": item.id.0}), "id")?;
|
||||
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
|
||||
}
|
||||
|
||||
fn placed_trace(h: &Host, a: &[Data]) -> Answer {
|
||||
image_trace(h, a, "PlacedItem")
|
||||
}
|
||||
|
||||
fn raster_trace(h: &Host, a: &[Data]) -> Answer {
|
||||
image_trace(h, a, "RasterItem")
|
||||
}
|
||||
|
||||
// ---- PluginItem ----
|
||||
|
||||
fn plugin_is_tracing(h: &Host, a: &[Data]) -> Answer {
|
||||
plugin_of(h, a)?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
fn plugin_tracing(h: &Host, a: &[Data]) -> Answer {
|
||||
let (item, handle) = plugin_of(h, a)?;
|
||||
let source = read_group(h, item, |_, g| g.children().and_then(|c| c.first()).map(|n| n.id).ok_or_else(stale))?;
|
||||
let (_, original) = node_of(h, &handle).ok_or_else(stale)?;
|
||||
h.dom.tracing.sources.borrow_mut().entry((item.doc.uid, original.0)).or_insert(source);
|
||||
Ok(host_ref("TracingObject", &handle))
|
||||
}
|
||||
|
||||
// ---- TracingObject ----
|
||||
|
||||
/// What a tracing's counts are made of.
|
||||
#[derive(Default)]
|
||||
struct Counts {
|
||||
paths: u64,
|
||||
anchors: u64,
|
||||
colors: u64,
|
||||
/// The objects looked at.
|
||||
visited: u64,
|
||||
}
|
||||
|
||||
/// Which of a tracing's counts a read needs; the others are not worked out.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Metric {
|
||||
Paths,
|
||||
Anchors,
|
||||
Colors,
|
||||
}
|
||||
|
||||
/// The anchor points of `n` and every path in it, adding each object looked at below `n` to
|
||||
/// `visited`.
|
||||
fn anchors_of(n: &Node, visited: &mut u64) -> u64 {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.anchor_count() as u64,
|
||||
_ => n.children().map_or(0, |c| {
|
||||
c.iter()
|
||||
.map(|m| {
|
||||
*visited += 1;
|
||||
anchors_of(m, visited)
|
||||
})
|
||||
.sum()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The traced paths of the Image Trace object `g`, their anchor points and paints: every path
|
||||
/// and compound path in it but its source image, the seam fills and clipping paths. The seam fills
|
||||
/// are a clip group directly in the tracing that [`crate::cmd::is_seam_fills`] accepts, or, for a
|
||||
/// trace made before seam fills were clipped, the lowest item above the source image when it
|
||||
/// accepts that. A group nested deeper, or an unclipped group higher up, is counted. An Image
|
||||
/// Trace object inside `g` leaves out its own seam fills the same way. Only the count `metric`
|
||||
/// names is worked out; a compound path counts as one path, and the paths inside it are looked at
|
||||
/// (and counted in `visited`) only for its anchor points.
|
||||
fn counts(g: &Node, metric: Metric) -> Counts {
|
||||
let mut c = Counts::default();
|
||||
let mut paints = HashSet::new();
|
||||
let mut todo: Vec<&Arc<Node>> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default();
|
||||
let mut seams = seam_fills_of(g);
|
||||
while let Some(n) = todo.pop() {
|
||||
c.visited += 1;
|
||||
if seams.contains(&n.id) {
|
||||
continue;
|
||||
}
|
||||
if crate::cmd::is_trace_group(n) {
|
||||
seams.extend(seam_fills_of(n));
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { clipping: true, .. } => {}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
c.paths += 1;
|
||||
match metric {
|
||||
Metric::Paths => {}
|
||||
Metric::Anchors => c.anchors += anchors_of(n, &mut c.visited),
|
||||
Metric::Colors => {
|
||||
for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] {
|
||||
if paint != vectorcraft_color::Paint::None
|
||||
&& let Ok(key) = serde_json::to_string(&paint)
|
||||
{
|
||||
paints.insert(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => todo.extend(n.children().into_iter().flatten()),
|
||||
}
|
||||
}
|
||||
c.colors = paints.len() as u64;
|
||||
c
|
||||
}
|
||||
|
||||
/// The seam fills of the Image Trace object `g` ([`counts`]).
|
||||
fn seam_fills_of(g: &Node) -> HashSet<NodeId> {
|
||||
g.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.skip(1)
|
||||
.enumerate()
|
||||
.filter(|(i, n)| (*i == 0 || matches!(n.kind, NodeKind::Group { clip: true, .. })) && crate::cmd::is_seam_fills(n))
|
||||
.map(|(_, n)| n.id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reads the counts of the tracing `this` names with `f`.
|
||||
fn count(h: &Host, a: &[Data], metric: Metric) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
let c = read_group(h, item, |_, g| Ok(counts(g, metric)))?;
|
||||
h.charge_call(c.visited)?;
|
||||
Ok(num(float(match metric {
|
||||
Metric::Paths => c.paths,
|
||||
Metric::Anchors => c.anchors,
|
||||
Metric::Colors => c.colors,
|
||||
})))
|
||||
}
|
||||
|
||||
fn tracing_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, Metric::Paths)
|
||||
}
|
||||
|
||||
fn tracing_anchors(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, Metric::Anchors)
|
||||
}
|
||||
|
||||
fn tracing_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, Metric::Colors)
|
||||
}
|
||||
|
||||
fn tracing_areas(h: &Host, a: &[Data]) -> Answer {
|
||||
tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
Err(HostError::Error(not_implemented("TracingObject", "areaCount")))
|
||||
}
|
||||
|
||||
/// `imageResolution`: the source image's pixels per inch, 72 over the size of a pixel in points.
|
||||
fn tracing_resolution(h: &Host, a: &[Data]) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
read_group(h, item, |_, g| {
|
||||
let source = g.children().and_then(|c| c.first()).ok_or_else(stale)?;
|
||||
let NodeKind::Image(im) = &source.kind else { return Err(stale()) };
|
||||
let none = || HostError::Error("the source image has no single resolution".into());
|
||||
if source.is_distorted_image() {
|
||||
return Err(none());
|
||||
}
|
||||
let [xa, xb, ya, yb, ..] = im.xf.as_coeffs();
|
||||
let (across, down) = (xa.hypot(xb), ya.hypot(yb));
|
||||
if across <= 1e-12 || down <= 1e-12 || (across - down).abs() > 1e-9 * across.max(down) {
|
||||
return Err(none());
|
||||
}
|
||||
Ok(num(72.0 / across))
|
||||
})
|
||||
}
|
||||
|
||||
fn tracing_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
Ok(host_ref("PluginItem", &handle))
|
||||
}
|
||||
|
||||
fn tracing_source(h: &Host, a: &[Data]) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
read_group(h, item, |st, g| g.children().and_then(|c| c.first()).map(|s| item_ref(h, st, s.id)).ok_or_else(stale))
|
||||
}
|
||||
|
||||
fn tracing_options(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
Ok(host_ref("TracingOptions", &handle))
|
||||
}
|
||||
|
||||
/// `expandTracing(viewed?)`: `imageTrace.expand` → the `GroupItem` that takes the tracing's place.
|
||||
fn tracing_expand(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::Undefined | Data::Bool(false) => {}
|
||||
Data::Bool(true) => {
|
||||
tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
return Err(HostError::Error(VIEWED_EXPAND.into()));
|
||||
}
|
||||
_ => return Err(HostError::Type("viewed must be true or false".into())),
|
||||
}
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
let id = replace(h, item, "imageTrace.expand", &json!({"ids": [item.id.0]}), "ids")?;
|
||||
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
|
||||
}
|
||||
|
||||
/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. A
|
||||
/// tracing that holds an object its trace did not make throws [`ADDED_ARTWORK_RELEASE`], since the
|
||||
/// release keeps only the source image.
|
||||
fn tracing_release(h: &Host, a: &[Data]) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
refuse_added(h, item, ADDED_ARTWORK_RELEASE)?;
|
||||
let id = replace(h, item, "imageTrace.release", &json!({"ids": [item.id.0]}), "ids")?;
|
||||
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
|
||||
}
|
||||
|
||||
// ---- TracingOptions ----
|
||||
|
||||
/// The tracing `this` names, the settings it was traced with, its view and its preset's name.
|
||||
fn options_of(h: &Host, a: &[Data]) -> Result<(Item, Map<String, Value>, TraceView, String), HostError> {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingOptions")?;
|
||||
read_group(h, item, |_, g| {
|
||||
let trace = g.extras().trace.as_deref();
|
||||
let params = trace.and_then(|t| t.get("params")).and_then(Value::as_object).cloned();
|
||||
let params = params.ok_or_else(|| HostError::Error("the tracing has no recorded options".into()))?;
|
||||
let preset = trace.and_then(|t| t.get("preset")).and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
Ok((item, params, g.trace_view(), preset))
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the setting `key` of the tracing `this` names with `f`.
|
||||
fn read_option(h: &Host, a: &[Data], key: &str, f: impl FnOnce(&Value) -> Answer) -> Answer {
|
||||
let (_, params, ..) = options_of(h, a)?;
|
||||
f(params.get(key).unwrap_or(&Value::Null))
|
||||
}
|
||||
|
||||
/// Traces again with the setting `key` at `value`, unless it is at that value already.
|
||||
fn write_option(h: &Host, a: &[Data], key: &str, value: Value) -> Answer {
|
||||
let (item, mut params, ..) = options_of(h, a)?;
|
||||
if params.get(key) == Some(&value) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
params.insert(key.into(), value);
|
||||
let on = |k: &str| params.get(k).and_then(Value::as_bool) == Some(true);
|
||||
if !on("fills") && !on("strokes") {
|
||||
return Err(HostError::Error(NEEDS_FILLS_OR_STROKES.into()));
|
||||
}
|
||||
let mut p = Map::new();
|
||||
p.insert("params".into(), Value::Object(params));
|
||||
retrace(h, item, p)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// A whole number from `lo` to `hi` for the option `name`.
|
||||
fn whole_in(d: &Data, name: &str, lo: u64, hi: u64) -> Result<u64, HostError> {
|
||||
let n = number(d, &format!("TracingOptions.{name}"))?;
|
||||
if n.fract() != 0.0 || n < float(lo) || n > float(hi) {
|
||||
return Err(out_of_range(name, &format!("a whole number from {lo} to {hi}")));
|
||||
}
|
||||
whole(n).ok_or_else(|| out_of_range(name, &format!("a whole number from {lo} to {hi}")))
|
||||
}
|
||||
|
||||
fn as_number(v: &Value) -> Answer {
|
||||
v.as_f64().map(num).ok_or_else(|| HostError::Error("the tracing's options are damaged".into()))
|
||||
}
|
||||
|
||||
fn as_bool(v: &Value) -> Answer {
|
||||
v.as_bool().map(Data::Bool).ok_or_else(|| HostError::Error("the tracing's options are damaged".into()))
|
||||
}
|
||||
|
||||
fn options_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "mode", |v| {
|
||||
let mode = v.as_str().unwrap_or_default();
|
||||
match MODES.iter().find(|(_, m)| *m == mode) {
|
||||
Some((name, _)) => Ok(text(*name)),
|
||||
None => Err(HostError::Error("TracingOptions.tracingMode has no value for this tracing's mode".into())),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn options_set_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let mode = match arg(a, 1) {
|
||||
Data::String(s) => MODES.iter().find(|(n, _)| n == s).map(|(_, m)| *m),
|
||||
_ => None,
|
||||
};
|
||||
let mode = mode.ok_or_else(|| HostError::Type("TracingOptions.tracingMode must be a TracingModeType value".into()))?;
|
||||
write_option(h, a, "mode", json!(mode))
|
||||
}
|
||||
|
||||
fn options_threshold(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "threshold", as_number)
|
||||
}
|
||||
|
||||
fn options_set_threshold(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = whole_in(arg(a, 1), "threshold", 0, 255)?;
|
||||
write_option(h, a, "threshold", json!(v))
|
||||
}
|
||||
|
||||
fn options_max_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "colors", as_number)
|
||||
}
|
||||
|
||||
fn options_set_max_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = whole_in(arg(a, 1), "maxColors", 2, 256)?;
|
||||
write_option(h, a, "colors", json!(v))
|
||||
}
|
||||
|
||||
fn options_min_area(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "noise", as_number)
|
||||
}
|
||||
|
||||
fn options_set_min_area(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = whole_in(arg(a, 1), "minArea", 0, MAX_MIN_AREA)?;
|
||||
write_option(h, a, "noise", json!(v))
|
||||
}
|
||||
|
||||
fn options_fills(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "fills", as_bool)
|
||||
}
|
||||
|
||||
fn options_set_fills(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = boolean(arg(a, 1), "TracingOptions.fills")?;
|
||||
write_option(h, a, "fills", json!(v))
|
||||
}
|
||||
|
||||
fn options_strokes(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "strokes", as_bool)
|
||||
}
|
||||
|
||||
fn options_set_strokes(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = boolean(arg(a, 1), "TracingOptions.strokes")?;
|
||||
write_option(h, a, "strokes", json!(v))
|
||||
}
|
||||
|
||||
fn options_ignore_white(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "ignoreWhite", as_bool)
|
||||
}
|
||||
|
||||
fn options_set_ignore_white(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = boolean(arg(a, 1), "TracingOptions.ignoreWhite")?;
|
||||
write_option(h, a, "ignoreWhite", json!(v))
|
||||
}
|
||||
|
||||
fn options_palette(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "palette", |v| {
|
||||
let palette = v.as_str().unwrap_or_default();
|
||||
match PALETTES.iter().find(|(_, p)| *p == palette) {
|
||||
Some((name, _)) => Ok(text(*name)),
|
||||
None => Err(HostError::Error("the tracing's options are damaged".into())),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn options_set_palette(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("TracingOptions.palette must be a string".into())) };
|
||||
let palette = PALETTES.iter().find(|(n, _)| n == name).map(|(_, p)| *p).ok_or_else(|| invalid("palette"))?;
|
||||
write_option(h, a, "palette", json!(palette))
|
||||
}
|
||||
|
||||
/// The view's `viewRaster` (`raster`) or `viewVector`.
|
||||
fn view_part(view: TraceView, raster: bool) -> Answer {
|
||||
let name = if raster { "viewRaster" } else { "viewVector" };
|
||||
VIEWS
|
||||
.iter()
|
||||
.find(|(v, ..)| *v == view)
|
||||
.map(|(_, r, v)| text(if raster { *r } else { *v }))
|
||||
.ok_or_else(|| HostError::Error(format!("TracingOptions.{name} has no value for the Split view")))
|
||||
}
|
||||
|
||||
fn options_view(h: &Host, a: &[Data], raster: bool) -> Answer {
|
||||
let (_, _, view, _) = options_of(h, a)?;
|
||||
view_part(view, raster)
|
||||
}
|
||||
|
||||
/// Shows the view `viewRaster` (`raster`) or `viewVector` makes with the other one as it is.
|
||||
fn options_set_view(h: &Host, a: &[Data], raster: bool) -> Answer {
|
||||
let (name, kind) = if raster { ("viewRaster", "ViewRasterType") } else { ("viewVector", "ViewVectorType") };
|
||||
let given = match arg(a, 1) {
|
||||
Data::String(s) if ENUMS.iter().any(|(e, members)| *e == kind && members.iter().any(|m| *s == format!("{kind}.{m}"))) => s.clone(),
|
||||
_ => return Err(HostError::Type(format!("TracingOptions.{name} must be a {kind} value"))),
|
||||
};
|
||||
let (item, _, view, _) = options_of(h, a)?;
|
||||
let Data::String(other) = view_part(view, !raster)? else { return Err(invalid(name)) };
|
||||
let pair = |r: &str, v: &str| if raster { given == r && other == v } else { other == r && given == v };
|
||||
let (to, ..) = VIEWS.iter().find(|(_, r, v)| pair(r, v)).ok_or_else(|| invalid(name))?;
|
||||
if *to != view {
|
||||
refuse_uneditable(h, item)?;
|
||||
edit_item(h, item, "imageTrace.setView", &json!({"ids": [item.id.0], "view": to.id()}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn options_view_raster(h: &Host, a: &[Data]) -> Answer {
|
||||
options_view(h, a, true)
|
||||
}
|
||||
|
||||
fn options_set_view_raster(h: &Host, a: &[Data]) -> Answer {
|
||||
options_set_view(h, a, true)
|
||||
}
|
||||
|
||||
fn options_view_vector(h: &Host, a: &[Data]) -> Answer {
|
||||
options_view(h, a, false)
|
||||
}
|
||||
|
||||
fn options_set_view_vector(h: &Host, a: &[Data]) -> Answer {
|
||||
options_set_view(h, a, false)
|
||||
}
|
||||
|
||||
fn options_preset(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, _, preset) = options_of(h, a)?;
|
||||
Ok(text(preset))
|
||||
}
|
||||
|
||||
fn options_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, handle) = tracing_of(h, arg(a, 0), "TracingOptions")?;
|
||||
Ok(host_ref("TracingObject", &handle))
|
||||
}
|
||||
|
||||
/// A preset name given to `method`: a string of at most [`MAX_PRESET_NAME`] bytes without `/`,
|
||||
/// `\`, `:` or control characters, trimmed.
|
||||
fn preset_name<'a>(d: &'a Data, method: &str) -> Result<&'a str, HostError> {
|
||||
let Data::String(name) = d else { return Err(HostError::Type(format!("TracingOptions.{method} needs a preset name, as a string"))) };
|
||||
if name.len() > MAX_PRESET_NAME {
|
||||
return Err(HostError::Range(format!("TracingOptions.{method}: a preset name has at most {MAX_PRESET_NAME} bytes")));
|
||||
}
|
||||
if name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) {
|
||||
return Err(HostError::Error(format!("TracingOptions.{method}: a preset name cannot hold / \\ : or control characters")));
|
||||
}
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err(HostError::Error(format!("TracingOptions.{method}: the preset name is empty")));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// `loadFromPreset(name)`: traces again with the built-in or saved preset `name` → `true`.
|
||||
fn options_load(h: &Host, a: &[Data]) -> Answer {
|
||||
let name = preset_name(arg(a, 1), "loadFromPreset")?;
|
||||
let (item, params, _, preset) = options_of(h, a)?;
|
||||
let wanted = vectorcraft_trace::preset(name).or_else(|| h.session.borrow().trace_preset(name).map(|q| q.params.clone()));
|
||||
let wanted = wanted.ok_or_else(|| HostError::Error("TracingOptions.loadFromPreset: no built-in or saved preset has that name".into()))?;
|
||||
let same = serde_json::to_value(&wanted).ok().as_ref().and_then(Value::as_object) == Some(¶ms);
|
||||
if !(same && preset.eq_ignore_ascii_case(name)) {
|
||||
let mut p = Map::new();
|
||||
p.insert("preset".into(), json!(name));
|
||||
retrace(h, item, p)?;
|
||||
}
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `storeToPreset(name)`: `false` for a built-in preset or `Custom`; any other name runs
|
||||
/// `imageTrace.presets.save`, which a script cannot run.
|
||||
fn options_store(h: &Host, a: &[Data]) -> Answer {
|
||||
let name = preset_name(arg(a, 1), "storeToPreset")?;
|
||||
let (_, params, ..) = options_of(h, a)?;
|
||||
if vectorcraft_trace::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") {
|
||||
return Ok(Data::Bool(false));
|
||||
}
|
||||
command(h, "imageTrace.presets.save", &json!({"name": name, "params": params}))?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// A member of `TracingOptions` with no VectorCraft setting: reading and assigning it both throw,
|
||||
/// after the check that the tracing `this` names is still there, and `reflect` and
|
||||
/// `hasOwnProperty` leave it out.
|
||||
fn missing(link: &Link, name: &'static str) -> Described {
|
||||
let message = not_implemented("TracingOptions", name);
|
||||
let l = link.clone();
|
||||
let f: vectorcraft_js::HostFunction = std::rc::Rc::new(move |a: Vec<Data>| {
|
||||
let h = super::current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
tracing_of(&h, arg(&a, 0), "TracingOptions")?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`.
|
||||
pub(super) fn add_trace(classes: &mut [HostClass], l: &Link) {
|
||||
for c in classes.iter_mut() {
|
||||
let f: super::Member = match c.name.as_str() {
|
||||
"PlacedItem" => placed_trace,
|
||||
"RasterItem" => raster_trace,
|
||||
_ => continue,
|
||||
};
|
||||
c.members.push(("trace".into(), method(l, f)));
|
||||
c.info.push(("trace".into(), returns("PluginItem", &[])));
|
||||
}
|
||||
}
|
||||
|
||||
/// `PluginItem`, after `PageItem`, `TracingObject` and `TracingOptions`.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let plugin = named(vec![("isTracing", get(l, plugin_is_tracing), typed("boolean")), ("tracing", get(l, plugin_tracing), typed("TracingObject"))]);
|
||||
let tracing = named(vec![
|
||||
("typename", typename_of("TracingObject"), typed("string")),
|
||||
("anchorCount", get(l, tracing_anchors), typed("number")),
|
||||
("areaCount", HostMember::Unavailable(super::function(l, tracing_areas)), MemberInfo { unavailable: true, ..MemberInfo::default() }),
|
||||
("imageResolution", get(l, tracing_resolution), typed("number")),
|
||||
("parent", get(l, tracing_parent), typed("PluginItem")),
|
||||
("pathCount", get(l, tracing_paths), typed("number")),
|
||||
("sourceArt", get(l, tracing_source), typed("PageItem")),
|
||||
("tracingOptions", get(l, tracing_options), typed("TracingOptions")),
|
||||
("usedColorCount", get(l, tracing_colors), typed("number")),
|
||||
("expandTracing", method(l, tracing_expand), returns("GroupItem", &[("viewed", "boolean")])),
|
||||
("releaseTracing", method(l, tracing_release), returns("PageItem", &[])),
|
||||
]);
|
||||
let mut options = named(vec![
|
||||
("typename", typename_of("TracingOptions"), typed("string")),
|
||||
("parent", get(l, options_parent), typed("TracingObject")),
|
||||
("preset", get(l, options_preset), typed("string")),
|
||||
("tracingMode", property(l, options_mode, options_set_mode), typed("TracingModeType")),
|
||||
("threshold", property(l, options_threshold, options_set_threshold), MemberInfo { min: Some(0.0), max: Some(255.0), ..typed("number") }),
|
||||
("fills", property(l, options_fills, options_set_fills), typed("boolean")),
|
||||
("strokes", property(l, options_strokes, options_set_strokes), typed("boolean")),
|
||||
("maxColors", property(l, options_max_colors, options_set_max_colors), MemberInfo { min: Some(2.0), max: Some(256.0), ..typed("number") }),
|
||||
("palette", property(l, options_palette, options_set_palette), typed("string")),
|
||||
("ignoreWhite", property(l, options_ignore_white, options_set_ignore_white), typed("boolean")),
|
||||
("minArea", property(l, options_min_area, options_set_min_area), typed("number")),
|
||||
("viewRaster", property(l, options_view_raster, options_set_view_raster), typed("ViewRasterType")),
|
||||
("viewVector", property(l, options_view_vector, options_set_view_vector), typed("ViewVectorType")),
|
||||
("loadFromPreset", method(l, options_load), returns("boolean", &[("presetName", "string")])),
|
||||
("storeToPreset", method(l, options_store), returns("boolean", &[("presetName", "string")])),
|
||||
]);
|
||||
options.extend(NOT_IMPLEMENTED.iter().map(|m| missing(l, m)));
|
||||
vec![
|
||||
class("PluginItem", Some("PageItem"), plugin, None),
|
||||
class("TracingObject", None, tracing, None),
|
||||
class("TracingOptions", None, options, None),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//! The transform methods of a page item, `translate`, `rotate`, `resize` and `transform`, as the
|
||||
//! help page <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> describes them. Each one
|
||||
//! runs `object.transform` on the object, with its selection kept, so it joins the run's one undo
|
||||
//! step for the document; a call that changes nothing runs no command. `PathItem` uses these
|
||||
//! methods too.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help page does not state:
|
||||
//! - Offsets, angles and matrices are taken with Y up, as `Matrix` records are, whatever
|
||||
//! `app.coordinateSystem` is: `translate(0, 10)` moves the object up, and a positive angle turns
|
||||
//! it counterclockwise.
|
||||
//! - `rotate`, `resize` and `transform` act about the center of the object's geometric bounds,
|
||||
//! unless a `Transformation` value names another point of those bounds; `DOCUMENTORIGIN` is the
|
||||
//! bottom-left corner of the first artboard. A matrix's own translation is added after it acts
|
||||
//! about that point. The value is checked even when the call changes nothing.
|
||||
//! - Positions, pattern fills and pattern strokes, and gradients each follow their argument:
|
||||
//! positions and gradients default to `true`, and patterns to the Transform Pattern Tiles
|
||||
//! preference. Fill and stroke patterns transform together, and gradients with the object, so a
|
||||
//! call whose values differ, counting the defaults of the arguments it leaves out, throws an error
|
||||
//! that says so.
|
||||
//! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own
|
||||
//! scale in percent, the square root of the area it scales by (stroke weights and effects scale
|
||||
//! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to
|
||||
//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any
|
||||
//! other value, and a scale of strokes and effects with positions left as they are, throws an
|
||||
//! error that says so.
|
||||
//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a
|
||||
//! locked object, and an object on a locked artboard are refused with nothing changed, and so are
|
||||
//! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object
|
||||
//! past the canvas.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_js::{Data, HostError};
|
||||
|
||||
use super::matrix::{self, Matrix};
|
||||
use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc};
|
||||
|
||||
/// The error for an object on a locked artboard.
|
||||
const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard";
|
||||
|
||||
/// The error for a locked object.
|
||||
const LOCKED: &str = "cannot transform locked objects";
|
||||
|
||||
/// The error for a hidden object.
|
||||
const HIDDEN: &str = "cannot transform hidden objects";
|
||||
|
||||
/// The identity matrix.
|
||||
const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
|
||||
/// What a transform method changes besides the object's geometry.
|
||||
struct Options {
|
||||
/// Positions and orientations (`changePositions`, `transformObjects`).
|
||||
objects: bool,
|
||||
/// Pattern fills and strokes.
|
||||
patterns: bool,
|
||||
/// Stroke weights and effects (`changeLineWidths`).
|
||||
strokes: bool,
|
||||
}
|
||||
|
||||
/// An optional `true` or `false` argument.
|
||||
fn flag(d: &Data, what: &str) -> std::result::Result<Option<bool>, HostError> {
|
||||
match d {
|
||||
Data::Undefined => Ok(None),
|
||||
Data::Bool(b) => Ok(Some(*b)),
|
||||
_ => Err(HostError::Type(format!("{what} must be true or false"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The positions, fill patterns, fill gradients and stroke patterns arguments at `at` and after,
|
||||
/// with the names the method gives them.
|
||||
fn options(h: &Host, a: &[Data], at: usize, names: [&str; 4]) -> std::result::Result<Options, HostError> {
|
||||
let tiles = h.session.borrow().prefs.transform_pattern_tiles;
|
||||
let objects = flag(arg(a, at), names[0])?.unwrap_or(true);
|
||||
let fill = flag(arg(a, at + 1), names[1])?.unwrap_or(tiles);
|
||||
let gradients = flag(arg(a, at + 2), names[2])?.unwrap_or(true);
|
||||
let stroke = flag(arg(a, at + 3), names[3])?.unwrap_or(tiles);
|
||||
if fill != stroke {
|
||||
return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3])));
|
||||
}
|
||||
if gradients != objects {
|
||||
return Err(HostError::Error(format!("{} different from {} is not available yet", names[2], names[0])));
|
||||
}
|
||||
Ok(Options { objects, patterns: fill, strokes: false })
|
||||
}
|
||||
|
||||
/// Whether `changeLineWidths` (`d`) is the scale of the linear part `m` of a matrix, so stroke
|
||||
/// weights and effects scale with it (`Some(true)`), or 100 (`Some(false)`); `None` for any other
|
||||
/// number.
|
||||
fn own_line_widths(d: &Data, m: Matrix) -> std::result::Result<(Option<bool>, f64, f64), HostError> {
|
||||
let lw = match d {
|
||||
Data::Undefined => return Ok((Some(false), 100.0, 100.0)),
|
||||
d => number(d, "changeLineWidths")?,
|
||||
};
|
||||
if lw < 0.0 {
|
||||
return Err(HostError::Range("changeLineWidths must not be negative".into()));
|
||||
}
|
||||
// The determinant is taken past the range of a number, so a scale whose square is too large
|
||||
// for one still has its own value.
|
||||
// 100 keeps the stroke weights, even for a scale within the tolerance of it.
|
||||
let own = matrix::area_scale(m) * 100.0;
|
||||
if (lw - 100.0).abs() <= 1e-9 {
|
||||
return Ok((Some(false), lw, own));
|
||||
}
|
||||
if lw > 0.0 && own.is_finite() && (lw - own).abs() <= 1e-9 * own {
|
||||
return Ok((Some((own - 100.0).abs() > 1e-9), lw, own));
|
||||
}
|
||||
Ok((None, lw, own))
|
||||
}
|
||||
|
||||
/// The error for a `changeLineWidths` the method does not take.
|
||||
fn other_line_widths(own: f64) -> HostError {
|
||||
HostError::Error(format!("changeLineWidths other than 100 or the scale itself ({own}) is not available yet"))
|
||||
}
|
||||
|
||||
/// Whether `changeLineWidths` (`d`) scales stroke weights for the linear part `m` of a matrix.
|
||||
fn line_widths(d: &Data, m: Matrix) -> std::result::Result<bool, HostError> {
|
||||
match own_line_widths(d, m)? {
|
||||
(Some(strokes), _, _) => Ok(strokes),
|
||||
(None, _, own) => Err(other_line_widths(own)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The member of `Transformation` that `d` names (left out: `CENTER`).
|
||||
fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> {
|
||||
const MEMBERS: [&str; 10] = ["CENTER", "TOPLEFT", "TOP", "TOPRIGHT", "LEFT", "RIGHT", "BOTTOMLEFT", "BOTTOM", "BOTTOMRIGHT", "DOCUMENTORIGIN"];
|
||||
let name = match d {
|
||||
Data::Undefined => "CENTER",
|
||||
Data::String(s) => s.strip_prefix("Transformation.").unwrap_or(""),
|
||||
_ => "",
|
||||
};
|
||||
if MEMBERS.contains(&name) { Ok(name) } else { Err(HostError::Type("the point to transform about must be a Transformation value".into())) }
|
||||
}
|
||||
|
||||
/// The point of `r` (document coordinates, Y down) that the `Transformation` member `name`
|
||||
/// ([`anchor_name`]) names.
|
||||
fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result<Point, HostError> {
|
||||
let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
|
||||
Ok(match name {
|
||||
"TOPLEFT" => Point::new(r.x0, r.y0),
|
||||
"TOP" => Point::new(cx, r.y0),
|
||||
"TOPRIGHT" => Point::new(r.x1, r.y0),
|
||||
"LEFT" => Point::new(r.x0, cy),
|
||||
"RIGHT" => Point::new(r.x1, cy),
|
||||
"BOTTOMLEFT" => Point::new(r.x0, r.y1),
|
||||
"BOTTOM" => Point::new(cx, r.y1),
|
||||
"BOTTOMRIGHT" => Point::new(r.x1, r.y1),
|
||||
"DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?,
|
||||
_ => Point::new(cx, cy),
|
||||
})
|
||||
}
|
||||
|
||||
/// The matrix `m` (Y up) as it acts on the page (Y down), about `o`.
|
||||
fn on_page(m: Matrix, o: Point) -> Affine {
|
||||
let [a, b, c, d, tx, ty] = m;
|
||||
let (b, c, ty) = (0.0 - b, 0.0 - c, 0.0 - ty);
|
||||
if [a, b, c, d] == [1.0, 0.0, 0.0, 1.0] {
|
||||
return Affine::translate((tx, ty));
|
||||
}
|
||||
Affine::translate((o.x + tx, o.y + ty)) * Affine::new([a, b, c, d, 0.0, 0.0]) * Affine::translate((-o.x, -o.y))
|
||||
}
|
||||
|
||||
/// Whether the object `id` of `d` stays within the canvas under `xf` (page coordinates), symbol
|
||||
/// instances measured by their art as [`vectorcraft_doc::Document::bounds_of`] measures them. The
|
||||
/// object is measured whole, and a group is looked into object by object, as the native file's
|
||||
/// canvas check does (`vectorcraft_doc::canvas_range`), since a clipping group's bounds are its
|
||||
/// clipping path's and leave out the art it clips.
|
||||
fn fits(d: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId, xf: Affine) -> bool {
|
||||
fn within(n: &vectorcraft_doc::Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. } | vectorcraft_doc::NodeKind::Layer { .. }) {
|
||||
n.children().into_iter().flatten().all(|c| within(c, symbols))
|
||||
} else {
|
||||
n.geometric_bounds_with(symbols).is_none_or(crate::sanity::rect_in_range)
|
||||
}
|
||||
}
|
||||
d.node(id).is_some_and(|n| {
|
||||
let mut n = n.clone();
|
||||
n.transform(xf, false);
|
||||
within(&n, &d.symbol_boxes())
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies `m` (Y up) to `item`, about the point `about` names (`None`: the matrix acts as a move,
|
||||
/// which needs no point), with `opts`, then sets the stroke weight of a path to `weight` points
|
||||
/// when it is given.
|
||||
fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, weight: Option<f64>) -> Answer {
|
||||
let about = about.map(anchor_name).transpose()?;
|
||||
if m.iter().any(|v| !v.is_finite()) {
|
||||
return Err(HostError::Range("the transformation has a value too large for a number".into()));
|
||||
}
|
||||
if matrix::singular(m) {
|
||||
return Err(HostError::Error("the transformation is singular and would flatten the object".into()));
|
||||
}
|
||||
let (locked, hidden, on_locked, bounds, uses_pattern, clipped) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let line = d.ancestry(item.id);
|
||||
let mut locked = line.as_ref().is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked)));
|
||||
let hidden = line.as_ref().is_none_or(|a| a.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(|n| !n.visible)));
|
||||
let (mut uses, mut clipped) = (false, false);
|
||||
if let Some(n) = d.node(item.id) {
|
||||
n.walk(&mut |c| {
|
||||
locked |= c.locked;
|
||||
uses |= vectorcraft_doc::pattern::uses_pattern(c, None);
|
||||
clipped |=
|
||||
matches!(c.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. } | vectorcraft_doc::NodeKind::Layer { clip: true, .. });
|
||||
});
|
||||
}
|
||||
(locked, hidden, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses, clipped)
|
||||
});
|
||||
if locked {
|
||||
return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0)));
|
||||
}
|
||||
if hidden {
|
||||
return Err(HostError::Error(format!("{HIDDEN}: {}", item.id.0)));
|
||||
}
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
// The identity acts the same about every point, so an object without bounds (an empty path)
|
||||
// takes it too.
|
||||
let o = match (about, bounds) {
|
||||
_ if m == IDENTITY => Point::ORIGIN,
|
||||
(Some(name), Some(r)) => anchor(h, item, r, name)?,
|
||||
(Some(_), None) => return Err(HostError::Error("the object has no bounds".into())),
|
||||
(None, _) => Point::ORIGIN,
|
||||
};
|
||||
let xf = on_page(m, o);
|
||||
if opts.strokes && !opts.objects {
|
||||
return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into()));
|
||||
}
|
||||
if opts.objects && xf != Affine::IDENTITY {
|
||||
// The transformed corners of the bounds hold the transformed object. When one of them is
|
||||
// past the canvas, or the object holds a clipping group (whose bounds leave out the art
|
||||
// it clips), the transformed object itself is measured.
|
||||
let inside = |p: Point| p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD;
|
||||
let outside = bounds.is_some_and(|r| {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)];
|
||||
!corners.iter().all(|p| inside(xf * *p))
|
||||
});
|
||||
if (clipped || outside) && !with_doc(h, item.doc, |_, st| fits(&st.doc, item.id, xf)) {
|
||||
return Err(HostError::Range("the transformation would take the object past the canvas".into()));
|
||||
}
|
||||
}
|
||||
let c = xf.as_coeffs();
|
||||
let identity = xf == Affine::IDENTITY;
|
||||
let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity };
|
||||
// The transformation and the stroke weight change together or not at all.
|
||||
atomically(h, |h| {
|
||||
if changes {
|
||||
let p = json!({"ids": [item.id.0], "matrix": c, "objects": opts.objects, "patterns": opts.patterns, "strokes": opts.strokes});
|
||||
edit_item(h, item, "object.transform", &p)?;
|
||||
}
|
||||
if let Some(w) = weight {
|
||||
paths::set_stroke_weight(h, item, w)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
}
|
||||
|
||||
/// `translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?,
|
||||
/// transformStrokePatterns?)`: moves the object by `deltaX` and `deltaY` points (0 when left out).
|
||||
pub(super) fn translate(h: &Host, a: &[Data]) -> Answer {
|
||||
let delta = |i: usize, what: &str| match arg(a, i) {
|
||||
Data::Undefined => Ok(0.0),
|
||||
d => number(d, what),
|
||||
};
|
||||
let (dx, dy) = (delta(1, "deltaX")?, delta(2, "deltaY")?);
|
||||
let names = ["transformObjects", "transformFillPatterns", "transformFillGradients", "transformStrokePatterns"];
|
||||
let opts = options(h, a, 3, names)?;
|
||||
let item = this_item(h, a)?;
|
||||
// An offset past the canvas is refused only when the call moves the object or a pattern it
|
||||
// uses.
|
||||
let limit = coordinate(&Data::Number(dx), "deltaX").and_then(|_| coordinate(&Data::Number(dy), "deltaY"));
|
||||
if let Err(e) = limit {
|
||||
let moves = opts.objects
|
||||
|| opts.patterns
|
||||
&& with_doc(h, item.doc, |_, st| {
|
||||
st.doc.node(item.id).is_some_and(|n| {
|
||||
let mut uses = false;
|
||||
n.walk(&mut |c| uses |= vectorcraft_doc::pattern::uses_pattern(c, None));
|
||||
uses
|
||||
})
|
||||
});
|
||||
if moves {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
apply(h, item, matrix::translate(dx, dy), None, &opts, None)
|
||||
}
|
||||
|
||||
const CHANGE_NAMES: [&str; 4] = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"];
|
||||
|
||||
/// `rotate(angle, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?,
|
||||
/// rotateAbout?)`: turns the object by `angle` degrees, counterclockwise when it is positive.
|
||||
pub(super) fn rotate(h: &Host, a: &[Data]) -> Answer {
|
||||
let angle = number(arg(a, 1), "angle")?;
|
||||
let opts = options(h, a, 2, CHANGE_NAMES)?;
|
||||
apply(h, this_item(h, a)?, matrix::rotate(angle), Some(arg(a, 6)), &opts, None)
|
||||
}
|
||||
|
||||
/// `resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?,
|
||||
/// changeStrokePattern?, changeLineWidths?, scaleAbout?)`: scales the object by `scaleX` and
|
||||
/// `scaleY` percent along the page's axes.
|
||||
pub(super) fn resize(h: &Host, a: &[Data]) -> Answer {
|
||||
let (sx, sy) = (number(arg(a, 1), "scaleX")?, number(arg(a, 2), "scaleY")?);
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err(HostError::Range("scaleX and scaleY must not be 0".into()));
|
||||
}
|
||||
let m = matrix::scaled(sx, sy);
|
||||
let mut opts = options(h, a, 3, CHANGE_NAMES)?;
|
||||
let item = this_item(h, a)?;
|
||||
let weight = match own_line_widths(arg(a, 7), m)? {
|
||||
// The compound holds a member's visible stroke, so its weight is set through the compound
|
||||
// as well as the member's own strokes and effects scaling, by the scale itself.
|
||||
(Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => {
|
||||
opts.strokes = true;
|
||||
paths::resized_stroke_weight(h, item, own, false)?
|
||||
}
|
||||
(Some(strokes), _, _) => {
|
||||
opts.strokes = strokes;
|
||||
None
|
||||
}
|
||||
(None, lw, _) if paths::is_path(h, item) => paths::resized_stroke_weight(h, item, lw, true)?,
|
||||
(None, _, own) => return Err(other_line_widths(own)),
|
||||
};
|
||||
apply(h, item, m, Some(arg(a, 8)), &opts, weight)
|
||||
}
|
||||
|
||||
/// `transform(transformationMatrix, changePositions?, changeFillPatterns?, changeFillGradients?,
|
||||
/// changeStrokePattern?, changeLineWidths?, transformAbout?)`: applies a `Matrix` record to the
|
||||
/// object.
|
||||
pub(super) fn transform(h: &Host, a: &[Data]) -> Answer {
|
||||
let m = matrix::matrix(arg(a, 1), "transformationMatrix")?;
|
||||
let mut opts = options(h, a, 2, CHANGE_NAMES)?;
|
||||
let item = this_item(h, a)?;
|
||||
let weight = match own_line_widths(arg(a, 6), m)? {
|
||||
// As in `resize`: the compound holds a member's visible stroke, so its weight is set
|
||||
// through the compound as well.
|
||||
(Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => {
|
||||
opts.strokes = true;
|
||||
paths::resized_stroke_weight(h, item, own, false)?
|
||||
}
|
||||
_ => {
|
||||
opts.strokes = line_widths(arg(a, 6), m)?;
|
||||
None
|
||||
}
|
||||
};
|
||||
apply(h, item, m, Some(arg(a, 7)), &opts, weight)
|
||||
}
|
||||
@@ -238,9 +238,10 @@ pub(crate) struct Files {
|
||||
entry_key: Option<String>,
|
||||
}
|
||||
|
||||
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
|
||||
/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text
|
||||
/// run as ECMAScript 5.1 with the ExtendScript extensions.
|
||||
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] and
|
||||
/// [`vectorcraft_js::Options::es2017`] when its file name ends in `.js` or `.mjs` (in any letter
|
||||
/// case); a `.jsx` script, any other file and a script given as text run as ECMAScript 5.1 with
|
||||
/// the ExtendScript extensions.
|
||||
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs"))
|
||||
}
|
||||
@@ -496,7 +497,7 @@ impl Files {
|
||||
|
||||
/// The options a file of this run is parsed with, preprocessor lines aside.
|
||||
pub(crate) fn options(&self) -> Options {
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, es2017: self.es2015, e4x: true, ..Options::default() }
|
||||
}
|
||||
|
||||
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
|
||||
|
||||
@@ -482,6 +482,7 @@ struct World {
|
||||
draw_mode: DrawMode,
|
||||
draw_inside: Option<NodeId>,
|
||||
clipboard: Clipboard,
|
||||
clipboard_copied: bool,
|
||||
untitled_counter: u32,
|
||||
menu: cmd::menucmds::MenuState,
|
||||
last_solid: crate::Color,
|
||||
@@ -563,19 +564,35 @@ impl Choices {
|
||||
}
|
||||
|
||||
/// The preferences after a run: `current`, the session's, which the app may have changed while the
|
||||
/// run went on, with each preference the run changed from `start` set to the run's value.
|
||||
/// run went on, with each preference the run changed from `start` set to the run's value. A
|
||||
/// preference the run emptied, which is then left out of the saved form, is left out of the result.
|
||||
/// The values scripts store with `app.preferences` are merged the same way one key at a time.
|
||||
fn merged_prefs(start: &crate::Prefs, run: &crate::Prefs, current: &crate::Prefs) -> crate::Prefs {
|
||||
let (Ok(Value::Object(start)), Ok(Value::Object(run)), Ok(Value::Object(mut out))) =
|
||||
const SCRIPT_KEYS: &str = "scriptPreferences";
|
||||
let (Ok(Value::Object(start_json)), Ok(Value::Object(run_json)), Ok(Value::Object(mut out))) =
|
||||
(serde_json::to_value(start), serde_json::to_value(run), serde_json::to_value(current))
|
||||
else {
|
||||
return current.clone();
|
||||
};
|
||||
for (key, value) in run {
|
||||
if start.get(&key) != Some(&value) {
|
||||
for key in start_json.keys().filter(|k| *k != SCRIPT_KEYS && !run_json.contains_key(*k)) {
|
||||
out.remove(key);
|
||||
}
|
||||
for (key, value) in run_json {
|
||||
if key != SCRIPT_KEYS && start_json.get(&key) != Some(&value) {
|
||||
out.insert(key, value);
|
||||
}
|
||||
}
|
||||
serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone())
|
||||
let mut merged: crate::Prefs = serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone());
|
||||
let script = &mut merged.script_preferences;
|
||||
for key in start.script_preferences.keys().filter(|k| !run.script_preferences.contains_key(*k)) {
|
||||
script.remove(key);
|
||||
}
|
||||
for (key, value) in &run.script_preferences {
|
||||
if start.script_preferences.get(key) != Some(value) {
|
||||
script.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
impl World {
|
||||
@@ -595,6 +612,7 @@ impl World {
|
||||
draw_mode: s.draw_mode,
|
||||
draw_inside: s.draw_inside,
|
||||
clipboard: s.clipboard.clone(),
|
||||
clipboard_copied: s.clipboard_copied,
|
||||
untitled_counter: s.untitled_counter,
|
||||
menu: s.menu.clone(),
|
||||
last_solid: s.last_solid,
|
||||
@@ -618,6 +636,7 @@ impl World {
|
||||
swap(&mut self.draw_mode, &mut s.draw_mode);
|
||||
swap(&mut self.draw_inside, &mut s.draw_inside);
|
||||
swap(&mut self.clipboard, &mut s.clipboard);
|
||||
swap(&mut self.clipboard_copied, &mut s.clipboard_copied);
|
||||
swap(&mut self.untitled_counter, &mut s.untitled_counter);
|
||||
swap(&mut self.menu, &mut s.menu);
|
||||
swap(&mut self.last_solid, &mut s.last_solid);
|
||||
@@ -629,9 +648,11 @@ impl World {
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands that can change the clipboard and still fail, and that do not put it back
|
||||
/// themselves. The clipboard can hold a great deal, so a savepoint copies it only for these.
|
||||
const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "edit.cut"];
|
||||
/// The commands that can change the clipboard and still fail, or still be put back because their
|
||||
/// result cannot reach the script, and that do not put it back themselves. The clipboard can hold
|
||||
/// a great deal, so a savepoint copies it only for these.
|
||||
const CAN_FAIL_AFTER_COPYING: &[&str] =
|
||||
&["action.batch", "artboard.copy", "artboard.cut", "clipboard.importSvg", "command.batch", "edit.copy", "edit.cut"];
|
||||
|
||||
/// The commands that remove a document's undo history, or the document: a savepoint keeps a whole
|
||||
/// copy of the histories for these. Any other command that removes or changes a step under the
|
||||
@@ -655,7 +676,8 @@ pub(crate) struct Savepoint {
|
||||
fill_active: bool,
|
||||
draw_mode: DrawMode,
|
||||
draw_inside: Option<NodeId>,
|
||||
clipboard: Option<Clipboard>,
|
||||
/// The clipboard, [`Session::clipboard_copied`] and [`Session::copies`].
|
||||
clipboard: Option<(Clipboard, bool, u64)>,
|
||||
untitled_counter: u32,
|
||||
menu: cmd::menucmds::MenuState,
|
||||
last_solid: crate::Color,
|
||||
@@ -691,7 +713,7 @@ impl Savepoint {
|
||||
fill_active: s.fill_active,
|
||||
draw_mode: s.draw_mode,
|
||||
draw_inside: s.draw_inside,
|
||||
clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| s.clipboard.clone()),
|
||||
clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| (s.clipboard.clone(), s.clipboard_copied, s.copies)),
|
||||
untitled_counter: s.untitled_counter,
|
||||
menu: s.menu.clone(),
|
||||
last_solid: s.last_solid,
|
||||
@@ -742,8 +764,10 @@ impl Savepoint {
|
||||
s.fill_active = self.fill_active;
|
||||
s.draw_mode = self.draw_mode;
|
||||
s.draw_inside = self.draw_inside;
|
||||
if let Some(clipboard) = self.clipboard {
|
||||
if let Some((clipboard, copied, copies)) = self.clipboard {
|
||||
s.clipboard = clipboard;
|
||||
s.clipboard_copied = copied;
|
||||
s.copies = copies;
|
||||
}
|
||||
s.untitled_counter = self.untitled_counter;
|
||||
s.menu = self.menu;
|
||||
@@ -781,6 +805,9 @@ struct Host {
|
||||
log: RefCell<Vec<Value>>,
|
||||
log_bytes: Cell<usize>,
|
||||
written: RefCell<Written>,
|
||||
/// A command ran a Copy or Cut ([`Session::copies`]), also inside a batch or an action, and
|
||||
/// the run kept it.
|
||||
copied: Cell<bool>,
|
||||
/// The run's number in its session, and the script's name, which its console lines carry.
|
||||
run: u64,
|
||||
name: Arc<str>,
|
||||
@@ -1337,8 +1364,9 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
raise_ids(s);
|
||||
s.script_style_trail = StyleTrail::start(s);
|
||||
let mutating = waits_for_tool_edit(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));
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. A
|
||||
// query that fills the clipboard (`clipboard.importSvg`) takes one too, for the clipboard.
|
||||
let save = ((mutating || CAN_FAIL_AFTER_COPYING.contains(&id)) && !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();
|
||||
@@ -1436,9 +1464,9 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
|
||||
let session = host.session.clone();
|
||||
let started = clock();
|
||||
let before = dom::before_command(host, id);
|
||||
let r = {
|
||||
let (copies, r) = {
|
||||
let mut s = session.borrow_mut();
|
||||
step(&mut s, host, id, params)
|
||||
(s.copies, step(&mut s, host, id, params))
|
||||
};
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(id)) {
|
||||
@@ -1469,14 +1497,19 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
|
||||
if crossed.is_err() {
|
||||
host.put_growth_back(mark);
|
||||
}
|
||||
let mut s = session.borrow_mut();
|
||||
if let Some(save) = save {
|
||||
let mut s = session.borrow_mut();
|
||||
if crossed.is_ok() {
|
||||
save.keep(&mut s);
|
||||
} else if !save.restore(&mut s) {
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
// A Copy or Cut counts for the run only once what it put on the clipboard is kept.
|
||||
if s.copies != copies {
|
||||
host.copied.set(true);
|
||||
}
|
||||
drop(s);
|
||||
dom::after_command(host, before);
|
||||
// Style objects follow only a command that is kept.
|
||||
if crossed.is_ok() {
|
||||
@@ -2082,12 +2115,28 @@ impl Session {
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting())).flatten()
|
||||
}
|
||||
|
||||
/// Whether [`Session::script_dialog`] is the confirm the app opened to turn off the external
|
||||
/// script warning, which only a person answers Yes to. A script's own confirm with the same
|
||||
/// text is not.
|
||||
pub fn script_dialog_turns_warning_off(&self) -> bool {
|
||||
self.script_dialog().is_some() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.asks_warning_off())).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Gives the dialog the running script waits at its answer; the next [`Session::script_pump`]
|
||||
/// goes on from the call. → false when nothing waits, the answer is for another kind of
|
||||
/// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`].
|
||||
/// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`]. Yes to a confirm the
|
||||
/// app opened for the script ([`dialogs::Dialogs::ask`]) also does what it asked.
|
||||
pub fn script_answer(&mut self, answer: DialogAnswer) -> bool {
|
||||
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false };
|
||||
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
|
||||
with_job(k, |j| {
|
||||
let given = j.host.dialogs.answer(&mut j.realm, answer);
|
||||
// Between slices the run's preferences are in its working copy.
|
||||
if let Some(dialogs::OnYes::ExternalScriptWarningOff) = j.host.dialogs.take_approved() {
|
||||
j.world.choices.prefs.show_external_script_warning = false;
|
||||
}
|
||||
given
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run
|
||||
@@ -2299,13 +2348,16 @@ impl Session {
|
||||
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
|
||||
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
|
||||
let es2015 = request.module || include::es2015_script(request.file.as_deref());
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
|
||||
// It also reads async functions and `await` (ECMAScript 2017).
|
||||
let options =
|
||||
Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, es2017: es2015, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
// A kept engine reads each run's code the way that run's script does.
|
||||
let mut realm = match realm {
|
||||
Some(mut realm) => {
|
||||
realm.set_limits(limits);
|
||||
realm.set_es2015(es2015);
|
||||
realm.set_es2017(es2015);
|
||||
if es2015 {
|
||||
realm.add_es2015();
|
||||
}
|
||||
@@ -2342,6 +2394,7 @@ impl Session {
|
||||
log: RefCell::new(Vec::new()),
|
||||
log_bytes: Cell::new(0),
|
||||
written: RefCell::new(Written::default()),
|
||||
copied: Cell::new(false),
|
||||
run: self.script_runs,
|
||||
name: console::line_name(&name),
|
||||
console: RefCell::default(),
|
||||
@@ -2695,6 +2748,13 @@ impl Session {
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
// The run ran a Copy or Cut, and the clipboard still holds what one put there.
|
||||
if host.copied.get()
|
||||
&& self.clipboard_copied
|
||||
&& let Some(o) = report.as_object_mut()
|
||||
{
|
||||
o.insert("copied".into(), json!(true));
|
||||
}
|
||||
// The jobs it prepared for a printer wait for the frontend now that its changes are kept.
|
||||
let prints = host.dom.take_prints();
|
||||
if !prints.is_empty() {
|
||||
|
||||
@@ -54,6 +54,8 @@ impl Session {
|
||||
paint: PaintDefaults::default(),
|
||||
fill_active: true,
|
||||
clipboard: Clipboard::default(),
|
||||
copies: 0,
|
||||
clipboard_copied: false,
|
||||
journal: Journal::default(),
|
||||
history_budget: crate::default_history_budget(),
|
||||
histories_seen: None,
|
||||
|
||||
@@ -185,7 +185,11 @@ mod script_dialogs;
|
||||
mod script_dollar;
|
||||
mod script_dom;
|
||||
mod script_dom_defaults;
|
||||
mod script_dom_images;
|
||||
mod script_dom_paths;
|
||||
mod script_dom_prefs;
|
||||
mod script_dom_tracing;
|
||||
mod script_dom_transform;
|
||||
mod script_engines;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
|
||||
@@ -134,6 +134,58 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() {
|
||||
assert_eq!(out[4], json!([20, 250, 80, 210]));
|
||||
}
|
||||
|
||||
/// `controlBounds` takes in the Bézier handles of a path, which can reach past what it draws.
|
||||
#[test]
|
||||
fn page_item_control_bounds_take_in_the_handles() {
|
||||
let (mut s, _, _) = doc();
|
||||
let anchors = json!([{"x": 0, "y": 100, "out": [0, 0]}, {"x": 100, "y": 100, "in": [100, 0]}]);
|
||||
s.execute("path.create", &json!({"anchors": anchors})).unwrap();
|
||||
let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);");
|
||||
let b = |v: &Value| -> Vec<f64> { v.as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect() };
|
||||
let (visible, control) = (b(&out[0]), b(&out[1]));
|
||||
assert!(visible[1] < 290.0, "the curve stays well under its handles: {visible:?}");
|
||||
assert!((control[1] - 300.0).abs() < 1e-9, "the handles reach the top of the page: {control:?}");
|
||||
assert!(control[0] <= visible[0] && control[2] >= visible[2] && control[3] <= visible[3], "{visible:?} {control:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_bounds_include_handles_inside_live_containers() {
|
||||
for command in ["object.blend.make", "object.envelope.makeWithMesh", "object.repeat.grid", "object.intertwine.make"] {
|
||||
let (mut s, _, _) = doc();
|
||||
let path = s
|
||||
.execute("path.create", &json!({"anchors": [{"x": 200, "y": 0, "out": [200, -100]}, {"x": 300, "y": 0, "in": [300, -100]}]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let other = rect(&mut s, 210.0, 10.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [path, other.0]})).unwrap();
|
||||
let params = match command {
|
||||
"object.blend.make" => json!({"steps": 2}),
|
||||
"object.envelope.makeWithMesh" | "object.repeat.grid" => json!({"rows": 1, "cols": 1}),
|
||||
_ => json!({}),
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var p = app.activeDocument.selection[0];\
|
||||
vc.log(p.controlBounds[1] < p.visibleBounds[1]);",
|
||||
);
|
||||
assert_eq!(out, [json!(true)], "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_bounds_take_in_the_direction_points() {
|
||||
let (mut s, _, _) = doc();
|
||||
// An arch whose top is at y 40 and whose direction points are at y 20.
|
||||
let id = s.execute("path.create", &json!({"d": "M100 100C100 20 200 20 200 100"})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let out = log(&mut s, "var i = app.activeDocument.selection[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);");
|
||||
let top = |v: &Value| v[1].as_f64().unwrap_or(f64::NAN);
|
||||
assert!(top(&out[0]) < 265.0, "{out:?}");
|
||||
assert_eq!(top(&out[1]), 280.0, "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -724,6 +776,24 @@ fn control_bounds_take_in_direction_points_past_the_curve() {
|
||||
assert_eq!(out[2], out[3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_selection_assignment_leaves_the_selection_within_the_run() {
|
||||
let (mut s, _, b) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
|
||||
// The run goes on after the failed assignment, so nothing it ends with puts the selection back.
|
||||
let c = rect(&mut s, 200.0, 20.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems, open, shut;\
|
||||
for (var i = 0; i < p.length; i++) { if (p[i].locked) shut = p[i]; else if (!p[i].selected) open = p[i]; }\
|
||||
try { d.selection = [open, shut]; vc.log('assigned'); } catch (e) { vc.log(String(e.message).indexOf('Cannot select') >= 0); }\
|
||||
vc.log([d.selection.length, open.selected, d.selection[0].locked]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!([1, false, false])]);
|
||||
assert_eq!(s.active().unwrap().selection.objects, vec![c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guide_path_is_not_selected_while_guides_are_locked() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -1434,7 +1504,7 @@ fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_image_stays_the_same_object_when_it_is_embedded() {
|
||||
fn a_held_image_is_stale_when_it_is_embedded() {
|
||||
let dir = super::links::Folder::new("dom-embed");
|
||||
let photo = dir.file("photo.png");
|
||||
super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0]));
|
||||
@@ -1444,11 +1514,12 @@ fn a_held_image_stays_the_same_object_when_it_is_embedded() {
|
||||
&mut s,
|
||||
&format!(
|
||||
"var i = app.activeDocument.pageItems[0]; vc.log(i.typename); vc.run('links.embed', {{ids: [{}]}});\
|
||||
var j = app.activeDocument.pageItems[0]; vc.log([i === j, i.typename, i instanceof RasterItem, i instanceof PlacedItem]);",
|
||||
var j = app.activeDocument.pageItems[0], m = ''; try {{ i.typename; }} catch (e) {{ m = e.message; }}\
|
||||
vc.log([i === j, m, j.typename, j instanceof RasterItem, i instanceof PlacedItem]);",
|
||||
id.0
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!("PlacedItem"), json!([true, "RasterItem", true, false])]);
|
||||
assert_eq!(out, vec![json!("PlacedItem"), json!([false, "Stale page item", "RasterItem", true, true])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1488,7 +1559,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
|
||||
for source in [
|
||||
"app.activeDocument.pageItems[0].isIsolated;",
|
||||
"app.activeDocument.pageItems[0].uuid = 'x';",
|
||||
"app.activeDocument.pageItems[0].transform(5);",
|
||||
"app.activeDocument.pageItems[0].bringInPerspective(0, 0);",
|
||||
] {
|
||||
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
|
||||
}
|
||||
@@ -1744,6 +1815,46 @@ fn document_preset_applies_only_its_given_fields() {
|
||||
assert_eq!(s.documents().len(), 2, "settings the built-in preset refuses make no document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_startup_preset_uses_its_own_size_beside_a_saved_preset_of_the_same_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 300, "height": 200})).unwrap();
|
||||
let first = crate::cmd::newdoc::category(&s, "Print").unwrap().remove(0);
|
||||
assert_eq!(first.name, "Letter");
|
||||
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height]);");
|
||||
assert_eq!((out[0][0].as_f64(), out[0][1].as_f64()), (Some(first.width), Some(first.height)), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_presets_hold_a_limited_amount_of_data() {
|
||||
let mut s = Session::new();
|
||||
// A 4,096-byte title fits and replacing it does not add up; one byte more is refused.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset();\
|
||||
for (var k = 0; k < 20; k++) p.title = t; vc.log(p.title.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(4096)]);
|
||||
let e = failure(&mut s, "var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset(); p.title = t + 'x';");
|
||||
assert!(e.contains("the title is too long"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_art_on_another_layer_keeps_the_current_layer() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = s.active().unwrap().current_layer().unwrap();
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let b = s.active().unwrap().current_layer().unwrap();
|
||||
assert_ne!(a, b);
|
||||
rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.active_mut().unwrap().active_layer = Some(a);
|
||||
log(&mut s, "var i = app.activeDocument.pageItems[0]; i.left = i.left + 5; i.translate(5, 0);");
|
||||
assert_eq!(s.active().unwrap().current_layer(), Some(a));
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_add_document_dialog_fails_without_creating() {
|
||||
let mut s = Session::new();
|
||||
@@ -2165,6 +2276,37 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() {
|
||||
assert_eq!(out, vec![json!(0)]);
|
||||
}
|
||||
|
||||
/// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it
|
||||
/// is runs no command, also in a layer whose ruler guides are above its art.
|
||||
#[test]
|
||||
fn move_refuses_art_on_a_locked_artboard_and_skips_a_move_to_the_same_place() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
// The topmost art, moved to the top of its layer, stays where it is.
|
||||
log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems, top = p[0];\
|
||||
for (var i = 1; i < p.length; i++) { if (p[i].zOrderPosition > top.zOrderPosition) top = p[i]; }\
|
||||
top.move(top.parent);",
|
||||
);
|
||||
assert_eq!(undo_steps(&s), steps, "a move to the same place adds no step");
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let order = |s: &Session| format!("{:?}", (s.active().unwrap().doc.position(a), s.active().unwrap().doc.position(b)));
|
||||
let before = order(&s);
|
||||
let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATBEGINNING);");
|
||||
assert!(e.contains("Cannot move PathItem"), "{e}");
|
||||
let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1].parent, ElementPlacement.PLACEATEND);");
|
||||
assert!(e.contains("Cannot move PathItem"), "{e}");
|
||||
assert_eq!(order(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_frames_remove_all_refuses_type_on_a_locked_artboard() {
|
||||
let mut s = Session::new();
|
||||
@@ -2560,7 +2702,7 @@ fn page_items_report_their_available_members_as_their_own() {
|
||||
vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\
|
||||
Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\
|
||||
app.hasOwnProperty('activeDocument')]);\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('transform'), d.hasOwnProperty('layers'),\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('layers'),\
|
||||
p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\
|
||||
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);",
|
||||
);
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
//! Placed and raster items in the script object model: placing a file with `PlacedItems.add()`,
|
||||
//! relinking, embedding, the encoded image's header, and the file checks.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// A fresh folder for test `name`, with a `main` folder for the script and an `outside` folder the
|
||||
/// script may not read, by its real path.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-dom-images-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
std::fs::create_dir_all(base.join("outside")).unwrap();
|
||||
PathBuf::from(plain_path(&std::fs::canonicalize(&base).unwrap().to_string_lossy()))
|
||||
}
|
||||
|
||||
/// A `w`×`h` 8-bit gray PNG.
|
||||
fn gray_png(w: u32, h: u32) -> Vec<u8> {
|
||||
let raw = vec![128u8; (w * h) as usize];
|
||||
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap();
|
||||
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// The path as the inside of a single-quoted script string: JSON escapes backslashes, quotes,
|
||||
/// line breaks and control characters, and the apostrophe is escaped as well.
|
||||
fn js_path(p: &Path) -> String {
|
||||
let quoted = Value::String(plain_path(&p.to_string_lossy())).to_string();
|
||||
quoted[1..quoted.len() - 1].replace('\'', "\\'")
|
||||
}
|
||||
|
||||
fn plain_path(path: &str) -> String {
|
||||
if let Some(tail) = path.strip_prefix(r"\\?\UNC\") { format!(r"\\{tail}") } else { path.strip_prefix(r"\\?\").unwrap_or(path).to_string() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixture_paths_strip_verbatim_prefixes_on_every_platform() {
|
||||
let drive = format!("{}{}", r"\\?\", r"C:\x\a.png");
|
||||
let unc = format!("{}{}", r"\\?\UNC\", r"server\share\a.png");
|
||||
assert_eq!(plain_path(&drive), r"C:\x\a.png");
|
||||
assert_eq!(plain_path(&unc), r"\\server\share\a.png");
|
||||
assert_eq!(js_path(Path::new(&drive)), r"C:\\x\\a.png");
|
||||
assert_eq!(js_path(Path::new("a\nb'c\"d")), r#"a\nb\'c\"d"#);
|
||||
assert_eq!(plain_path("/tmp/a.png"), "/tmp/a.png");
|
||||
}
|
||||
|
||||
/// A session with one 400 × 300 pt document.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Runs `text` as `main/main.jsx` in `base`.
|
||||
fn run(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
|
||||
let main = base.join("main/main.jsx");
|
||||
std::fs::write(&main, text).unwrap();
|
||||
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
|
||||
}
|
||||
|
||||
fn log(s: &mut Session, base: &Path, text: &str) -> Vec<Value> {
|
||||
let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn failure(s: &mut Session, base: &Path, text: &str) -> String {
|
||||
run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The images of the active document: (id, linked path).
|
||||
fn images(s: &Session) -> Vec<(NodeId, Option<String>)> {
|
||||
let mut out = vec![];
|
||||
s.active().unwrap().doc.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
out.push((n.id, im.link.as_ref().map(|l| l.path.clone())));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Places `path` linked (`link`) with the engine's own command, outside any script.
|
||||
fn place(s: &mut Session, path: &Path, link: bool) -> NodeId {
|
||||
let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": link})).unwrap();
|
||||
NodeId(r["ids"][0].as_u64().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_add_file_keeps_wrapper_identity_in_collections() {
|
||||
let base = folder("bound-identity");
|
||||
let png = base.join("main/a.png");
|
||||
std::fs::write(&png, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, p = d.placedItems.add(); p.file = new File('{}'); p.name = 'placed'; d.selection = [p];\
|
||||
vc.log(p === d.placedItems[0]); vc.log(p === d.placedItems.getByName('placed'));\
|
||||
vc.log(p === d.pageItems[0]); vc.log(p === d.selection[0]);",
|
||||
js_path(&png)
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(true); 4]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_add_file_links_one_image() {
|
||||
let base = folder("add");
|
||||
let png = base.join("main/a.png");
|
||||
std::fs::write(&png, gray_png(40, 20)).unwrap();
|
||||
let mut s = session();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, p = d.placedItems.add(); vc.log(p.file); vc.log(d.placedItems.length);\
|
||||
var m = ''; try {{ p.width; }} catch (e) {{ m = e.message; }} vc.log(m);\
|
||||
p.file = new File('{}'); vc.log(d.placedItems.length); vc.log(p.typename); vc.log(p.file.name);\
|
||||
vc.log(p.width); vc.log(d.placedItems[0].file.name); vc.log(d.rasterItems.length);\
|
||||
try {{ p.file = new File('{}'); }} catch (e) {{ m = e.message; }} vc.log(m);",
|
||||
js_path(&png),
|
||||
js_path(&png)
|
||||
),
|
||||
);
|
||||
assert_eq!(out[..3], [json!(null), json!(0), json!("PlacedItem.file is required")]);
|
||||
assert_eq!(out[3..9], [json!(1), json!("PlacedItem"), json!("a.png"), json!(40), json!("a.png"), json!(0)]);
|
||||
assert_eq!(out[9], json!("PlacedItem.file is read-only: use relink"));
|
||||
let imgs = images(&s);
|
||||
assert_eq!(imgs.len(), 1);
|
||||
assert_eq!(imgs[0].1.as_deref().map(Path::new), Some(png.as_path()));
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A `placedItems.add()` result made before File › Revert is stale, as the document's other objects
|
||||
/// are, and places nothing.
|
||||
#[test]
|
||||
fn a_placed_items_add_result_is_stale_after_a_revert() {
|
||||
let base = folder("add-revert");
|
||||
let png = base.join("main/a.png");
|
||||
std::fs::write(&png, gray_png(4, 2)).unwrap();
|
||||
let mut s = session();
|
||||
s.execute("document.save", &json!({"path": base.join("main/saved.vectorcraft").to_string_lossy()})).unwrap();
|
||||
let assign = format!("p.file = new File('{}')", js_path(&png));
|
||||
for read in ["p.file", assign.as_str()] {
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("var d = app.activeDocument; d.pathItems.rectangle(0, 0, 10, 10); var p = d.placedItems.add(); vc.run('file.revert'); {read};"),
|
||||
);
|
||||
assert!(e.contains("Stale page item"), "{read}: {e}");
|
||||
}
|
||||
assert!(images(&s).is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_file_refuses_bad_values_without_changing_the_document() {
|
||||
let base = folder("bad");
|
||||
std::fs::write(base.join("main/notes.txt"), "hello").unwrap();
|
||||
std::fs::write(base.join("outside/b.png"), gray_png(4, 4)).unwrap();
|
||||
let big = std::fs::File::create(base.join("main/big.png")).unwrap();
|
||||
big.set_len((256 << 20) + 1).unwrap();
|
||||
drop(big);
|
||||
let mut s = session();
|
||||
let cases = [
|
||||
("'a.png'", "must be a File"),
|
||||
("{}", "must be a File"),
|
||||
(&format!("new File('{}')", js_path(&base.join("main/notes.txt"))), "not an image"),
|
||||
(&format!("new File('{}')", js_path(&base.join("outside/b.png"))), "Script file access denied"),
|
||||
(&format!("new File('{}')", js_path(&base.join("main/big.png"))), "larger than 256 MiB"),
|
||||
(&format!("new File('{}')", js_path(&base.join("main/none.png"))), "does not exist"),
|
||||
(&format!("new Folder('{}')", js_path(&base.join("main"))), "must be a File"),
|
||||
];
|
||||
for (value, message) in cases {
|
||||
let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = {value};"));
|
||||
assert!(e.contains(message), "{value}: {e}");
|
||||
assert!(!e.contains("outside"), "{value}: {e}");
|
||||
assert!(images(&s).is_empty(), "{value}");
|
||||
assert_eq!(undo_steps(&s), 0, "{value}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_object_shaped_like_a_file_is_not_one() {
|
||||
let base = folder("forged");
|
||||
std::fs::write(base.join("outside/b.png"), gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
let forged = js_path(&base.join("outside/b.png"));
|
||||
let e = failure(&mut s, &base, &format!("var f = {{}}; f['\\u0000fileRef'] = '{forged}'; app.activeDocument.placedItems.add().file = f;"));
|
||||
assert!(e.contains("not plain data"), "{e}");
|
||||
assert!(images(&s).is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forged_or_altered_file_does_not_change_the_path() {
|
||||
let base = folder("forged-proto");
|
||||
let (a, b, c) = (base.join("main/a.png"), base.join("main/b.png"), base.join("outside/c.png"));
|
||||
std::fs::write(&a, gray_png(10, 10)).unwrap();
|
||||
std::fs::write(&b, gray_png(20, 10)).unwrap();
|
||||
std::fs::write(&c, gray_png(30, 10)).unwrap();
|
||||
let mut s = session();
|
||||
let forged = js_path(&c);
|
||||
let make = format!(
|
||||
"var f = Object.create(File.prototype); f.__vcPath = '{forged}';\
|
||||
Object.defineProperty(f, 'fsName', {{value: '{forged}', enumerable: true}});\
|
||||
Object.defineProperty(f, 'path', {{value: '{forged}', enumerable: true}});"
|
||||
);
|
||||
for target in ["app.activeDocument.placedItems.add().file = f;", "app.activeDocument.placedItems[0].relink(f);"] {
|
||||
if target.contains("relink") {
|
||||
place(&mut s, &a, true);
|
||||
}
|
||||
let e = failure(&mut s, &base, &format!("{make} {target}"));
|
||||
assert!(e.contains("must be a File") && !e.contains("c.png"), "{target}: {e}");
|
||||
}
|
||||
let id = images(&s)[0].0;
|
||||
assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]);
|
||||
let alter = format!(
|
||||
"f.__vcPath = '{forged}'; Object.defineProperty(f, '__vcPath', {{value: '{forged}'}});\
|
||||
Object.defineProperty(f, 'fsName', {{value: '{forged}', enumerable: true}});"
|
||||
);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var f = new File('{}'); {alter} var p = app.activeDocument.placedItems.add(); p.file = f; vc.log(p.file.name);\
|
||||
f = new File('{}'); {alter} p.relink(f); vc.log(p.file.name);",
|
||||
js_path(&b),
|
||||
js_path(&a)
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!("b.png"), json!("a.png")]);
|
||||
let paths: Vec<_> = images(&s).into_iter().map(|(_, p)| p).collect();
|
||||
assert_eq!(paths.len(), 2);
|
||||
assert!(paths.iter().all(|p| p.as_deref().map(Path::new) == Some(a.as_path())), "{paths:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_items_add_result_is_a_relative_object() {
|
||||
let base = folder("relative");
|
||||
let (a, b) = (base.join("main/a.png"), base.join("main/b.png"));
|
||||
std::fs::write(&a, gray_png(10, 10)).unwrap();
|
||||
std::fs::write(&b, gray_png(20, 10)).unwrap();
|
||||
let mut s = session();
|
||||
let first = place(&mut s, &a, true);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, q = d.placedItems[0], p = d.placedItems.add(), m = '';\
|
||||
try {{ q.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m = e.message; }} vc.log(m);\
|
||||
p.file = new File('{}'); q.move(p, ElementPlacement.PLACEBEFORE);",
|
||||
js_path(&b)
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!("PlacedItem.file is required")]);
|
||||
let order: Vec<NodeId> = images(&s).into_iter().map(|(id, _)| id).collect();
|
||||
assert_eq!(order.len(), 2);
|
||||
assert_eq!(order[1], first, "{order:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_not_an_image_is_refused_before_placing() {
|
||||
let base = folder("text");
|
||||
let notes = base.join("main/notes.txt");
|
||||
std::fs::write(¬es, "hello").unwrap();
|
||||
let mut s = session();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("try {{ app.activeDocument.placedItems.add().file = new File('{}'); }} catch (e) {{ vc.log(e.message); }}", js_path(¬es)),
|
||||
);
|
||||
assert_eq!(out, vec![json!("The file is not an image")]);
|
||||
assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, |c| c.len()), 0);
|
||||
assert_eq!(undo_steps(&s), 0);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_items_add_is_bounded() {
|
||||
let base = folder("pending");
|
||||
let mut s = session();
|
||||
let e = failure(&mut s, &base, "var p = app.activeDocument.placedItems; for (var i = 0; i < 1025; i++) p.add();");
|
||||
assert!(e.contains("at most 1024"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relink_denied_path_preserves_old_link() {
|
||||
let base = folder("relink");
|
||||
let (a, b, c) = (base.join("main/a.png"), base.join("main/b.png"), base.join("outside/c.png"));
|
||||
std::fs::write(&a, gray_png(10, 10)).unwrap();
|
||||
std::fs::write(&b, gray_png(20, 10)).unwrap();
|
||||
std::fs::write(&c, gray_png(30, 10)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &a, true);
|
||||
let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&c)));
|
||||
assert!(e.contains("Script file access denied") && !e.contains("c.png"), "{e}");
|
||||
assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(&mut s, &base, &format!("var p = app.activeDocument.placedItems[0]; p.relink(new File('{}')); vc.log(p.file.name);", js_path(&b)));
|
||||
assert_eq!(out, vec![json!("b.png")]);
|
||||
assert_eq!(images(&s), vec![(id, Some(b.to_string_lossy().into_owned()))]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embed_reclassifies_and_stales_wrapper() {
|
||||
let base = folder("embed");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(10, 10)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &a, true);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.activeDocument, p = d.placedItems[0]; p.embed(); var m = '';\
|
||||
try { p.name; } catch (e) { m = e.message; } vc.log(m);\
|
||||
vc.log(d.placedItems.length); var r = d.rasterItems[0]; vc.log(r.typename);\
|
||||
vc.log(r.embedded); vc.log(r.file); vc.log(r.status === RasterLinkState.NODATA); r.embedded = true;\
|
||||
try { r.embedded = false; } catch (e) { m = e.message; } vc.log(m);",
|
||||
);
|
||||
assert_eq!(out[..6], [json!("Stale page item"), json!(0), json!("RasterItem"), json!(true), json!(null), json!(true)]);
|
||||
assert!(out[6].as_str().unwrap().contains("cannot be linked"), "{out:?}");
|
||||
assert_eq!(images(&s), vec![(id, None)]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embed_gives_raster_item_a_new_object() {
|
||||
let base = folder("embed-new");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(10, 10)).unwrap();
|
||||
let mut s = session();
|
||||
place(&mut s, &a, true);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.activeDocument, p = d.placedItems[0], q = d.pageItems[0]; vc.log(p === q); p.embed();\
|
||||
var r = d.rasterItems[0]; vc.log(p === r); vc.log(r.typename); vc.log(d.pageItems[0] === r); var m = '';\
|
||||
try { p.name; } catch (e) { m = e.message; } vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(false), json!("RasterItem"), json!(true), json!("Stale page item")]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_embed_reports_error() {
|
||||
let base = folder("missing");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(10, 10)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &a, true);
|
||||
std::fs::remove_file(&a).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let e = failure(&mut s, &base, "app.activeDocument.placedItems[0].embed();");
|
||||
assert!(e.contains("Linked image is missing"), "{e}");
|
||||
assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embed_keeps_an_exact_image_id_above_javascript_integer_precision() {
|
||||
let base = folder("embed-big-id");
|
||||
let png = base.join("main/a.png");
|
||||
std::fs::write(&png, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
let big = (1u64 << 53) + 1;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let id = place(&mut s, &png, true);
|
||||
assert_eq!(id, NodeId(big));
|
||||
let out =
|
||||
log(&mut s, &base, "var d = app.activeDocument; d.placedItems[0].embed(); vc.log(d.placedItems.length); vc.log(d.rasterItems[0].embedded);");
|
||||
assert_eq!(out, [json!(0), json!(true)]);
|
||||
assert_eq!(images(&s), vec![(id, None)]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_metadata_uses_encoded_header_not_rgb_fallback() {
|
||||
let base = folder("meta");
|
||||
let (g, c) = (base.join("main/g.png"), base.join("main/c.png"));
|
||||
std::fs::write(&g, gray_png(6, 4)).unwrap();
|
||||
std::fs::write(&c, super::links::png(3, 2, [10, 20, 30])).unwrap();
|
||||
let mut s = session();
|
||||
place(&mut s, &g, false);
|
||||
place(&mut s, &c, false);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var r = app.activeDocument.rasterItems, t = [];\
|
||||
for (var i = 0; i < r.length; i++) t.push([r[i].imageColorSpace, r[i].channels, r[i].bitsPerChannel, r[i].transparent, r[i].colorizedGrayscale]);\
|
||||
vc.log(t); vc.log(r[1].boundingBox); vc.log(r[0].imageColorSpace === ImageColorSpace.RGB); var m = r[0].matrix; vc.log([m.typename, m.mValueA, m.mValueD]);",
|
||||
);
|
||||
// The collection lists the images topmost first, as `pageItems` does: the color image placed last comes first.
|
||||
assert_eq!(out[0], json!([["ImageColorSpace.RGB", 4, 8, true, false], ["ImageColorSpace.Grayscale", 1, 8, false, false]]));
|
||||
assert_eq!(out[1], json!([0, 4, 6, 0]));
|
||||
assert_eq!(out[2], json!(true));
|
||||
let m = out[3].as_array().unwrap();
|
||||
assert_eq!(m[0], json!("Matrix"));
|
||||
assert!(m[1].as_f64().unwrap() > 0.0 && m[2].as_f64().unwrap() < 0.0, "{m:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_matrix_assignment_transforms_the_image() {
|
||||
let base = folder("matrix");
|
||||
let g = base.join("main/g.png");
|
||||
std::fs::write(&g, gray_png(10, 20)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &g, false);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var r = app.activeDocument.rasterItems[0], m = r.matrix;\
|
||||
m.mValueA = 0; m.mValueB = 2; m.mValueC = -3; m.mValueD = 0; m.mValueTX = 50; m.mValueTY = 60; r.matrix = m;\
|
||||
var n = r.matrix; vc.log([n.mValueA, n.mValueB, n.mValueC, n.mValueD, n.mValueTX, n.mValueTY]); r.matrix = n;",
|
||||
);
|
||||
let got: Vec<f64> = out[0].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
for (g, w) in got.iter().zip([0.0, 2.0, -3.0, 0.0, 50.0, 60.0]) {
|
||||
assert!((g - w).abs() < 1e-6, "{got:?}");
|
||||
}
|
||||
let xf = match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Image(im) => im.xf.as_coeffs(),
|
||||
_ => panic!("not an image"),
|
||||
};
|
||||
assert!((xf[1] + 2.0).abs() < 1e-6 && (xf[2] + 3.0).abs() < 1e-6, "{xf:?}");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
log(&mut s, &base, "var r = app.activeDocument.rasterItems[0]; r.matrix = r.matrix;");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
// A change smaller than 1e-9 to the linear part still counts.
|
||||
log(&mut s, &base, "var r = app.activeDocument.rasterItems[0], m = r.matrix; m.mValueB = m.mValueB * (1 + 1e-10); r.matrix = m;");
|
||||
assert_eq!(undo_steps(&s), before + 2);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_matrix_refuses_bad_values_without_changing_the_image() {
|
||||
let base = folder("matrix-bad");
|
||||
let g = base.join("main/g.png");
|
||||
std::fs::write(&g, gray_png(10, 20)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &g, true);
|
||||
let xf = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Image(im) => im.xf,
|
||||
_ => panic!("not an image"),
|
||||
};
|
||||
let (was, before) = (xf(&s), undo_steps(&s));
|
||||
let cases = [
|
||||
("m.mValueA = NaN;", "mValueA is not a finite number"),
|
||||
("m.mValueTY = -Infinity;", "mValueTY is not a finite number"),
|
||||
("m.mValueB = '1';", "finite mValueB"),
|
||||
("delete m.mValueTX;", "finite mValueTX"),
|
||||
("m = 5;", "finite mValueA"),
|
||||
("m.mValueA = 0; m.mValueD = 0;", "no area"),
|
||||
("m.mValueA = 1e300;", "outside the canvas"),
|
||||
("m.mValueTX = 9e6;", "outside the canvas"),
|
||||
("m.mValueA = 1e6;", "outside the canvas"),
|
||||
];
|
||||
for (change, message) in cases {
|
||||
let e = failure(&mut s, &base, &format!("var p = app.activeDocument.placedItems[0], m = p.matrix; {change} p.matrix = m;"));
|
||||
assert!(e.contains(message), "{change}: {e}");
|
||||
assert_eq!(xf(&s), was, "{change}");
|
||||
assert_eq!(undo_steps(&s), before, "{change}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_file_getter_hides_out_of_scope_link() {
|
||||
let base = folder("hide");
|
||||
let b = base.join("outside/secret.png");
|
||||
std::fs::write(&b, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
place(&mut s, &b, true);
|
||||
let e = failure(&mut s, &base, "vc.log(app.activeDocument.placedItems[0].file.fsName);");
|
||||
assert!(e.contains("Script file access denied") && !e.contains("secret"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_file_getter_resolves_document_relative_and_fallback_paths() {
|
||||
let base = folder("resolved-file");
|
||||
let png = base.join("main/a.png");
|
||||
std::fs::write(&png, gray_png(4, 4)).unwrap();
|
||||
for (stored, relative) in [
|
||||
("a.png".to_string(), None),
|
||||
(base.join("missing/a.png").to_string_lossy().into_owned(), None),
|
||||
(base.join("missing/old.png").to_string_lossy().into_owned(), Some("a.png".to_string())),
|
||||
] {
|
||||
let mut s = session();
|
||||
let image = place(&mut s, &png, true);
|
||||
s.doc_mut().unwrap().path = Some(base.join("main/page.vectorcraft").to_string_lossy().into_owned());
|
||||
if relative.is_some() {
|
||||
s.doc_mut().unwrap().path = Some(base.join("main/saved/page.vectorcraft").to_string_lossy().into_owned());
|
||||
s.doc_mut().unwrap().links_from = Some(base.join("main/original.vectorcraft").to_string_lossy().into_owned());
|
||||
}
|
||||
s.edit("Set linked path", |d, _| {
|
||||
let NodeKind::Image(im) = &mut d.node_mut(image).unwrap().kind else { panic!("not an image") };
|
||||
im.link.as_mut().unwrap().path = stored.clone();
|
||||
im.link.as_mut().unwrap().relative = relative.clone();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let out = log(&mut s, &base, &format!("vc.log(app.activeDocument.placedItems[0].file.fsName === new File('{}').fsName);", js_path(&png)));
|
||||
assert_eq!(out, [json!(true)], "{stored}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_file_getter_hides_a_link_to_an_open_document_out_of_scope() {
|
||||
let base = folder("hidedoc");
|
||||
let b = base.join("outside/secret.png");
|
||||
std::fs::write(&b, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
place(&mut s, &b, true);
|
||||
// The linked file is also the file of an open document, which the script's commands may read.
|
||||
s.doc_mut().unwrap().path = Some(b.to_string_lossy().into_owned());
|
||||
let e = failure(&mut s, &base, "vc.log(app.activeDocument.placedItems[0].file.fsName);");
|
||||
assert!(e.contains("Script file access denied") && !e.contains("secret"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Assigning `file` or `matrix` checks the item before the value: an `add()` result with no file
|
||||
/// throws `PlacedItem.file is required`, and one that was embedded throws `Stale page item`.
|
||||
#[test]
|
||||
fn assignments_check_the_item_before_the_value() {
|
||||
let base = folder("receiver");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, n = d.placedItems.add(), p = d.placedItems.add(), m = [];\
|
||||
try {{ n.matrix = null; }} catch (e) {{ m.push(e.message); }}\
|
||||
p.file = new File('{0}'); p.embed();\
|
||||
try {{ p.file = new File('{0}'); }} catch (e) {{ m.push(e.message); }}\
|
||||
try {{ p.matrix = null; }} catch (e) {{ m.push(e.message); }}\
|
||||
try {{ d.rasterItems[0].matrix = null; }} catch (e) {{ m.push(e.name); }}\
|
||||
vc.log(m);",
|
||||
js_path(&a)
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "Stale page item", "TypeError"])]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `removeAll()` deletes no image when one is on a locked artboard, in both collections.
|
||||
#[test]
|
||||
fn remove_all_keeps_images_on_a_locked_artboard() {
|
||||
let base = folder("locked-board");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
let linked = place(&mut s, &a, true);
|
||||
let embedded = place(&mut s, &a, false);
|
||||
let lock = |s: &mut Session, locked: bool| {
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = locked;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
lock(&mut s, true);
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, &base, "app.activeDocument.placedItems.removeAll();");
|
||||
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", linked.0)), "{e}");
|
||||
let e = failure(&mut s, &base, "app.activeDocument.rasterItems.removeAll();");
|
||||
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", embedded.0)), "{e}");
|
||||
assert_eq!(images(&s).len(), 2);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
lock(&mut s, false);
|
||||
let out = log(&mut s, &base, "var d = app.activeDocument; d.placedItems.removeAll(); d.rasterItems.removeAll(); vc.log(d.pageItems.length);");
|
||||
assert_eq!(out, vec![json!(0)]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_and_foreign_placed_items_are_refused() {
|
||||
let base = folder("stale");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &a, true);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = app.activeDocument.placedItems[0], m = []; p.remove();\
|
||||
try { p.relink(null); } catch (e) { m.push(e.message); }\
|
||||
try { app.activeDocument.placedItems.add().file; RasterItem.prototype.embedded.call(1); } catch (e) { m.push(e.name); }\
|
||||
try { PlacedItem.prototype.embed.call(app.activeDocument); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Stale page item", "TypeError", "this is not a PlacedItem"])]);
|
||||
assert!(s.active().unwrap().doc.node(id).is_none());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_not_available_yet_check_the_image_first() {
|
||||
let base = folder("later");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
place(&mut s, &a, true);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\
|
||||
try { n.contentVariable; } catch (e) { m.push(e.message); }\
|
||||
p.embed(); try { p.contentVariable; } catch (e) { m.push(e.message); }\
|
||||
var r = d.rasterItems[0]; try { r.colorize; } catch (e) { m.push(e.message); }\
|
||||
r.remove(); try { r.overprint; } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "RasterItem.colorize is not available yet", "Stale page item"])]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The `file` of a `PlacedItems.add()` result with no file is null while its document is open, and
|
||||
/// the item is stale once that document is closed.
|
||||
#[test]
|
||||
fn a_pending_placed_items_file_is_stale_once_its_document_closes() {
|
||||
let base = folder("pending-closed");
|
||||
let mut s = session();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = app.activeDocument.placedItems.add(); vc.log(p.file); vc.run('file.close', {});\
|
||||
var m = ''; try { vc.log(p.file); } catch (e) { m = e.message; } vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(null), json!("Stale page item")]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Assigning `file` binds the placed item to the image `file.place` made, by its exact id, also
|
||||
/// for an id above 2^53, which a script number does not hold exactly.
|
||||
#[test]
|
||||
fn a_placed_items_file_binds_the_exact_id_of_the_image_placed() {
|
||||
let base = folder("big-id");
|
||||
let png = base.join("main/a.png");
|
||||
std::fs::write(&png, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
let big = (1u64 << 53) + 1;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("var p = app.activeDocument.placedItems.add(); p.file = new File('{}'); vc.log(p.file.name); vc.log(p.width);", js_path(&png)),
|
||||
);
|
||||
assert_eq!(out, vec![json!("a.png"), json!(4)]);
|
||||
let imgs = images(&s);
|
||||
assert_eq!(imgs.len(), 1, "{imgs:?}");
|
||||
assert_eq!(imgs[0].0, NodeId(big));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A `PlacedItem` that was embedded is stale as the relative object of `move`: the raster item
|
||||
/// it became is named by a fresh wrapper.
|
||||
#[test]
|
||||
fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() {
|
||||
let base = folder("stale-relative");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
place(&mut s, &a, true);
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.activeDocument, p = d.placedItems[0], x = null, m = '';\
|
||||
for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') x = d.pageItems[i]; }\
|
||||
p.embed(); try { x.move(p, ElementPlacement.PLACEAFTER); } catch (e) { m = e.message; } vc.log(m);\
|
||||
x.move(d.rasterItems[0], ElementPlacement.PLACEAFTER); vc.log([d.pageItems[0].typename, d.pageItems[1].typename]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Stale page item"), json!(["RasterItem", "PathItem"])]);
|
||||
assert!(s.active().unwrap().doc.node(NodeId(rect)).is_some());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -734,6 +734,39 @@ fn filled_true_on_a_compound_member_places_the_gradient_on_the_compound() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.resize(50, 50, true, true, true, true, 50);\
|
||||
vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(2)], "the compound's stroke halves with the member");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforming_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.transform(app.getScaleMatrix(50), true, true, true, true, 50);\
|
||||
vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(2)], "transform scales the compound's stroke as resize does");
|
||||
// 100 keeps the weight even when the scale is within the tolerance of 100%.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems[0]; p.transform(app.getScaleMatrix(100.00000005), true, true, true, true, 100);\
|
||||
vc.log(p.strokeWidth);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_anchors_reads_smooth_false_as_a_corner() {
|
||||
let (mut s, a, _) = doc();
|
||||
@@ -1203,7 +1236,7 @@ fn locked_paths_and_wrong_objects_are_refused() {
|
||||
("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", "Cannot edit PathItem"),
|
||||
("app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", "Cannot edit PathItem"),
|
||||
("app.activeDocument.pathItems[0].strokeWidth = 3;", "Cannot edit PathItem"),
|
||||
("app.activeDocument.pathItems[0].translate(5, 5);", "Cannot edit PathItem"),
|
||||
("app.activeDocument.pathItems[0].translate(5, 5);", "cannot transform locked objects"),
|
||||
] {
|
||||
let e = failure(&mut s, source);
|
||||
assert!(e.contains(part), "{source}: {e}");
|
||||
@@ -1236,10 +1269,10 @@ fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() {
|
||||
assert_eq!(out[3], json!(6));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].rotate(10, true, true, true, true, 'CENTER');").contains("Transformation"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].resize(0, 100);").contains("scaleX"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("changePositions"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("transformObjects"));
|
||||
let before = art(&s);
|
||||
for (source, part) in [
|
||||
("app.activeDocument.pathItems[0].translate(1, 2, true, true, false);", "changeFillGradients false"),
|
||||
("app.activeDocument.pathItems[0].translate(1, 2, true, false, false);", "transformFillGradients different from transformObjects"),
|
||||
("app.activeDocument.pathItems[0].rotate(10, true, true, true, false);", "must be the same"),
|
||||
("app.activeDocument.pathItems.ellipse(10, 10, 5, 5, false, true);", "inscribed"),
|
||||
(
|
||||
@@ -1543,18 +1576,16 @@ fn path_changes_refuse_paths_on_a_locked_artboard() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
// Points (waiting and written at once), paint, stroke and a transform.
|
||||
for change in [
|
||||
"p.closed = false;",
|
||||
"p.pathPoints[0].anchor = [1, 2];",
|
||||
"p.setEntirePath([[0, 0], [10, 10]]);",
|
||||
"p.filled = false;",
|
||||
"p.strokeWidth = 7;",
|
||||
"p.translate(5, 5);",
|
||||
] {
|
||||
// Points (waiting and written at once), paint and stroke.
|
||||
for change in
|
||||
["p.closed = false;", "p.pathPoints[0].anchor = [1, 2];", "p.setEntirePath([[0, 0], [10, 10]]);", "p.filled = false;", "p.strokeWidth = 7;"]
|
||||
{
|
||||
let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}"));
|
||||
assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}");
|
||||
}
|
||||
// A transform is PageItem's, which refuses any object on a locked artboard.
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems[0].translate(5, 5);");
|
||||
assert!(e.contains(&format!("cannot transform objects on a locked artboard: {}", a.0)), "{e}");
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete objects on a locked artboard"), "{e}");
|
||||
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps));
|
||||
|
||||
@@ -0,0 +1,662 @@
|
||||
//! The script object model: `app.preferences`, the matrix functions of `app` and `app.copy`,
|
||||
//! `app.cut` and `app.paste`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::script::dom::preferences::{MAX_KEYS, MAX_STRING_BYTES, MAX_TOTAL_BYTES, WARNING_OFF_NEEDS_A_PERSON, WARNING_OFF_QUESTION};
|
||||
use crate::script::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn stored(s: &Session, key: &str) -> Option<ScriptPreference> {
|
||||
s.prefs.script_preferences.get(key).cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_external_jsx_warning_is_the_external_script_warning() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
let journal = s.journal.len();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.preferences; vc.log(p.typename); vc.log(p.getBooleanPreference('ShowExternalJSXWarning'));\
|
||||
vc.log(p.getIntegerPreference('ShowExternalJSXWarning')); p.setBooleanPreference('ShowExternalJSXWarning', true);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Preferences"), json!(true), json!(1)]);
|
||||
// A preference is not a command, so the journal has no entry for the run.
|
||||
assert_eq!(s.journal.len(), journal);
|
||||
assert!(s.prefs.script_preferences.is_empty());
|
||||
assert!(failure(&mut s, "app.preferences.setIntegerPreference('ShowExternalJSXWarning', 1);").contains("setBooleanPreference"));
|
||||
// Turned off by the person, a script reads it as off and can turn it back on, or remove it.
|
||||
s.prefs.show_external_script_warning = false;
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.preferences; p.setBooleanPreference('ShowExternalJSXWarning', false);\
|
||||
vc.log(p.getBooleanPreference('ShowExternalJSXWarning')); p.setBooleanPreference('ShowExternalJSXWarning', true);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(false)]);
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
s.prefs.show_external_script_warning = false;
|
||||
log(&mut s, "app.preferences.removePreference('ShowExternalJSXWarning');");
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
}
|
||||
|
||||
/// A run with nobody to ask cannot turn the warning off, even with a Yes in `answers`.
|
||||
#[test]
|
||||
fn a_run_without_a_person_cannot_turn_the_warning_off() {
|
||||
let mut s = Session::new();
|
||||
let off = "app.preferences.setBooleanPreference('ShowExternalJSXWarning', false);";
|
||||
assert!(failure(&mut s, off).contains(WARNING_OFF_NEEDS_A_PERSON));
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
let r = s.execute("script.run", &json!({"source": off, "name": "t.js", "answers": [{"kind": "confirm", "value": true}]}));
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains(WARNING_OFF_NEEDS_A_PERSON)), "{r:?}");
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
let caught = log(&mut s, &format!("try {{ {off} }} catch (e) {{ vc.log(e.message); }}"));
|
||||
assert_eq!(caught, vec![json!(WARNING_OFF_NEEDS_A_PERSON)]);
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
}
|
||||
|
||||
/// A run in the app, one slice in.
|
||||
fn framed(s: &mut Session, source: &str) {
|
||||
s.script_frames = true;
|
||||
assert_eq!(run(s, source).unwrap()["running"], true);
|
||||
assert!(s.script_pump().is_none());
|
||||
}
|
||||
|
||||
/// Pumps the run in the app until it ends or waits at a dialog (`None`).
|
||||
fn pump(s: &mut Session) -> Option<Result<Value>> {
|
||||
for _ in 0..10_000 {
|
||||
if s.script_dialog().is_some() {
|
||||
return None;
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
return Some(r);
|
||||
}
|
||||
}
|
||||
panic!("the run neither ended nor waited");
|
||||
}
|
||||
|
||||
const ASK_OFF: &str = "var p = app.preferences; var r = p.setBooleanPreference('ShowExternalJSXWarning', false);\
|
||||
vc.log([r === undefined, p.getBooleanPreference('ShowExternalJSXWarning')]);";
|
||||
|
||||
#[test]
|
||||
fn yes_to_the_confirm_turns_the_warning_off() {
|
||||
let mut s = Session::new();
|
||||
framed(&mut s, ASK_OFF);
|
||||
let want = ScriptDialog {
|
||||
kind: DialogKind::Confirm,
|
||||
message: WARNING_OFF_QUESTION.into(),
|
||||
title: None,
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(s.script_dialog_turns_warning_off());
|
||||
assert!(s.prefs.show_external_script_warning, "nothing changes while the confirm waits");
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(true)));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([[true, false]]));
|
||||
assert_eq!(r["dialogs"][0]["answer"], true);
|
||||
assert!(!s.prefs.show_external_script_warning);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_confirm_with_the_same_text_is_not_the_warning_question() {
|
||||
let mut s = Session::new();
|
||||
framed(&mut s, &format!("vc.log(confirm({}));", json!(WARNING_OFF_QUESTION)));
|
||||
assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string()));
|
||||
assert!(!s.script_dialog_turns_warning_off());
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(true)));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([true]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_the_warning_on_after_yes_keeps_it_on() {
|
||||
let mut s = Session::new();
|
||||
framed(
|
||||
&mut s,
|
||||
&format!("{ASK_OFF} p.setBooleanPreference('ShowExternalJSXWarning', true); vc.log(p.getBooleanPreference('ShowExternalJSXWarning'));"),
|
||||
);
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(true)));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([[true, false], true]), "the script sees the answer at once");
|
||||
assert!(s.prefs.show_external_script_warning, "the script's last write is what the run keeps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_to_the_confirm_or_stop_leaves_the_warning_on() {
|
||||
let mut s = Session::new();
|
||||
framed(&mut s, ASK_OFF);
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(false)));
|
||||
assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([[true, true]]));
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
framed(&mut s, ASK_OFF);
|
||||
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
|
||||
assert!(!s.script_answer(DialogAnswer::Confirm(true)));
|
||||
assert!(s.script_pump().unwrap().is_err());
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
// Yes in a run that then fails is put back with the rest of the run.
|
||||
framed(&mut s, &format!("{ASK_OFF} throw new Error('stop');"));
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(true)));
|
||||
assert!(pump(&mut s).unwrap().is_err());
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
}
|
||||
|
||||
/// Asking to show no dialogs does not skip the confirm, and a call from a callback, where no dialog
|
||||
/// can open, throws.
|
||||
#[test]
|
||||
fn the_confirm_cannot_be_skipped() {
|
||||
let mut s = Session::new();
|
||||
framed(&mut s, &format!("try {{ app.userInteractionLevel = 'DONTDISPLAYALERTS'; }} catch (e) {{}} {ASK_OFF}"));
|
||||
assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string()));
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(false)));
|
||||
assert!(pump(&mut s).unwrap().is_ok());
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
let callback = "[1].forEach(function () { app.preferences.setBooleanPreference('ShowExternalJSXWarning', false); });";
|
||||
assert_eq!(run(&mut s, callback).unwrap()["running"], true);
|
||||
let e = pump(&mut s).unwrap().unwrap_err().to_string();
|
||||
assert!(e.contains(WARNING_OFF_NEEDS_A_PERSON), "{e}");
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_keys_keep_their_type_across_runs_and_a_restart() {
|
||||
let mut s = Session::new();
|
||||
log(
|
||||
&mut s,
|
||||
"var p = app.preferences; p.setBooleanPreference('my/flag', true); p.setIntegerPreference('count', -7);\
|
||||
p.setRealPreference('ratio', 0.25); p.setStringPreference('name', 'Ünïcode \\u2713');",
|
||||
);
|
||||
assert_eq!(stored(&s, "my/flag"), Some(ScriptPreference::Boolean(true)));
|
||||
assert_eq!(stored(&s, "count"), Some(ScriptPreference::Integer(-7)));
|
||||
assert_eq!(stored(&s, "ratio"), Some(ScriptPreference::Real(0.25)));
|
||||
assert_eq!(stored(&s, "name"), Some(ScriptPreference::String("Ünïcode \u{2713}".into())));
|
||||
// The preferences as the app saves them, read into a new session.
|
||||
let saved = serde_json::to_string(&s.prefs).unwrap();
|
||||
let mut t = Session::new();
|
||||
t.prefs = serde_json::from_str(&saved).unwrap();
|
||||
let out = log(
|
||||
&mut t,
|
||||
"var p = app.preferences; vc.log(p.getBooleanPreference('my/flag')); vc.log(p.getIntegerPreference('count'));\
|
||||
vc.log(p.getRealPreference('ratio')); vc.log(p.getStringPreference('name'));",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(-7), json!(0.25), json!("Ünïcode \u{2713}")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_keys_read_as_empty_values_and_getters_convert() {
|
||||
let mut s = Session::new();
|
||||
let mut out = log(
|
||||
&mut s,
|
||||
"var p = app.preferences; vc.log([p.getBooleanPreference('none'), p.getIntegerPreference('none'),\
|
||||
p.getRealPreference('none'), p.getStringPreference('none')]);\
|
||||
p.setRealPreference('r', -2.75); p.setStringPreference('t', ' 12.5 '); p.setStringPreference('x', 'abc');\
|
||||
p.setBooleanPreference('b', true); p.setIntegerPreference('i', 0);\
|
||||
vc.log([p.getIntegerPreference('r'), p.getStringPreference('r'), p.getBooleanPreference('r')]);\
|
||||
vc.log([p.getRealPreference('t'), p.getIntegerPreference('t'), p.getBooleanPreference('t')]);\
|
||||
vc.log([isNaN(p.getRealPreference('x')), p.getIntegerPreference('x')]);\
|
||||
vc.log([p.getStringPreference('b'), p.getRealPreference('b'), p.getBooleanPreference('i'), p.getStringPreference('i')]);\
|
||||
var n = []; ['0x10', '0B101', '0o17', '-0x10', '0x', ' -Infinity ', '1e3', '.5', 'inf', '1_0'].forEach(function (t) {\
|
||||
p.setStringPreference('n', t); n.push(String(p.getRealPreference('n'))); }); vc.log(n.join(' '));\
|
||||
p.setStringPreference('n', '0x200000000000018'); var r = [p.getRealPreference('n') === Math.pow(2, 57) + 32];\
|
||||
p.setStringPreference('n', '0x' + new Array(301).join('f')); r.push(String(p.getRealPreference('n')));\
|
||||
p.setStringPreference('n', '0b' + new Array(60).join('0') + '1' + new Array(53).join('0') + '1'); r.push(p.getRealPreference('n') === Math.pow(2, 53));\
|
||||
vc.log(r);",
|
||||
);
|
||||
// Each whole number in base 16, 8 or 2 is rounded once: 2^57 + 24 to 2^57 + 32, 1,200 bits to
|
||||
// Infinity, and 2^53 + 1 after leading zeros to 2^53 (ties to even).
|
||||
assert_eq!(out.pop(), Some(json!([true, "Infinity", true])));
|
||||
assert_eq!(out.pop(), Some(json!("16 5 15 NaN NaN -Infinity 1000 0.5 NaN NaN")));
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![json!([false, 0, 0, ""]), json!([-2, "-2.75", true]), json!([12.5, 12, true]), json!([true, 0]), json!(["true", 1, false, "0"])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_reads_trim_javascript_whitespace_only() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.preferences; var r = [];\
|
||||
['\\u0085' + '42', '\\ufeff 42\\u00a0', '\\u2028' + '42\\u3000'].forEach(function (t) {\
|
||||
p.setStringPreference('n', t); r.push(String(p.getRealPreference('n'))); }); vc.log(r.join(' '));",
|
||||
);
|
||||
assert_eq!(out, vec![json!("NaN 42 42")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_preference_changes_between_zero_and_negative_zero() {
|
||||
let mut s = Session::new();
|
||||
log(&mut s, "app.preferences.setRealPreference('z', -0);");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.preferences; vc.log(String(1 / p.getRealPreference('z'))); p.setRealPreference('z', 0); vc.log(String(1 / p.getRealPreference('z')));",
|
||||
);
|
||||
assert_eq!(out, vec![json!("-Infinity"), json!("Infinity")]);
|
||||
// The change is kept when the run's keys are merged with the app's.
|
||||
assert_eq!(stored(&s, "z").map(|v| matches!(v, ScriptPreference::Real(r) if r.to_bits() == 0)), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arguments_throw_and_store_nothing() {
|
||||
let mut s = Session::new();
|
||||
let mut wrong = Vec::new();
|
||||
for (source, message) in [
|
||||
("app.preferences.setIntegerPreference('k', 1.5);", "whole number"),
|
||||
("app.preferences.setIntegerPreference('k', 1e300);", "whole number"),
|
||||
("app.preferences.setIntegerPreference('k', '3');", "whole number"),
|
||||
("app.preferences.setRealPreference('k', Infinity);", "finite number"),
|
||||
("app.preferences.setRealPreference('k', NaN);", "finite number"),
|
||||
("app.preferences.setBooleanPreference('k', 1);", "true or false"),
|
||||
("app.preferences.setStringPreference('k', 5);", "a string"),
|
||||
("app.preferences.setStringPreference(5, 'v');", "key must be a string"),
|
||||
("app.preferences.getBooleanPreference();", "key must be a string"),
|
||||
("app.preferences.setStringPreference('', 'v');", "1 to 256"),
|
||||
("app.preferences.setStringPreference(new Array(258).join('k'), 'v');", "1 to 256"),
|
||||
// 129 characters outside the Basic Multilingual Plane are 258 UTF-16 code units.
|
||||
("app.preferences.setStringPreference(new Array(130).join('\\uD83D\\uDE00'), 'v');", "1 to 256"),
|
||||
("app.preferences.setStringPreference('a\\u0000b', 'v');", "control characters"),
|
||||
("app.preferences.setStringPreference('k', new Array(65538).join('v'));", "at most 65536 bytes"),
|
||||
("var f = app.preferences.getBooleanPreference; f.call({}, 'k');", "not a Preferences"),
|
||||
("Preferences.prototype.setBooleanPreference('k', true);", "not a Preferences"),
|
||||
] {
|
||||
match run(&mut s, source) {
|
||||
Err(e) if e.to_string().contains(message) => {}
|
||||
r => wrong.push(format!("{source}: {r:?}")),
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
assert!(s.prefs.script_preferences.is_empty());
|
||||
// A key of exactly 256 code units and a value of exactly the limit are taken.
|
||||
log(&mut s, "app.preferences.setStringPreference(new Array(257).join('k'), new Array(65537).join('v'));");
|
||||
assert_eq!(stored(&s, &"k".repeat(256)), Some(ScriptPreference::String("v".repeat(MAX_STRING_BYTES))));
|
||||
log(&mut s, "app.preferences.setStringPreference(new Array(129).join('\\uD83D\\uDE00'), 'v');");
|
||||
assert_eq!(stored(&s, &"\u{1F600}".repeat(128)), Some(ScriptPreference::String("v".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_store_limits_its_keys() {
|
||||
let mut s = Session::new();
|
||||
for i in 0..MAX_KEYS {
|
||||
s.prefs.script_preferences.insert(format!("k{i}"), ScriptPreference::Integer(1));
|
||||
}
|
||||
assert!(failure(&mut s, "app.preferences.setIntegerPreference('one more', 1);").contains("at most 4096 keys"));
|
||||
assert_eq!(s.prefs.script_preferences.len(), MAX_KEYS);
|
||||
// A key already stored can still change.
|
||||
log(&mut s, "app.preferences.setIntegerPreference('k0', 2);");
|
||||
assert_eq!(stored(&s, "k0"), Some(ScriptPreference::Integer(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_store_limits_its_bytes() {
|
||||
let mut s = Session::new();
|
||||
let big = "v".repeat(MAX_STRING_BYTES);
|
||||
for i in 0..MAX_TOTAL_BYTES / MAX_STRING_BYTES - 1 {
|
||||
s.prefs.script_preferences.insert(format!("{i:02}"), ScriptPreference::String(big.clone()));
|
||||
}
|
||||
let e = failure(&mut s, "app.preferences.setStringPreference('last', new Array(65537).join('v'));");
|
||||
assert!(e.contains("at most 1048576 bytes"), "{e}");
|
||||
assert_eq!(stored(&s, "last"), None);
|
||||
// Replacing a stored value counts the new value instead of the old one.
|
||||
log(&mut s, "app.preferences.setStringPreference('00', new Array(65537).join('w'));");
|
||||
assert_eq!(stored(&s, "00"), Some(ScriptPreference::String("w".repeat(MAX_STRING_BYTES))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_run_puts_the_store_back_and_removing_the_last_key_empties_it() {
|
||||
let mut s = Session::new();
|
||||
log(&mut s, "app.preferences.setIntegerPreference('keep', 1);");
|
||||
let e = failure(&mut s, "app.preferences.setIntegerPreference('keep', 2); app.preferences.setRealPreference('new', 1); throw new Error('stop');");
|
||||
assert!(e.contains("stop"));
|
||||
assert_eq!(stored(&s, "keep"), Some(ScriptPreference::Integer(1)));
|
||||
assert_eq!(stored(&s, "new"), None);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.preferences; p.removePreference('missing'); p.removePreference('keep');\
|
||||
vc.log(p.getIntegerPreference('keep'));",
|
||||
);
|
||||
assert_eq!(out, vec![json!(0)]);
|
||||
assert!(s.prefs.script_preferences.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_merges_its_keys_with_keys_the_app_changed_meanwhile() {
|
||||
let mut s = Session::new();
|
||||
s.prefs.script_preferences.insert("gone".into(), ScriptPreference::Integer(1));
|
||||
s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(1));
|
||||
s.script_frames = true;
|
||||
let source = "var p = app.preferences; p.removePreference('gone'); p.setIntegerPreference('mine', 2);\
|
||||
for (var i = 0; i < 2000000; i++) {}";
|
||||
assert_eq!(run(&mut s, source).unwrap()["running"], true);
|
||||
assert!(s.script_pump().is_none());
|
||||
assert!(s.script_running());
|
||||
s.prefs.script_preferences.insert("theirs".into(), ScriptPreference::Boolean(true));
|
||||
s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(3));
|
||||
while s.script_pump().is_none() {}
|
||||
let keys: Vec<(&str, &ScriptPreference)> = s.prefs.script_preferences.iter().map(|(k, v)| (k.as_str(), v)).collect();
|
||||
assert_eq!(
|
||||
keys,
|
||||
vec![("kept", &ScriptPreference::Integer(3)), ("mine", &ScriptPreference::Integer(2)), ("theirs", &ScriptPreference::Boolean(true))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix_functions_give_new_records() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"function v(m) { return [m.typename, m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\
|
||||
vc.log(v(app.getIdentityMatrix())); vc.log(v(app.getTranslationMatrix(100, 200))); vc.log(v(app.getTranslationMatrix()));\
|
||||
vc.log(v(app.getScaleMatrix(60))); vc.log(v(app.getScaleMatrix(50, 200))); vc.log(v(app.getScaleMatrix()));\
|
||||
vc.log(v(app.getRotationMatrix(90))); vc.log(v(app.getRotationMatrix(-270))); vc.log(v(app.getRotationMatrix()));",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(["Matrix", 1, 0, 0, 1, 0, 0]),
|
||||
json!(["Matrix", 1, 0, 0, 1, 100, 200]),
|
||||
json!(["Matrix", 1, 0, 0, 1, 0, 0]),
|
||||
json!(["Matrix", 0.6, 0, 0, 0.6, 0, 0]),
|
||||
json!(["Matrix", 0.5, 0, 0, 2, 0, 0]),
|
||||
json!(["Matrix", 1, 0, 0, 1, 0, 0]),
|
||||
json!(["Matrix", 0, 1, -1, 0, 0, 0]),
|
||||
json!(["Matrix", 0, 1, -1, 0, 0, 0]),
|
||||
json!(["Matrix", 1, 0, 0, 1, 0, 0]),
|
||||
]
|
||||
);
|
||||
let r = log(&mut s, "var m = app.getRotationMatrix(30); vc.log([m.mValueA, m.mValueB, m.mValueC, m.mValueD]);");
|
||||
let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
|
||||
assert_eq!(r, vec![json!([c, sn, -sn, c])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concatenation_applies_the_first_matrix_first() {
|
||||
let mut s = Session::new();
|
||||
// As PDF `cm` operators compose (ISO 32000-1, 8.3.4): [x y 1] × M × N.
|
||||
// M = [2 0 0 3 5 7] then N = [0 1 -1 0 10 20]: (x, y) → (2x + 5, 3y + 7) → (-(3y + 7) + 10, 2x + 5 + 20).
|
||||
let out = log(
|
||||
&mut s,
|
||||
"function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\
|
||||
var m = {mValueA: 2, mValueB: 0, mValueC: 0, mValueD: 3, mValueTX: 5, mValueTY: 7};\
|
||||
var n = {mValueA: 0, mValueB: 1, mValueC: -1, mValueD: 0, mValueTX: 10, mValueTY: 20};\
|
||||
var c = app.concatenateMatrix(m, n); vc.log(v(c)); vc.log(v(m)); vc.log(c === m);\
|
||||
vc.log(v(app.concatenateTranslationMatrix(m, 1, 2))); vc.log(v(app.concatenateScaleMatrix(m, 50)));\
|
||||
vc.log(v(app.concatenateRotationMatrix(m, 90)));\
|
||||
vc.log(app.isEqualMatrix(app.concatenateRotationMatrix(m, 90), app.concatenateMatrix(m, app.getRotationMatrix(90))));",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!([0, 2, -3, 0, 3, 25]),
|
||||
json!([2, 0, 0, 3, 5, 7]),
|
||||
json!(false),
|
||||
json!([2, 0, 0, 3, 6, 9]),
|
||||
json!([1, 0, 0, 1.5, 2.5, 3.5]),
|
||||
json!([0, 2, -3, 0, -7, 5]),
|
||||
json!(true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_number() {
|
||||
let mut s = Session::new();
|
||||
// N·(1 - 2^-53) is N - S/2, which rounds up to N; the exact A is -1.5·S, which rounds to -2·S.
|
||||
// MAX - 2^969 + 2^970 rounds to MAX, while adding the rounded MAX - 2^969 and 2^970 overflows.
|
||||
// MAX·(1 - 2^-53) + 2^971 + 2^970 - 2^917 is past the overflow midpoint by 2^917, which rounding
|
||||
// the first product drops.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\
|
||||
var n = Math.pow(2, -1022), s = Number.MIN_VALUE;\
|
||||
vc.log(app.concatenateMatrix(mat([n, n + s, 0, 1, 0, 0]), mat([1 - Math.pow(2, -53), 0, -1, 1, 0, 0])).mValueA === -2 * s);\
|
||||
vc.log(app.concatenateMatrix(mat([n, 0, 0, 1, 0, 0]), mat([1, 0, 0, 1, 0, 0])).mValueA === n);\
|
||||
var shift = mat([1, 0, -1, 1, Math.pow(2, 970), 0]);\
|
||||
vc.log(app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, Math.pow(2, 969)]), shift).mValueTX === Number.MAX_VALUE);\
|
||||
try { app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, 0]), shift); vc.log('finite'); }\
|
||||
catch (e) { vc.log(e.name); }\
|
||||
var near = mat([1 - Math.pow(2, -53), 0, 1, 1, Math.pow(2, 970) - Math.pow(2, 917), 0]);\
|
||||
try { app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, Math.pow(2, 971)]), near); vc.log('finite'); }\
|
||||
catch (e) { vc.log(e.name); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(true), json!(true), json!("RangeError"), json!("RangeError")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concatenation_keeps_a_small_translation_that_a_large_one_cancels() {
|
||||
let mut s = Session::new();
|
||||
// 2^53 + 1 rounds to 2^53, so adding the rounded products and then -2^53 gives 0; the exact X is 1.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\
|
||||
var big = Math.pow(2, 53);\
|
||||
vc.log(app.concatenateMatrix(mat([1, 0, 0, 1, big, 1]), mat([1, 0, 1, 1, -big, 0])).mValueTX);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_number() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\
|
||||
function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\
|
||||
var x = Math.pow(2, 600), y = Math.pow(2, -500), z = Math.pow(2, -575);\
|
||||
var c = app.concatenateMatrix(mat([x, x, 0, 1, x, x]), mat([x, 0, -x, 1, 0, 0]));\
|
||||
vc.log([c.mValueA, c.mValueB === x, c.mValueC === -x, c.mValueD, c.mValueTX, c.mValueTY === x]);\
|
||||
vc.log(app.concatenateMatrix(mat([y, y, 0, 1, 0, 0]), mat([z, 0, z, 1, 0, 0])).mValueA === Number.MIN_VALUE);\
|
||||
var p = 2.0543170765449965e-57, q = 6.201533916984909e-252;\
|
||||
vc.log(app.concatenateMatrix(mat([p, 0, 0, 1, 0, 0]), mat([q, 0, 0, 1, 0, 0])).mValueA === p * q);\
|
||||
vc.log(v(app.concatenateMatrix(mat([-2, 0, 0, -3, 0, 0]), mat([0, 1, -1, 0, 0, 0]))));\
|
||||
var big = mat([1, 0, 0, 1, Number.MAX_VALUE, 0]), up = 1 + Math.pow(2, -52);\
|
||||
try { app.concatenateMatrix(big, mat([up, 0, 0, 1, -Math.pow(2, 971), 0])); vc.log('finite'); }\
|
||||
catch (e) { vc.log(e.name); }\
|
||||
vc.log(app.concatenateMatrix(big, mat([up, 0, 0, 1, -Math.pow(2, 972), 0])).mValueTX === Number.MAX_VALUE);\
|
||||
var h = Math.pow(2, 500), far = mat([1, 0, 0, 1, Math.pow(2, 600), -Math.pow(2, 600)]);\
|
||||
vc.log(app.concatenateMatrix(far, mat([h, 0, h, 1, 1, 0])).mValueTX);\
|
||||
var g = Math.pow(2, 100), farther = mat([1, 0, 0, 1, Math.pow(2, 1000), -Math.pow(2, 1000)]);\
|
||||
vc.log(app.concatenateMatrix(farther, mat([g, 0, g, 1, Math.pow(2, -100), 0])).mValueTX === Math.pow(2, -100));\
|
||||
var tiny = mat([1, 0, 0, 1, y, 0]);\
|
||||
vc.log(app.concatenateMatrix(tiny, mat([z, 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === 2 * Number.MIN_VALUE);\
|
||||
var least = mat([1, 0, 0, 1, Number.MIN_VALUE, 0]);\
|
||||
vc.log(app.concatenateMatrix(least, mat([0.5 - Math.pow(2, -54), 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === Number.MIN_VALUE);\
|
||||
vc.log(app.concatenateMatrix(least, mat([0.5 + Math.pow(2, -53), 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === 2 * Number.MIN_VALUE);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!([0, true, true, 1, 0, true]),
|
||||
json!(true),
|
||||
json!(true),
|
||||
json!([0, -2, 3, 0, 0, 0]),
|
||||
json!("RangeError"),
|
||||
json!(true),
|
||||
json!(1),
|
||||
json!(true),
|
||||
json!(true),
|
||||
json!(true),
|
||||
json!(true)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_concatenated_translation_next_to_the_largest_number_is_rounded_once() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\
|
||||
var a = Math.pow(2, 969), b = Math.pow(2, 970);\
|
||||
function tx(f, t) { try { return app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, f]), mat([1, 0, 1, 1, t, 0])).mValueTX === Number.MAX_VALUE; }\
|
||||
catch (e) { return e.name; } }\
|
||||
vc.log(tx(-a, b)); vc.log(tx(a, a));",
|
||||
);
|
||||
// MAX + 2^969 is below the halfway point to 2^1024, and MAX + 2^970 is that point, which rounds
|
||||
// to 2^1024.
|
||||
assert_eq!(out, vec![json!(true), json!("RangeError")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD]; }\
|
||||
var m = app.getRotationMatrix(-89.99999999999999); vc.log(m.mValueA > 0); vc.log(m.mValueB);\
|
||||
vc.log(v(app.getRotationMatrix(-90))); vc.log(v(app.getRotationMatrix(-180))); vc.log(v(app.getRotationMatrix(-450)));",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(-1), json!([0, -1, 1, 0]), json!([-1, 0, 0, -1]), json!([0, -1, 1, 0])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_singular_and_equal_matrices() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var m = app.concatenateTranslationMatrix(app.concatenateRotationMatrix(app.getScaleMatrix(40, 250), 33), 17, -4);\
|
||||
var i = app.invertMatrix(m), back = app.concatenateMatrix(m, i), id = app.getIdentityMatrix();\
|
||||
var d = [back.mValueA - 1, back.mValueB, back.mValueC, back.mValueD - 1, back.mValueTX, back.mValueTY];\
|
||||
vc.log(Math.max.apply(null, d.map(Math.abs)) < 1e-12);\
|
||||
vc.log(app.isSingularMatrix(app.getScaleMatrix(0, 100))); vc.log(app.isSingularMatrix(m));\
|
||||
vc.log(app.isEqualMatrix(id, app.getRotationMatrix(360))); vc.log(app.isEqualMatrix(id, app.getTranslationMatrix(0, 1e-300)));\
|
||||
var tiny = app.getScaleMatrix(1e-198, 1e202), t = app.invertMatrix(tiny);\
|
||||
function near(v, w) { return Math.abs(v / w - 1) < 1e-12; }\
|
||||
vc.log([app.isSingularMatrix(tiny), near(t.mValueA, 1e200), near(t.mValueD, 1e-200), t.mValueB, t.mValueC]);\
|
||||
vc.log(near(app.invertMatrix(app.getScaleMatrix(1e202)).mValueA, 1e-200));\
|
||||
function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: 0, mValueTY: 0}; }\
|
||||
var wide = mat([1e308, 0, 1e308, 1e-100]), w = app.invertMatrix(wide);\
|
||||
vc.log([app.isSingularMatrix(wide), near(w.mValueA, 1e-308), near(w.mValueC, -1e100), near(w.mValueD, 1e100)]);\
|
||||
var thin = app.invertMatrix(mat([1e300, 0, 1e300, 5e-24]));\
|
||||
vc.log([near(thin.mValueA, 1e-300), near(thin.mValueC, -2e23), near(thin.mValueD, 2e23)]);\
|
||||
var close = mat([7207, 7440, 382, 394.34993756070486]), ci = app.invertMatrix(close);\
|
||||
vc.log([app.isSingularMatrix(close), app.isSingularMatrix(mat([6, 4, 3, 2])), near(ci.mValueD, 7207 / -8.009237717487849e-11)]);\
|
||||
var far = mat([1e-100, 1e-100, 1e-100, 1e-100 + 1e-115]); far.mValueTX = 1e200; far.mValueTY = 1e200;\
|
||||
var fi = app.invertMatrix(far); vc.log([Math.abs(fi.mValueTX / -1e300 - 1) < 1e-6, fi.mValueTY]);",
|
||||
);
|
||||
assert_eq!(out[..5], [json!(true), json!(true), json!(false), json!(true), json!(false)]);
|
||||
assert_eq!(out[5], json!([false, true, true, 0, 0]));
|
||||
assert_eq!(out[6], json!(true));
|
||||
assert_eq!(out[7], json!([false, true, true, true]));
|
||||
assert_eq!(out[8], json!([true, true, true]));
|
||||
assert_eq!(out[9], json!([false, true, true]));
|
||||
assert_eq!(out[10], json!([true, 0]));
|
||||
let mut wrong = Vec::new();
|
||||
for (source, message) in [
|
||||
("app.invertMatrix(app.getScaleMatrix(100, 0));", "singular"),
|
||||
("app.getTranslationMatrix(NaN);", "not a finite number"),
|
||||
("app.getScaleMatrix('50');", "scaleX must be a finite number"),
|
||||
("app.getRotationMatrix(Infinity);", "not a finite number"),
|
||||
("app.getRotationMatrix(null);", "angle must be a finite number"),
|
||||
("app.concatenateMatrix(app.getIdentityMatrix(), {mValueA: 1});", "secondMatrix must be a Matrix"),
|
||||
(
|
||||
"app.concatenateMatrix(app.getIdentityMatrix(), {mValueA: 1, mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: '0', mValueTY: 0});",
|
||||
"secondMatrix must be a Matrix",
|
||||
),
|
||||
("app.invertMatrix(5);", "matrix must be a Matrix"),
|
||||
("var m = app.getIdentityMatrix(); m.mValueTX = Infinity; app.isSingularMatrix(m);", "not a finite number"),
|
||||
("app.concatenateScaleMatrix(app.getScaleMatrix(1e300), 1e300);", "too large"),
|
||||
] {
|
||||
match run(&mut s, source) {
|
||||
Err(e) if e.to_string().contains(message) => {}
|
||||
r => wrong.push(format!("{source}: {r:?}")),
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_and_paste_run_as_one_undo_step() {
|
||||
let mut s = Session::new();
|
||||
assert!(failure(&mut s, "app.paste();").contains("No active document"));
|
||||
log(&mut s, "app.copy(); app.cut();");
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let steps = s.active().unwrap().history.undo.len();
|
||||
// Nothing selected and the clipboard empty: nothing happens and no step is added.
|
||||
log(&mut s, "app.copy(); app.cut(); app.paste();");
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), steps);
|
||||
assert!(s.clipboard.is_empty());
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let steps = s.active().unwrap().history.undo.len();
|
||||
let out = log(&mut s, "app.copy(); app.paste(); app.paste(); vc.log(app.activeDocument.pageItems.length);");
|
||||
assert_eq!(out, vec![json!(3)]);
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), steps + 1);
|
||||
// A cut in a run that fails is put back.
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let steps = s.active().unwrap().history.undo.len();
|
||||
assert!(failure(&mut s, "app.cut(); throw new Error('stop');").contains("stop"));
|
||||
assert!(s.active().unwrap().doc.node(NodeId(a)).is_some());
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), steps);
|
||||
log(&mut s, "app.cut();");
|
||||
assert!(s.active().unwrap().doc.node(NodeId(a)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_copies_that_fill_the_clipboard_and_are_kept_are_counted() {
|
||||
let mut s = Session::new();
|
||||
s.clipboard_copied = true;
|
||||
s.note_copy();
|
||||
assert_eq!(s.copies, 0);
|
||||
assert!(!s.clipboard_copied);
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
assert_eq!(s.copies, 1);
|
||||
assert!(s.clipboard_copied);
|
||||
// A batch that copies and then fails puts the count back with the clipboard.
|
||||
s.execute("clipboard.importSvg", &json!({"svg": "<svg xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"5\" height=\"5\"/></svg>"})).unwrap();
|
||||
assert!(!s.clipboard_copied);
|
||||
let batch = json!({"commands": [{"command": "edit.copy", "params": {}}, {"command": "no.such", "params": {}}]});
|
||||
assert!(s.execute("command.batch", &batch).is_err());
|
||||
assert_eq!(s.copies, 1);
|
||||
assert!(!s.clipboard_copied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_or_cut_the_run_puts_back_is_not_reported() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
// The clipboard holds a copy from before the run.
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let copies = s.copies;
|
||||
// No command result reaches the script, so each command below is put back.
|
||||
crate::script::TEST_RESULT_BYTES.with(|b| b.set(Some(1)));
|
||||
let r = run(
|
||||
&mut s,
|
||||
"try { vc.run('command.batch', {commands: [{command: 'edit.copy', params: {}}]}); } catch (e) { vc.log(e.name); }\
|
||||
try { vc.run('edit.cut'); } catch (e) { vc.log(e.name); }\
|
||||
try { vc.run('edit.copy'); } catch (e) { vc.log(e.name); }\
|
||||
try { vc.run('artboard.copy', {indices: [0]}); } catch (e) { vc.log(e.name); }\
|
||||
try { vc.run('clipboard.importSvg', {svg: '<svg xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"5\" height=\"5\"/></svg>'}); }\
|
||||
catch (e) { vc.log(e.name); }",
|
||||
);
|
||||
crate::script::TEST_RESULT_BYTES.with(|b| b.set(None));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", "RangeError", "RangeError"]), "{r}");
|
||||
assert_eq!(r.get("copied"), None, "{r}");
|
||||
assert_eq!(s.copies, copies);
|
||||
assert!(s.clipboard_copied);
|
||||
assert!(s.active().unwrap().doc.node(NodeId(a)).is_some());
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,341 @@
|
||||
//! The script object model: a page item's `translate`, `rotate`, `resize` and `transform`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A 400 × 300 pt document with a 30 × 40 pt rectangle above a 50 × 50 pt one, so that `pageItems`
|
||||
/// (topmost first) lists the 30 × 40 pt one first.
|
||||
fn doc() -> (Session, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0);
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
(s, a, b)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The numbers of a logged array, or a logged number as one.
|
||||
fn numbers(v: &Value) -> Vec<f64> {
|
||||
match v.as_array() {
|
||||
Some(a) => a.iter().map(|n| n.as_f64().unwrap()).collect(),
|
||||
None => vec![v.as_f64().unwrap()],
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: &[f64], b: &[f64]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translate_moves_by_the_offsets_with_y_up_in_one_undo_step() {
|
||||
let (mut s, a, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0]; var l = i.left, t = i.top;\
|
||||
i.translate(10, 0); vc.log([i.left - l, i.top - t]);\
|
||||
i.translate(0, 10); vc.log([i.left - l, i.top - t]);\
|
||||
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var t2 = i.top;\
|
||||
i.translate(0, 5); vc.log(i.top - t2);",
|
||||
);
|
||||
assert!(close(&numbers(&out[0]), &[10.0, 0.0]), "{out:?}");
|
||||
assert!(close(&numbers(&out[1]), &[10.0, 10.0]), "{out:?}");
|
||||
// With Y down from the artboard's top, a move up reads as a smaller top.
|
||||
assert!(close(&numbers(&out[2]), &[-5.0]), "{out:?}");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.active().unwrap().doc.bounds_of(&[a], false).unwrap();
|
||||
assert!(close(&[r.x0, r.y0], &[10.0, 20.0]), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_turns_counterclockwise_about_the_center_or_the_named_point() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var g = app.activeDocument.pageItems[0], r = g.geometricBounds; vc.log(g.typename);\
|
||||
vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);\
|
||||
g.rotate(90); r = g.geometricBounds; vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);",
|
||||
);
|
||||
assert_eq!(out[0], json!("GroupItem"));
|
||||
let (before, after) = (numbers(&out[1]), numbers(&out[2]));
|
||||
// The width and height trade places, and the center stays.
|
||||
assert!(close(&after, &[before[1], before[0], before[2], before[3]]), "{before:?} {after:?}");
|
||||
|
||||
// A positive angle about the bottom-left corner swings a rectangle to the left of that corner.
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0]; vc.log(i.geometricBounds);\
|
||||
i.rotate(90, true, true, true, true, Transformation.BOTTOMLEFT); vc.log(i.geometricBounds);",
|
||||
);
|
||||
let (b0, b1) = (numbers(&out[0]), numbers(&out[1]));
|
||||
// [left, top, right, bottom], Y up: the 30 pt wide side now stands up, and the 40 pt tall side
|
||||
// lies to the left.
|
||||
assert!(close(&b1, &[b0[0] - 40.0, b0[3] + 30.0, b0[0], b0[3]]), "{b0:?} {b1:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_scales_about_the_center_and_line_widths_follow_their_argument() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, i = p[0], j = p[1];\
|
||||
function stroke(o) { return (o.visibleBounds[2] - o.visibleBounds[0]) - o.width; }\
|
||||
var r = i.geometricBounds, s0 = stroke(i); i.resize(50, 50); var q = i.geometricBounds;\
|
||||
vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3]), stroke(i) - s0]);\
|
||||
var s1 = stroke(j); j.resize(50, 50, true, true, true, true, 50); vc.log([s0, stroke(j) / s1]);",
|
||||
);
|
||||
let first = numbers(&out[0]);
|
||||
assert!(close(&first, &[15.0, 20.0, 0.0, 0.0, 0.0]), "{first:?}");
|
||||
let second = numbers(&out[1]);
|
||||
assert!(second[0] > 0.0, "the rectangles have a stroke: {second:?}");
|
||||
assert!(close(&second[1..], &[0.5]), "{second:?}");
|
||||
// On a path, any other line width sets the stroke weight to that percent of what it was.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0], w = i.strokeWidth; i.resize(50, 50, true, true, true, true, 70); vc.log(i.strokeWidth / w);",
|
||||
);
|
||||
assert!(close(&numbers(&out[0]), &[0.7]), "{out:?}");
|
||||
// On a group, a line width that is neither 100 nor the scale itself is refused.
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(50, 50, true, true, true, true, 70);");
|
||||
assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_applies_a_matrix_record_about_the_center() {
|
||||
let (mut s, _, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0], r = i.geometricBounds;\
|
||||
i.transform(app.getRotationMatrix(45)); var q = i.geometricBounds;\
|
||||
vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3])]);\
|
||||
var l = i.left; i.transform(app.getTranslationMatrix(5, 0)); vc.log(i.left - l);",
|
||||
);
|
||||
let side = 70.0 / 2f64.sqrt();
|
||||
assert!(close(&numbers(&out[0]), &[side, side, 0.0, 0.0]), "{out:?}");
|
||||
assert!(close(&numbers(&out[1]), &[5.0]), "{out:?}");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforms_that_change_nothing_add_no_undo_step() {
|
||||
let (mut s, _, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0]; i.translate(); i.translate(0, 0); i.rotate(0); i.rotate(360);\
|
||||
i.resize(100, 100); i.transform(app.getIdentityMatrix()); i.translate(10, 0, false, false, false, false);\
|
||||
i.translate(7000000, 0, false, false, false, false);\
|
||||
i.transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 100);",
|
||||
);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scale_whose_square_is_too_large_for_a_number_keeps_its_own_line_width() {
|
||||
let (mut s, _, _) = doc();
|
||||
let call = "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 70);";
|
||||
let e = failure(&mut s, call);
|
||||
assert!(e.contains("other than 100 or the scale itself"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_width_of_zero_is_not_the_scale_itself_however_small_the_scale() {
|
||||
let (mut s, _, _) = doc();
|
||||
let call = "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(1e-10), true, false, true, false, 0);";
|
||||
let e = failure(&mut s, call);
|
||||
assert!(e.contains("other than 100 or the scale itself"), "{e}");
|
||||
// A positive request still matches a tiny scale of its own.
|
||||
log(&mut s, "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(1e-10), true, false, true, false, 1e-10);");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_offset_past_the_canvas_is_taken_when_the_call_moves_nothing() {
|
||||
let (mut s, _, _) = doc();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
log(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0, false, false, false, false);");
|
||||
// The object uses no pattern, so moving patterns moves nothing either.
|
||||
log(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0, false, true, false, true);");
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(Infinity, 0, false, false, false, false);");
|
||||
assert!(e.contains("finite number"), "{e}");
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0);");
|
||||
assert!(e.contains("outside the canvas"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_too_small_to_round_away_moves_the_object() {
|
||||
let (mut s, _, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, "var i = app.activeDocument.pageItems[0], l = i.left; i.translate(5e-13, 0); vc.log(i.left > l);");
|
||||
assert_eq!(out, vec![json!(true)]);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiny_move_about_a_distant_center_moves_the_object() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
// The center is at x = 100, where 1e-15 rounds away; the left edge at 0 keeps it.
|
||||
rect(&mut s, 0.0, 0.0, 200.0, 10.0);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0], l = i.left;\
|
||||
i.transform({mValueA: 1, mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: 1e-15, mValueTY: 0}); vc.log(i.left > l);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scale_and_translation_about_the_center_straddle_the_origin() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 127, "y1": 0, "x2": 129, "y2": 0})).unwrap()["id"].as_u64().unwrap());
|
||||
log(
|
||||
&mut s,
|
||||
"app.activeDocument.pageItems[0].transform({mValueA: Math.pow(2, -55), mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: -128, mValueTY: 0});",
|
||||
);
|
||||
let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap();
|
||||
assert!(r.x0 < 0.0 && r.x1 > 0.0, "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clipped_object_moved_past_the_canvas_is_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let far = rect(&mut s, 0.9 * crate::MAX_COORD, 0.0, 10.0, 10.0);
|
||||
let mask = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [far.0, mask.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].translate({}, 0);", 0.2 * crate::MAX_COORD));
|
||||
assert!(e.contains("past the canvas"), "{e}");
|
||||
assert_eq!(s.active().unwrap().doc.node(far), before.node(far));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transformation_whose_bounds_reach_past_the_canvas_is_kept_when_the_art_does_not() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
// A diagonal line through the origin, 0.6 of the canvas limit out each way.
|
||||
let a = 0.6 * crate::MAX_COORD;
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": -a, "y1": a, "x2": a, "y2": -a})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
// On the page (Y down), x' = x + y about the center: the line becomes upright at x = 0, while
|
||||
// a corner of its bounds would go to 1.2 times the limit.
|
||||
log(
|
||||
&mut s,
|
||||
"var m = {mValueA: 1, mValueB: 0, mValueC: -1, mValueD: 1, mValueTX: 0, mValueTY: 0};\
|
||||
app.activeDocument.pageItems[0].transform(m);",
|
||||
);
|
||||
let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap();
|
||||
assert!(r.width() < 1e-6 && (r.height() - 2.0 * a).abs() < 1e-3, "{r:?}");
|
||||
// The same shear twice takes the line itself past the canvas.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
"var m = {mValueA: 1, mValueB: 0, mValueC: -2, mValueD: 1, mValueTX: 0, mValueTY: 0};\
|
||||
app.activeDocument.pageItems[0].transform(m);",
|
||||
);
|
||||
assert!(e.contains("past the canvas"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_art_and_art_on_a_locked_artboard_are_refused() {
|
||||
let (mut s, a, b) = doc();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
for call in ["translate(5, 0)", "rotate(30)", "resize(50, 50)", "transform(app.getScaleMatrix(200))"] {
|
||||
let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0]; i.locked = true; i.{call};"));
|
||||
assert!(e.contains(&format!("cannot transform locked objects: {}", a.0)), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
// A group that holds a locked object is refused too.
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
|
||||
let (before, steps) = (s.active().unwrap().doc.clone(), undo_steps(&s));
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(5, 0);");
|
||||
assert!(e.contains("cannot transform locked objects"), "{e}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[1].rotate(45);");
|
||||
assert!(e.contains("cannot transform objects on a locked artboard"), "{e}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arguments_throw_and_change_nothing() {
|
||||
let (mut s, _, _) = doc();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
for (call, says) in [
|
||||
("rotate('x')", "angle must be a finite number"),
|
||||
("rotate()", "angle must be a finite number"),
|
||||
("resize(50)", "scaleY must be a finite number"),
|
||||
("resize(0, 50)", "must not be 0"),
|
||||
("resize(50, 50, true, true, true, true, -1)", "changeLineWidths must not be negative"),
|
||||
("transform({})", "transformationMatrix must be a Matrix"),
|
||||
("transform(app.getScaleMatrix(0))", "singular"),
|
||||
("translate(1, 0, 'yes')", "transformObjects must be true or false"),
|
||||
("translate(7000000, 0)", "past the canvas"),
|
||||
("translate('x')", "deltaX must be a finite number"),
|
||||
("translate(NaN)", "is not a finite number"),
|
||||
("rotate(5, true, false, false)", "changeFillGradients different from changePositions"),
|
||||
("rotate(5, true, true, true, false)", "changeFillPatterns and changeStrokePattern"),
|
||||
// Left out, the stroke pattern follows the Transform Pattern Tiles preference (off), and
|
||||
// gradients default to true.
|
||||
("rotate(5, true, true)", "changeFillPatterns and changeStrokePattern"),
|
||||
("translate(10, 0, false)", "transformFillGradients different from transformObjects"),
|
||||
("rotate(5, true, true, true, true, 'Transformation.NOPE')", "Transformation value"),
|
||||
("rotate(5, true, true, true, true, 3)", "Transformation value"),
|
||||
("resize(1e9, 1e9)", "past the canvas"),
|
||||
// Stroke weights cannot scale while the object stays where it is.
|
||||
("resize(50, 50, false, false, false, false, 50)", "with changePositions false is not available yet"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};"));
|
||||
assert!(e.contains(says), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
// A deleted object is stale before its arguments are used.
|
||||
let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.rotate(10);");
|
||||
assert!(e.contains("Stale page item"), "{e}");
|
||||
}
|
||||
@@ -435,6 +435,29 @@ fn a_js_script_has_proxy_and_reflect_and_a_jsx_script_does_not() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them() {
|
||||
let dir = fresh_folder("es2017");
|
||||
let write = |name: &str, text: &str| {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, text).unwrap();
|
||||
p.to_string_lossy().into_owned()
|
||||
};
|
||||
let mut s = two_docs();
|
||||
let path = |p: &str| json!({"path": p});
|
||||
let src = "async function twice(p) { return 2 * await p; }\nvar half = async x => x / 2;\n\
|
||||
twice(Promise.resolve(3)).then(function (v) { vc.log(v); });\n\
|
||||
(async function () { try { await Promise.reject(new Error('no')); } catch (e) { vc.log(await half(8) + e.message); } })();\n\
|
||||
vc.log('sync');\n";
|
||||
let r = s.execute("script.run", &path(&write("async.js", src))).unwrap();
|
||||
assert_eq!(r["log"], json!(["sync", 6, "4no"]), "{r}");
|
||||
for (name, text) in [("async.jsx", "async function f() {}"), ("arrow.jsx", "var f = async x => x;")] {
|
||||
let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string();
|
||||
assert!(e.contains("SyntaxError"), "{name}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() {
|
||||
let dir = fresh_folder("es2020");
|
||||
|
||||
@@ -110,6 +110,25 @@ fn data_folder(s: &mut Session, base: &Path) -> PathBuf {
|
||||
PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_as_uses_the_supplied_alias_extension() {
|
||||
let base = folder("save-alias-format");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let target = dir.join("output.vectorcraft");
|
||||
let alias = dir.join("output.svg");
|
||||
std::fs::write(&target, "before").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &alias).unwrap();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&alias)));
|
||||
let svg = std::fs::read_to_string(&target).unwrap();
|
||||
assert!(svg.contains("<svg"), "{svg}");
|
||||
assert!(std::fs::symlink_metadata(&alias).unwrap().file_type().is_symlink());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
fn quoted(p: &Path) -> String {
|
||||
serde_json::to_string(&p.to_string_lossy()).unwrap()
|
||||
}
|
||||
@@ -157,6 +176,66 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_file_logs_encoder_warnings() {
|
||||
let base = folder("export-warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let text = format!(
|
||||
"Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\
|
||||
d.pathItems[0].name = 'invalid\\u0001name';\
|
||||
vc.log(String(d.exportFile(new File({}), ExportType.SVG)));",
|
||||
quoted(&dir.join("warnings.svg"))
|
||||
);
|
||||
let r = run(&mut s, &base, &text).unwrap();
|
||||
assert_eq!(r["log"], json!(["undefined"]));
|
||||
assert!(dir.join("warnings.svg").is_file());
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
let warning = "exportFile: Object names containing invalid XML characters were left out of SVG name attributes";
|
||||
assert!(lines.iter().any(|line| line.as_str() == Some(warning)), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The warnings of the save go to the console, and `saveAs` still returns nothing.
|
||||
#[test]
|
||||
fn save_as_logs_the_saves_warnings() {
|
||||
let base = folder("warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let d = quoted(&dir);
|
||||
let text = format!(
|
||||
"Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
|
||||
vc.log(String(d.saveAs(new File({d} + '/a.svg'))));"
|
||||
);
|
||||
let r = run(&mut s, &base, &text).unwrap_or_else(|e| panic!("{text}: {e}"));
|
||||
assert_eq!(r["log"], json!(["undefined"]));
|
||||
let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default();
|
||||
let warned = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ") && l.contains("keeps the artwork"));
|
||||
assert!(warned, "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_logs_warnings_for_an_unreadable_linked_image() {
|
||||
let base = folder("open-warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let svg = dir.join("missing-image.svg");
|
||||
std::fs::write(
|
||||
&svg,
|
||||
"<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='50' height='50'>\
|
||||
<image width='10' height='10' xlink:href='missing.png'/></svg>",
|
||||
)
|
||||
.unwrap();
|
||||
let text = format!("Folder.userData; var d = app.open(new File({})); vc.log(d.typename);", quoted(&svg));
|
||||
let r = run(&mut s, &base, &text).unwrap();
|
||||
assert_eq!(r["log"], json!(["Document"]));
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("open: ") && l.contains("missing.png")), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_saved_paths_use_the_process_working_directory() {
|
||||
let cwd = crate::cmd::findfiles::plain(std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap());
|
||||
@@ -276,6 +355,39 @@ fn omitted_options_are_a_new_options_objects_defaults() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// White, the default `matteColor` of `ExportOptionsPNG24` and `ExportOptionsJPEG`, is accepted, and
|
||||
/// another color is refused.
|
||||
#[test]
|
||||
fn a_white_matte_color_is_the_default() {
|
||||
let base = folder("matte");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let d = quoted(&dir);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100), c = new RGBColor();\n\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); c.red = 255; c.green = 255; c.blue = 255;\n\
|
||||
var p = new ExportOptionsPNG24(); p.matteColor = c; d.exportFile(new File(dir + '/p'), ExportType.PNG24, p);\n\
|
||||
var j = new ExportOptionsJPEG(); j.matteColor = c; d.exportFile(new File(dir + '/j'), ExportType.JPEG, j);"
|
||||
),
|
||||
);
|
||||
assert!(dir.join("p.png").exists() && dir.join("j.jpg").exists());
|
||||
for (class, kind) in [("ExportOptionsPNG24", "PNG24"), ("ExportOptionsJPEG", "JPEG")] {
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var c = new RGBColor(); c.red = 255; c.green = 0; c.blue = 255; var o = new {class}(); o.matteColor = c;\
|
||||
app.activeDocument.exportFile(new File({d} + '/x'), ExportType.{kind}, o);"
|
||||
),
|
||||
);
|
||||
assert!(e.contains("matteColor"), "{class}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A new `IllustratorSaveOptions` reads `compatibility` as its default, ILLUSTRATOR19, and saves
|
||||
/// with it untouched.
|
||||
#[test]
|
||||
@@ -462,9 +574,37 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() {
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(&board, perms).unwrap();
|
||||
// A folder where an artboard's file goes writes none of them either.
|
||||
std::fs::remove_file(&board).unwrap();
|
||||
std::fs::create_dir(&board).unwrap();
|
||||
let e = failure(&mut s, &base, &save);
|
||||
assert!(e.contains("not a file"), "{e}");
|
||||
assert!(!central.exists(), "the central file is not written when a folder is where an artboard's file goes");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An export that writes several files writes none of them when a folder is where one of them goes.
|
||||
#[test]
|
||||
fn an_export_writes_nothing_when_a_folder_is_where_one_of_its_files_goes() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("export-folder-target");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let path = dir.join("a.eps").to_string_lossy().into_owned();
|
||||
let export = json!({"path": path, "format": "eps", "useArtboards": true});
|
||||
let r = s.execute("document.export", &export).unwrap();
|
||||
let files: Vec<PathBuf> =
|
||||
r["files"].as_array().unwrap_or_else(|| panic!("several files: {r}")).iter().map(|f| PathBuf::from(f.as_str().unwrap())).collect();
|
||||
assert!(files.len() > 1, "{r}");
|
||||
for f in &files {
|
||||
std::fs::remove_file(f).unwrap();
|
||||
}
|
||||
std::fs::create_dir(files.last().unwrap()).unwrap();
|
||||
let e = s.execute("document.export", &export).unwrap_err().to_string();
|
||||
assert!(e.contains("not a file"), "{e}");
|
||||
assert!(files[..files.len() - 1].iter().all(|f| !f.exists()), "no file is written when a folder is where one goes");
|
||||
}
|
||||
|
||||
/// When the writer a save is given does not check the file access itself, a save of several files
|
||||
/// whose file access refuses one of them hands none of them to the writer.
|
||||
#[test]
|
||||
@@ -644,6 +784,34 @@ fn open_reads_linked_files_only_where_the_script_may() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A file an open document links to is read by `open` only where the script may read, too.
|
||||
#[test]
|
||||
fn open_reads_files_open_documents_link_to_only_where_the_script_may() {
|
||||
let base = folder("linked-by-open");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let pic = base.join("outside/linked.png");
|
||||
std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": true})).unwrap();
|
||||
let href = pic.to_string_lossy().replace('\\', "/").replace('&', "&").replace('<', "<").replace('\'', "'");
|
||||
std::fs::write(
|
||||
dir.join("page.svg"),
|
||||
format!("<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='50' height='50'><image x='0' y='0' width='10' height='10' xlink:href='{href}'/></svg>"),
|
||||
)
|
||||
.unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&dir.join("page.svg"))));
|
||||
let mut sizes = vec![];
|
||||
s.active().unwrap().doc.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
sizes.push((im.width, im.height));
|
||||
}
|
||||
});
|
||||
assert_eq!(sizes.len(), 1, "{sizes:?}");
|
||||
assert_ne!(sizes[0], (2, 2), "the linked file outside the script's folders is not read");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An SVG export with `embedRasterImages` false writes the document's embedded image beside the
|
||||
/// SVG, and when that file may not be written, the SVG is not written either.
|
||||
#[test]
|
||||
|
||||
@@ -37,6 +37,11 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
|
||||
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
|
||||
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
|
||||
("Preferences.prototype.setBooleanPreference", "app.preferences.setBooleanPreference(k, true);", "preferences"),
|
||||
("Preferences.prototype.setIntegerPreference", "app.preferences.setIntegerPreference(k, 1);", "preferences"),
|
||||
("Preferences.prototype.setRealPreference", "app.preferences.setRealPreference(k, 0.5);", "preferences"),
|
||||
("Preferences.prototype.setStringPreference", "app.preferences.setStringPreference(k, s);", "preferences"),
|
||||
("Preferences.prototype.removePreference", "app.preferences.removePreference(k);", "preferences"),
|
||||
("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"),
|
||||
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
|
||||
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
|
||||
@@ -50,7 +55,11 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// change anything outside it. The document model (`app`, its classes and the enumerations) acts on
|
||||
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
|
||||
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
|
||||
/// `Document.path` only name its file and folder. `app.open` reads the file it is given.
|
||||
/// `Document.path` only name its file and folder. `app.open` reads the file it is given, and
|
||||
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. Reading a
|
||||
/// preference changes nothing, and the matrix functions return new records. `app.copy` and `app.cut`
|
||||
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit ›
|
||||
/// Copy does.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "alert confirm length prompt prototype"),
|
||||
@@ -89,18 +98,23 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"",
|
||||
"activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
|
||||
DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \
|
||||
Documents ElementPlacement Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType \
|
||||
PolarityValues RulerUnits ScreenMode selection selection= StrokeCap StrokeJoin Tag Tags Transformation View Views \
|
||||
ZOrderMethod",
|
||||
Documents ElementPlacement Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PlacedItem \
|
||||
PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \
|
||||
selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= open PPDFileList printPresetsList printerList redo redraw \
|
||||
selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \
|
||||
"activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \
|
||||
executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \
|
||||
invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \
|
||||
printerList redo redraw selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= \
|
||||
userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
),
|
||||
("Preferences.", "prototype"),
|
||||
("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
"DocumentPreset.prototype.",
|
||||
@@ -120,8 +134,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
|
||||
groupItems= height layers layers= name pageItems paragraphStyles parent path pathItems rulerOrigin \
|
||||
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
|
||||
groupItems= height layers layers= name pageItems paragraphStyles parent path pathItems placedItems rasterItems \
|
||||
rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
@@ -138,20 +152,51 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"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 toString top top= transform \
|
||||
transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
|
||||
position= remove resize rotate selected selected= sliced sliced= tags toString top top= transform translate \
|
||||
typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
|
||||
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
|
||||
),
|
||||
("PlacedItems.", "prototype"),
|
||||
("PlacedItems.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("PlacedItem.", "prototype"),
|
||||
("PlacedItem.prototype.", "boundingBox constructor contentVariable contentVariable= embed file file= matrix matrix= relink trace"),
|
||||
("PluginItem.", "prototype"),
|
||||
("PluginItem.prototype.", "constructor isTracing tracing"),
|
||||
("RasterItems.", "prototype"),
|
||||
("RasterItems.prototype.", "constructor getByName index length parent removeAll typename"),
|
||||
("RasterItem.", "prototype"),
|
||||
(
|
||||
"RasterItem.prototype.",
|
||||
"bitsPerChannel boundingBox channels colorants colorants= colorize colorize= colorizedGrayscale constructor \
|
||||
contentVariable contentVariable= embedded embedded= file imageColorSpace matrix matrix= overprint overprint= status \
|
||||
trace transparent",
|
||||
),
|
||||
("TracingObject.", "prototype"),
|
||||
(
|
||||
"TracingObject.prototype.",
|
||||
"anchorCount areaCount areaCount= constructor expandTracing imageResolution parent pathCount releaseTracing sourceArt \
|
||||
tracingOptions typename usedColorCount",
|
||||
),
|
||||
("TracingOptions.", "prototype"),
|
||||
(
|
||||
"TracingOptions.prototype.",
|
||||
"constructor cornerAngle cornerAngle= fills fills= ignoreWhite ignoreWhite= livePaintOutput livePaintOutput= \
|
||||
loadFromPreset maxColors maxColors= maxStrokeWeight maxStrokeWeight= minArea minArea= minStrokeLength \
|
||||
minStrokeLength= outputToSwatches outputToSwatches= palette palette= parent pathFitting pathFitting= \
|
||||
preprocessBlur preprocessBlur= preset resample resample= resampleResolution resampleResolution= storeToPreset \
|
||||
strokes strokes= threshold threshold= tracingMode tracingMode= typename viewRaster viewRaster= viewVector \
|
||||
viewVector=",
|
||||
),
|
||||
("PathItems.", "prototype"),
|
||||
("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"),
|
||||
("PathItem.", "prototype"),
|
||||
(
|
||||
"PathItem.prototype.",
|
||||
"area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \
|
||||
filled= guides guides= length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \
|
||||
filled= guides guides= length pathPoints polarity polarity= resolution resolution= selectedPathPoints \
|
||||
setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \
|
||||
strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \
|
||||
strokeWidth strokeWidth= stroked stroked= translate",
|
||||
strokeWidth strokeWidth= stroked stroked=",
|
||||
),
|
||||
("PathPoints.", "prototype"),
|
||||
("PathPoints.prototype.", "add constructor index length parent removeAll typename"),
|
||||
@@ -243,6 +288,19 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
|
||||
("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"),
|
||||
("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"),
|
||||
// The enumerations of placed and raster items.
|
||||
("", "ImageColorSpace RasterLinkState"),
|
||||
("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"),
|
||||
("RasterLinkState.", "DATAFROMFILE DATAMODIFIED NODATA"),
|
||||
// The enumerations of tracings.
|
||||
("", "TracingModeType ViewRasterType ViewVectorType"),
|
||||
("TracingModeType.", "TRACINGMODEBLACKANDWHITE TRACINGMODECOLOR TRACINGMODEGRAY"),
|
||||
("ViewRasterType.", "TRACINGVIEWRASTERADJUSTEDIMAGE TRACINGVIEWRASTERNOIMAGE TRACINGVIEWRASTERORIGINALIMAGE TRACINGVIEWRASTERTRANSPARENTIMAGE"),
|
||||
(
|
||||
"ViewVectorType.",
|
||||
"TRACINGVIEWVECTORNOTRACINGRESULT TRACINGVIEWVECTOROUTLINES TRACINGVIEWVECTOROUTLINESWITHTRACING \
|
||||
TRACINGVIEWVECTORTRACINGRESULT",
|
||||
),
|
||||
// The print option classes and the enumerations of printing.
|
||||
(
|
||||
"",
|
||||
@@ -455,11 +513,11 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
];
|
||||
|
||||
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
|
||||
/// other than `PathItem`, the color classes, and the save and export option classes.
|
||||
/// other than `PathItem`, `PlacedItem` and `RasterItem`, the color classes and the save and export
|
||||
/// option classes.
|
||||
const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \
|
||||
IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \
|
||||
SymbolItem cmykColor EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \
|
||||
PDFSaveOptions";
|
||||
IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem \
|
||||
cmykColor EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions";
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -135,6 +135,12 @@ pub struct Imported {
|
||||
pub preview: bool,
|
||||
}
|
||||
|
||||
/// `img` as a PNG with fast compression, which keeps opening a file with large images quick.
|
||||
pub(crate) fn png(img: &craft_image_codecs::Image) -> Option<Vec<u8>> {
|
||||
let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
|
||||
craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok()
|
||||
}
|
||||
|
||||
/// The DSC comments the reader uses.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct Dsc {
|
||||
|
||||
@@ -648,7 +648,7 @@ impl<'a> Reader<'a> {
|
||||
self.image_left_out("an image VectorCraft can't read was left out");
|
||||
return Ok(());
|
||||
};
|
||||
let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else {
|
||||
let Some(png) = crate::import::png(&img) else {
|
||||
self.image_left_out("an image VectorCraft can't read was left out");
|
||||
return Ok(());
|
||||
};
|
||||
@@ -678,7 +678,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
let written = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray)
|
||||
.ok()
|
||||
.and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok());
|
||||
.and_then(|img| crate::import::png(&img));
|
||||
let Some(png) = written else {
|
||||
self.image_left_out("an image VectorCraft can't read was left out");
|
||||
return Ok(());
|
||||
@@ -778,7 +778,7 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
craft_image_codecs::Image::from_raw(ow, oh, layout, craft_image_codecs::SampleType::U8, pixels)
|
||||
.ok()
|
||||
.and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok())
|
||||
.and_then(|img| crate::import::png(&img))
|
||||
.map(|png| ImageBlob::new("image/png", png))
|
||||
};
|
||||
// One that can't be encoded is left to the page's art, as one past the hard limits.
|
||||
@@ -870,7 +870,7 @@ impl<'a> Reader<'a> {
|
||||
let raw =
|
||||
craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec())
|
||||
.ok()?;
|
||||
let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
|
||||
let png = crate::import::png(&raw)?;
|
||||
let blob = ImageBlob::new("image/png", png);
|
||||
let key = blob.content_key();
|
||||
self.doc.images.entry(key.clone()).or_insert(blob);
|
||||
@@ -1224,7 +1224,7 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec<u8>, u32, u32)> {
|
||||
}
|
||||
let raw =
|
||||
craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?;
|
||||
let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
|
||||
let png = crate::import::png(&raw)?;
|
||||
Some((png, width, height))
|
||||
}
|
||||
|
||||
|
||||
@@ -3154,6 +3154,35 @@ fn a_reduced_separation_image_keeps_its_ink_and_its_alpha_as_a_mask() {
|
||||
assert!(r.doc.images[&im.key].gray_source().is_some_and(|g| !g.alpha), "no alpha in the pixels");
|
||||
}
|
||||
|
||||
/// Images come in as PNGs written with fast compression, which keeps a file with large images
|
||||
/// quick to open: an RGB image with an alpha channel, and a Separation image with its opacity
|
||||
/// mask, at full size and reduced to fit the limits.
|
||||
#[test]
|
||||
fn images_and_their_masks_are_stored_with_fast_compression() {
|
||||
let pngs = |doc: &Document| {
|
||||
let fast = |n: &Node| {
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("{:?}", n.kind) };
|
||||
let blob = &doc.images[&im.key];
|
||||
assert_eq!(blob.mime, "image/png");
|
||||
crate::import::tests::fastest_png(&blob.bytes)
|
||||
};
|
||||
let a = art(doc);
|
||||
let mut out = vec![fast(&a[0])];
|
||||
out.extend(a[0].extras().mask.as_ref().map(|m| fast(&m.art)));
|
||||
out
|
||||
};
|
||||
let rgb = image("[ 10 0 0 10 50 90 ]", (2, 1), ("DeviceRGB", 3, 1), &[255, 0, 0, 0, 255, 0, 255, 128], 10);
|
||||
assert_eq!(pngs(&read(&rgb).unwrap().doc), [true], "the RGB image");
|
||||
let black = "1 [0 0 0 1 /DeviceCMYK (Black Ink) /Separation]";
|
||||
let ink = ink_image(black, 8, 1, 2, &[0, 255, 255, 64]);
|
||||
assert_eq!(pngs(&read(&ink).unwrap().doc), [true, true], "the Separation image and its mask");
|
||||
let samples = [255u8; 16].iter().chain([0u8; 16].iter()).copied().collect::<Vec<_>>();
|
||||
let ink = ink_image(black, 8, 1, 16, &samples);
|
||||
let r = super::with_image_limits(4, 1 << 31, 512 << 20, || read(&ink).unwrap());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("was reduced")), "{:?}", r.warnings);
|
||||
assert_eq!(pngs(&r.doc), [true, true], "the reduced Separation image and its mask");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_with_alpha_channels() {
|
||||
// RGB samples, then the alpha channel (not counted in the data's size).
|
||||
|
||||
@@ -1157,7 +1157,7 @@ impl Interp<'_> {
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let Ok(png) = craft_image_codecs::encode(&rgba, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else {
|
||||
let Some(png) = crate::import::png(&rgba) else {
|
||||
self.out.warn("an image that couldn't be read was left out");
|
||||
return Ok(());
|
||||
};
|
||||
@@ -1184,7 +1184,7 @@ impl Interp<'_> {
|
||||
let raw =
|
||||
craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec())
|
||||
.ok()?;
|
||||
let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
|
||||
let png = crate::import::png(&raw)?;
|
||||
let blob = ImageBlob::new("image/png", png);
|
||||
let key = blob.content_key();
|
||||
self.out.doc.images.entry(key.clone()).or_insert(blob);
|
||||
|
||||
@@ -46,7 +46,7 @@ fn image_doc(img: image::RgbaImage, frame: Rect) -> Option<Document> {
|
||||
}
|
||||
let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw())
|
||||
.ok()?;
|
||||
let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
|
||||
let png = super::png(&raw)?;
|
||||
let mut doc = Document::new(frame.width(), frame.height());
|
||||
let blob = ImageBlob::new("image/png", png);
|
||||
let key = blob.content_key();
|
||||
|
||||
@@ -208,6 +208,19 @@ fn arrays_and_dictionaries_holding_themselves_are_freed() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2,
|
||||
/// FLEVEL 0).
|
||||
pub(super) fn fastest_png(png: &[u8]) -> bool {
|
||||
let mut at = 8;
|
||||
while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) {
|
||||
if kind == b"IDAT" {
|
||||
return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0);
|
||||
}
|
||||
at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize;
|
||||
}
|
||||
panic!("a PNG with image data: {png:?}");
|
||||
}
|
||||
|
||||
/// The objects of the document's layer.
|
||||
pub(super) fn objects(d: &Document) -> Vec<Arc<Node>> {
|
||||
d.layers[0].children().unwrap().clone()
|
||||
|
||||
@@ -14,7 +14,7 @@ use vectorcraft_doc::cmyk::Inks;
|
||||
use vectorcraft_doc::{ImageBlob, Node, NodeKind};
|
||||
|
||||
use super::import;
|
||||
use super::tests::{all, eps, read};
|
||||
use super::tests::{all, eps, fastest_png, read};
|
||||
use super::tests_generators::pixel;
|
||||
|
||||
/// Each pixel of the first image, row by row.
|
||||
@@ -223,6 +223,24 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() {
|
||||
assert!(first_image(&r).extras().mask.is_none());
|
||||
}
|
||||
|
||||
/// Images come in as PNGs written with fast compression, which keeps a file with large images
|
||||
/// quick to open: an RGB image, and the opacity mask of a masked CMYK image.
|
||||
#[test]
|
||||
fn images_and_their_masks_are_stored_with_fast_compression() {
|
||||
let r = read("30 20 scale 3 2 8 [3 0 0 -2 0 2] <ff0000102030> <00ff00405060> <0000ff708090> true 3 colorimage");
|
||||
let b = blob(&r, &first_image(&r));
|
||||
assert_eq!(b.mime, "image/png");
|
||||
assert!(fastest_png(&b.bytes), "the RGB image");
|
||||
let r = read(
|
||||
"/DeviceCMYK setcolorspace 30 20 scale << /ImageType 4 /Width 2 /Height 1 /BitsPerComponent 8 /Decode [0 1 0 1 0 1 0 1] \
|
||||
/ImageMatrix [2 0 0 -1 0 1] /DataSource <0a141e28 00667f08> /MaskColor [10 20 30 40] >> image",
|
||||
);
|
||||
let n = first_image(&r);
|
||||
let mask = blob(&r, &n.extras().mask.as_ref().expect("an opacity mask").art);
|
||||
assert_eq!(mask.mime, "image/png");
|
||||
assert!(fastest_png(&mask.bytes), "the opacity mask");
|
||||
}
|
||||
|
||||
/// A CMYK JPEG gives its samples as stored, for the Decode array to read: Adobe's inverted
|
||||
/// samples with `[1 0 1 0 1 0 1 0]`, the ink amounts themselves with `[0 1 0 1 0 1 0 1]`.
|
||||
#[test]
|
||||
|
||||
@@ -118,6 +118,14 @@ pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool {
|
||||
/// filled shape doesn't touch it, so a marquee drawn over a background picks only what is on it
|
||||
/// (#1103).
|
||||
pub fn intersects_rect(path: &PathData, r: Rect) -> bool {
|
||||
// The control box holds every anchor and segment, and the path keeps it measured, so a path
|
||||
// whose control box lies wholly apart from the rect misses it without measuring its segments.
|
||||
// The test is strict: a control box that only touches the rect, or has no area, goes on to the
|
||||
// exact checks below.
|
||||
let (Some(c), n) = (path.control_bounds(), r.abs()) else { return false };
|
||||
if c.x1 < n.x0 || n.x1 < c.x0 || c.y1 < n.y0 || n.y1 < c.y0 {
|
||||
return false;
|
||||
}
|
||||
let Some(b) = path.bounds() else { return false };
|
||||
let degenerate = |x: Rect| x.width() == 0.0 || x.height() == 0.0;
|
||||
if b.intersect(r).area() <= 0.0 && !degenerate(b) && !degenerate(r) {
|
||||
@@ -238,6 +246,30 @@ mod tests {
|
||||
// zero-height marquee missing it
|
||||
assert!(!intersects_rect(&p, Rect::new(20.0, 5.0, 30.0, 5.0)));
|
||||
}
|
||||
|
||||
/// A marquee that lies apart from a path's control box misses it without measuring the path's
|
||||
/// segments. One that reaches the control box but not the curve is still judged on the curve.
|
||||
#[test]
|
||||
fn marquee_apart_from_the_control_box_measures_no_segment() {
|
||||
let p = shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let measured = crate::path::measured_segments;
|
||||
let before = measured();
|
||||
assert!(!intersects_rect(&p, Rect::new(20.0, 20.0, 30.0, 30.0)));
|
||||
assert!(!intersects_rect(&p, Rect::new(-30.0, 4.0, -20.0, 6.0)));
|
||||
assert_eq!(measured(), before, "a marquee apart from the control box measures nothing");
|
||||
// A curve whose handle reaches into the marquee while the curve stays below it.
|
||||
use crate::path::{Anchor, SubPath};
|
||||
let arch = PathData::new(vec![SubPath::new(
|
||||
vec![
|
||||
Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 40.0)),
|
||||
Anchor::with_handles(Point::new(10.0, 0.0), Point::new(10.0, 40.0), Point::new(10.0, 0.0)),
|
||||
],
|
||||
false,
|
||||
)]);
|
||||
assert!(!intersects_rect(&arch, Rect::new(-1.0, 35.0, 11.0, 39.0)), "the curve peaks at y 30");
|
||||
assert!(measured() > before, "a marquee inside the control box measures the curve");
|
||||
assert!(intersects_rect(&arch, Rect::new(4.0, 25.0, 6.0, 35.0)), "a marquee across the peak");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -238,6 +238,8 @@ pub enum Expr {
|
||||
/// `...expression` in an array literal or an argument list, and as the last of an arrow
|
||||
/// function's parenthesized parameters while they are read.
|
||||
Spread(ExprId),
|
||||
/// `await operand`, in an async function's body.
|
||||
Await(ExprId),
|
||||
/// An optional chain (`a?.b.c`, `a?.[k]`, `f?.()`): its accesses and calls, the
|
||||
/// [`Expr::Optional`] steps among them included. It is `undefined` when one of those steps
|
||||
/// finds `undefined` or `null`, and the rest of the chain is skipped.
|
||||
@@ -502,6 +504,8 @@ pub struct Function {
|
||||
pub strict: bool,
|
||||
/// A generator function (`function*`, or `*name() {…}` in an object literal).
|
||||
pub generator: bool,
|
||||
/// An async function (ECMAScript 2017): a call returns a promise, and its body may `await`.
|
||||
pub is_async: bool,
|
||||
pub span: Span,
|
||||
/// The function is defined in a class body (a method, an accessor or the constructor): it has
|
||||
/// a home object for `super.property`.
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
//! Async functions and `await` in realms with [`Options::es2017`].
|
||||
|
||||
use super::*;
|
||||
|
||||
fn realm() -> Realm {
|
||||
Realm::with_options(Options { es2017: true, ..Options::default() }, Limits::default())
|
||||
}
|
||||
|
||||
/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran.
|
||||
fn log(src: &str) -> String {
|
||||
let mut r = realm();
|
||||
if let Err(e) = r.run(&format!("var log = [];\n{src}")) {
|
||||
panic!("{src}\n{e:?}");
|
||||
}
|
||||
match r.run("log.join(' ')") {
|
||||
Ok(JsValue::String(s)) => s,
|
||||
other => panic!("{src}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn syntax_error(r: &mut Realm, src: &str) {
|
||||
match r.run(src) {
|
||||
Err(e) if e.kind == RunErrorKind::Syntax => {}
|
||||
other => panic!("{src}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn awaits_resume_in_the_job_order_promise_reactions_have() {
|
||||
let src = "async function f() { log.push('f1'); await null; log.push('f2'); await null; log.push('f3'); }\n\
|
||||
f();\n\
|
||||
Promise.resolve().then(function () { log.push('t1'); }).then(function () { log.push('t2'); });\n\
|
||||
log.push('sync');";
|
||||
assert_eq!(log(src), "f1 sync f2 t1 f3 t2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_function_returns_a_promise_its_return_resolves_and_its_throw_rejects() {
|
||||
let src = "async function ok(x) { return x + 1; }\n\
|
||||
async function bad() { throw new TypeError('no'); }\n\
|
||||
var p = ok(1); log.push(p instanceof Promise);\n\
|
||||
p.then(function (v) { log.push('ok ' + v); });\n\
|
||||
bad().then(null, function (e) { log.push(e instanceof TypeError); });";
|
||||
assert_eq!(log(src), "true ok 2 true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_await_throws_where_it_stands_and_finally_runs_after_an_await() {
|
||||
let src = "async function f() {\n\
|
||||
try { await Promise.reject('r'); log.push('not here'); }\n\
|
||||
catch (e) { log.push('caught ' + e); }\n\
|
||||
finally { await 1; log.push('finally'); }\n\
|
||||
return 'end';\n\
|
||||
}\n\
|
||||
f().then(function (v) { log.push(v); });";
|
||||
assert_eq!(log(src), "caught r finally end");
|
||||
let rethrow = "async function g() { try { await Promise.reject(new Error('x')); } finally { log.push('cleanup'); } }\n\
|
||||
g().catch(function (e) { log.push('rejected ' + e.message); });";
|
||||
assert_eq!(log(rethrow), "cleanup rejected x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_expressions_and_methods_can_be_async() {
|
||||
let src = "var a = async x => (await x) * 2;\n\
|
||||
var b = async (x, y) => { return await x + y; };\n\
|
||||
var c = async function named() { return typeof named; };\n\
|
||||
var o = { async m(v) { return this.k + await v; }, k: 'k' };\n\
|
||||
Promise.all([a(2), b(Promise.resolve(1), 2), c(), o.m('v')]).then(function (r) { log.push(r.join(',')); });";
|
||||
assert_eq!(log(src), "4,3,function,kv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comma_may_follow_an_arrow_functions_last_parameter_but_not_a_rest_parameter() {
|
||||
let src = "var f = async (x,) => x; var g = async (x, ...xs) => xs.length; var h = (a, b,) => a + b;\n\
|
||||
var async = function () { return arguments.length; }; log.push(async(...[1, 2],));\n\
|
||||
Promise.all([f(1), g(1, 2, 3), h(1, 2), h.length]).then(function (r) { log.push(r.join(',')); });";
|
||||
assert_eq!(log(src), "2 1,2,3,2");
|
||||
let mut r = realm();
|
||||
for src in ["async (...xs,) => xs", "async (a, ...xs,) => xs", "(...xs,) => xs", "(a, ...xs,) => xs", "(a,);", "(a, b,);"] {
|
||||
syntax_error(&mut r, src);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_functions_are_not_constructors_and_have_no_prototype() {
|
||||
let src = "async function f() {}\n\
|
||||
log.push(f.hasOwnProperty('prototype'));\n\
|
||||
try { new f(); } catch (e) { log.push(e instanceof TypeError); }\n\
|
||||
var AF = Object.getPrototypeOf(f).constructor;\n\
|
||||
log.push(AF !== Function, typeof AF, Object.getPrototypeOf(AF) === Function);\n\
|
||||
log.push(typeof this.AsyncFunction);\n\
|
||||
var g = AF('a', 'return await a;');\n\
|
||||
log.push(Object.getPrototypeOf(g) === Object.getPrototypeOf(f));\n\
|
||||
g(5).then(function (v) { log.push(v); });\n\
|
||||
log.push(String(async function h() { await 0; }));";
|
||||
assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_construct_rejects_an_async_function_as_new_target() {
|
||||
let src = "async function f() {}\n\
|
||||
var ran = false;\n\
|
||||
function C() { ran = true; }\n\
|
||||
try { Reflect.construct(C, [], f); } catch (e) { log.push(e instanceof TypeError); }\n\
|
||||
log.push(ran);\n\
|
||||
try { Reflect.construct(C, [], new Proxy(f, {})); } catch (e) { log.push(e instanceof TypeError); }";
|
||||
assert_eq!(log(src), "true false true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_function_inherits_from_the_built_in_function_after_a_script_replaced_its_constructor() {
|
||||
let mut r = Realm::new();
|
||||
assert_eq!(r.run("Function.prototype.constructor = {}; 0"), Ok(JsValue::Number(0.0)));
|
||||
r.add_es2015();
|
||||
r.set_es2017(true);
|
||||
let src = "var AF = Object.getPrototypeOf(async function () {}).constructor; Object.getPrototypeOf(AF) === Function && typeof AF.call";
|
||||
assert_eq!(r.run(src), Ok(JsValue::String("function".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_e4x_async_before_a_double_colon_is_a_qualified_name() {
|
||||
let options = Options { es2017: true, e4x: true, ..Options::default() };
|
||||
assert!(parse("async::b", &options).is_ok());
|
||||
let mut r = Realm::with_options(options, Limits::default());
|
||||
let src = "var async = new Namespace('u'); var x = <a xmlns:p='u'><p:b>7</p:b><b>8</b></a>; String(x.async::b)";
|
||||
assert_eq!(r.run(src), Ok(JsValue::String("7".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn await_is_an_identifier_outside_async_functions() {
|
||||
let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\
|
||||
var async = function (x) { return x; }; log.push(async(1));\n\
|
||||
async\nfunction g() {}\n\
|
||||
log.push(typeof g);";
|
||||
assert_eq!(log(src), "3 1 function");
|
||||
// A function in an async arrow function's parameters reads `await` as its own body does,
|
||||
// and an async function declared in a script may be named `await`.
|
||||
let nested = "var g = async (x = function () { return await; }) => x;\n\
|
||||
var h = async (x = async function () { await 0; }) => x;\n\
|
||||
async function await() { return 1; }\n\
|
||||
log.push(typeof g, typeof h, typeof await);";
|
||||
assert_eq!(log(nested), "function function function");
|
||||
// An arrow function in an async arrow function's parameters reads `await` as its own body does.
|
||||
let arrow = "var await = 7; var f = async (cb = () => await) => cb(); f().then(function (v) { log.push(v); });";
|
||||
assert_eq!(log(arrow), "7");
|
||||
let mut r = realm();
|
||||
syntax_error(&mut r, "async function f() { var await; }");
|
||||
syntax_error(&mut r, "async function f(await) {}");
|
||||
syntax_error(&mut r, "async function f(x = await 1) {}");
|
||||
syntax_error(&mut r, "function f() { await 1; }");
|
||||
syntax_error(&mut r, "if (1) async function f() {}");
|
||||
syntax_error(&mut r, "async (x = await 1) => x");
|
||||
syntax_error(&mut r, "async\n(x) => x");
|
||||
syntax_error(&mut r, "async (a = (...await) => {}) => {}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suspended_function_survives_a_collection_and_an_unreachable_one_is_freed() {
|
||||
let mut r = realm();
|
||||
r.run(
|
||||
"var resume; var gate = new Promise(function (res) { resume = res; });\n\
|
||||
var out = [];\n\
|
||||
async function f() { var local = { n: 41 }; var v = await gate; out.push(local.n + v); }\n\
|
||||
f();",
|
||||
)
|
||||
.unwrap();
|
||||
r.interp().collect_garbage();
|
||||
r.run("resume(1);").unwrap();
|
||||
assert_eq!(r.run("out.join()").unwrap(), JsValue::String("42".into()));
|
||||
// A function waiting on a promise nothing can settle is collected with it.
|
||||
r.interp().collect_garbage();
|
||||
let before = r.interp().heap.live_cells();
|
||||
r.run("(function () { async function w() { var big = []; for (var i = 0; i < 200; i++) big.push({ i: i }); await new Promise(function () {}); } w(); })();")
|
||||
.unwrap();
|
||||
r.interp().collect_garbage();
|
||||
let after = r.interp().heap.live_cells();
|
||||
assert!(after < before + 50, "{before} {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_that_ends_with_awaits_pending_ends_cleanly() {
|
||||
let mut r = realm();
|
||||
let v = r.run("async function f() { await new Promise(function () {}); return 1; } f(); 'done'").unwrap();
|
||||
assert_eq!(v, JsValue::String("done".into()));
|
||||
assert!(!r.is_running());
|
||||
assert_eq!(r.run("1 + 1").unwrap(), JsValue::Number(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_function_prototype_has_its_to_string_tag() {
|
||||
let src = "var AFP = Object.getPrototypeOf(async function () {});\n\
|
||||
var d = Object.getOwnPropertyDescriptor(AFP, Symbol.toStringTag);\n\
|
||||
log.push(d.value, d.writable, d.enumerable, d.configurable, Object.prototype.toString.call(async function () {}));";
|
||||
assert_eq!(log(src), "AsyncFunction false false true [object AsyncFunction]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_await_stays_within_the_heap_limit() {
|
||||
// The activation, its two reactions, the derived promise and the suspended frame's bytes all
|
||||
// fit in the heap limit, or the run stops at the `await`. The frame waits with 40 operands on
|
||||
// a promise that never settles, so its bytes stay charged after the run. A suspension that
|
||||
// went past the limit would be stopped only later, at the end of the run, so the largest
|
||||
// heap that still stops the run must stop it at the `await`.
|
||||
let operands: String = (0..40).map(|i| format!("{i}, ")).collect();
|
||||
let setup =
|
||||
format!("var gate = new Promise(function () {{}}); function g() {{ return 0; }} async function f() {{ return g({operands}await gate); }} 0");
|
||||
let setup = setup.as_str();
|
||||
let await_column = setup.find("await gate").map(|i| i + 1);
|
||||
let run = "f(); 0";
|
||||
let mut measure = realm();
|
||||
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
|
||||
let base = measure.collect_garbage();
|
||||
assert_eq!(measure.run(run), Ok(JsValue::Number(0.0)));
|
||||
let need = measure.interp().settled_heap_bytes().saturating_sub(base) + 1024;
|
||||
let mut last_stop = None;
|
||||
let mut over = Vec::new();
|
||||
for spare in (0..=need).step_by(4) {
|
||||
let mut r = realm();
|
||||
assert_eq!(r.run(setup), Ok(JsValue::Number(0.0)));
|
||||
let heap_bytes = r.collect_garbage() + spare;
|
||||
r.set_limits(Limits { heap_bytes, ..Limits::default() });
|
||||
let out = r.run(run);
|
||||
match &out {
|
||||
Ok(JsValue::Number(_)) => {}
|
||||
Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => last_stop = Some((spare, e.line, e.column)),
|
||||
other => panic!("{spare}: {other:?}"),
|
||||
}
|
||||
let bytes = r.interp().settled_heap_bytes();
|
||||
if out.is_ok() && bytes > heap_bytes {
|
||||
over.push((spare, bytes - heap_bytes));
|
||||
}
|
||||
}
|
||||
assert!(over.is_empty(), "runs that suspended past the limit (spare bytes, bytes over): {over:?}");
|
||||
let Some((spare, line, column)) = last_stop else { panic!("no limit stopped the run") };
|
||||
assert_eq!((line, usize::try_from(column).ok()), (1, await_column), "the run with {spare} spare bytes stopped away from the await");
|
||||
}
|
||||
|
||||
/// The fewest frames with which `src` runs to its end.
|
||||
fn fewest_frames(src: &str) -> usize {
|
||||
for frames in 1..64 {
|
||||
let mut r = Realm::with_options(Options { es2017: true, ..Options::default() }, Limits { frames, ..Limits::default() });
|
||||
if r.run(src).is_ok() {
|
||||
return frames;
|
||||
}
|
||||
}
|
||||
panic!("{src} did not run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_then_getter_on_a_returned_value_runs_after_the_async_frame_ends() {
|
||||
let setup = "function rec(n) { return n ? rec(n - 1) : 0; }\n\
|
||||
var o = { get then() { rec(5); return undefined; } };\n";
|
||||
let direct = fewest_frames(&format!("{setup}o.then; 0"));
|
||||
let returned = fewest_frames(&format!("{setup}async function f() {{ return o; }} f(); 0"));
|
||||
assert_eq!(returned, direct);
|
||||
// Returning the function's own promise rejects it with a TypeError.
|
||||
let own = "async function f() { await 0; return p; } var p = f(); p.catch(function (e) { log.push(e instanceof TypeError); });";
|
||||
assert_eq!(log(own), "true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_async_arrow_head_reads_patterns_with_defaults_and_rejects_a_shorthand_await() {
|
||||
let src = "var f = async ({a = 1}) => a; var g = async ({await: x}) => x; var h = async ([b = 2]) => b;\n\
|
||||
Promise.all([f({}), g({ await: 3 }), h([])]).then(function (r) { log.push(r.join(',')); });";
|
||||
assert_eq!(log(src), "1,3,2");
|
||||
let mut r = realm();
|
||||
syntax_error(&mut r, "var async = function () {}; async({a = 1});");
|
||||
syntax_error(&mut r, "async ({await}) => 0");
|
||||
syntax_error(&mut r, "async ({a = await}) => 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_resume_takes_fuel() {
|
||||
let mut r = realm();
|
||||
r.set_limits(Limits { fuel: 20_000, ..Limits::default() });
|
||||
let e = r.run("async function f() { for (;;) await 0; } f();").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn es5_and_extendscript_realms_do_not_read_async_functions() {
|
||||
let mut es2015 = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
syntax_error(&mut es2015, "async function f() {}");
|
||||
assert_eq!(es2015.run("var async = 1, await = 2; async + await").unwrap(), JsValue::Number(3.0));
|
||||
syntax_error(&mut Realm::with_options(Options::default(), Limits::default()), "async function f() {}");
|
||||
syntax_error(&mut Realm::new(), "var f = async () => 1;");
|
||||
}
|
||||
|
||||
/// Starts `src` in a realm with `start`, calls `change` once the run has paused, runs it to its
|
||||
/// end, and gives the run's value and the realm's options after it.
|
||||
fn run_changing_language(src: &str, start: Options, change: impl FnOnce(&mut Realm)) -> (Result<JsValue, RunError>, Options) {
|
||||
let mut realm = Realm::with_options(start, Limits::default());
|
||||
if let Err(e) = realm.start(src) {
|
||||
return (Err(e), realm.interp().options.clone());
|
||||
}
|
||||
match realm.advance(20) {
|
||||
Ok(crate::Progress::Paused) => {}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
change(&mut realm);
|
||||
loop {
|
||||
match realm.advance(1000) {
|
||||
Ok(crate::Progress::Done(v)) => return (Ok(v), realm.interp().options.clone()),
|
||||
Ok(_) => {}
|
||||
Err(e) => return (Err(e), realm.interp().options.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_changes_during_a_run_apply_after_it_in_the_order_they_were_made() {
|
||||
let src = "for (var i = 0; i < 200; i++) {} eval('(async function () {})'); 1";
|
||||
let es2017 = Options { es2017: true, ..Options::default() };
|
||||
let es2015 = Options { es2015: true, ..Options::default() };
|
||||
let (v, o) = run_changing_language(src, es2017.clone(), |r| r.set_es2017(false));
|
||||
assert_eq!(v, Ok(JsValue::Number(1.0)), "the run keeps async functions for the code it evaluates");
|
||||
assert!(o.es2015 && !o.es2017, "{o:?}");
|
||||
let (v, o) = run_changing_language(src, es2017.clone(), |r| {
|
||||
r.set_es2015(false);
|
||||
r.set_es2017(true);
|
||||
});
|
||||
assert_eq!(v, Ok(JsValue::Number(1.0)));
|
||||
assert!(o.es2015 && o.es2017, "the later call wins: {o:?}");
|
||||
let (v, o) = run_changing_language(src, es2017, |r| {
|
||||
r.set_es2017(true);
|
||||
r.set_es2015(false);
|
||||
});
|
||||
assert_eq!(v, Ok(JsValue::Number(1.0)));
|
||||
assert!(!o.es2015 && !o.es2017, "turning es2015 off turns es2017 off: {o:?}");
|
||||
let (v, o) = run_changing_language("for (var i = 0; i < 200; i++) {} 1", es2015, |r| r.set_es2017(true));
|
||||
assert_eq!(v, Ok(JsValue::Number(1.0)));
|
||||
assert!(o.es2015 && o.es2017, "{o:?}");
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
//! run past [`crate::Limits`].
|
||||
|
||||
mod array;
|
||||
mod async_function;
|
||||
pub(crate) mod binary;
|
||||
pub(crate) mod collections;
|
||||
pub(crate) mod extensions;
|
||||
@@ -250,6 +251,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
|
||||
method(interp, object_proto, "propertyIsEnumerable", property_is_enumerable, 1)?;
|
||||
|
||||
let function = native(interp, "Function", function_ctor, 1, NativeKind::Plain, true)?;
|
||||
interp.intrinsics.function_ctor = function;
|
||||
constructor(interp, "Function", function, function_proto)?;
|
||||
let call = native(interp, "call", unreachable_native, 1, NativeKind::Call, false)?;
|
||||
data(interp, function_proto, "call", Value::Object(call), HIDDEN)?;
|
||||
@@ -670,13 +672,21 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b
|
||||
/// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as
|
||||
/// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function.
|
||||
fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
create_dynamic_function(interp, args, false)
|
||||
create_dynamic_function(interp, args, false, false)
|
||||
}
|
||||
|
||||
/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with
|
||||
/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`.
|
||||
pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult<Value> {
|
||||
let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" };
|
||||
/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function`, with
|
||||
/// `generator` for `GeneratorFunction`, whose source is read as `(function* anonymous(…`, and with
|
||||
/// `is_async` for `AsyncFunction` (ECMA-262 2017 section 25.5.1.1), whose source is read as
|
||||
/// `(async function anonymous(…`. An async function's source is read with
|
||||
/// [`crate::Options::es2017`] whatever the realm reads scripts with, since only an async function
|
||||
/// leads a script to `AsyncFunction`.
|
||||
pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool, is_async: bool) -> JsResult<Value> {
|
||||
let head: &str = match (generator, is_async) {
|
||||
(true, _) => "(function* anonymous(",
|
||||
(false, true) => "(async function anonymous(",
|
||||
(false, false) => "(function anonymous(",
|
||||
};
|
||||
const MID: &str = "\n) {\n";
|
||||
const TAIL: &str = "\n})";
|
||||
let mut parts = Vec::with_capacity(args.len());
|
||||
@@ -706,14 +716,15 @@ pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], gener
|
||||
interp.observe_code(&units);
|
||||
interp.source_units = interp.source_units.saturating_add(units.len());
|
||||
let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len()));
|
||||
let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() };
|
||||
let es2017 = interp.options.es2017 || is_async;
|
||||
let options = crate::Options { strict: false, max_source_units: remaining, es2017, ..interp.options.clone() };
|
||||
let program = match crate::parse_utf16(&units, &options) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)),
|
||||
};
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() });
|
||||
let code = match compile_constructed_function(&program, &source) {
|
||||
Ok(Some(code)) if code.generator == generator => code,
|
||||
Ok(Some(code)) if code.generator == generator && code.is_async == is_async => code,
|
||||
Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")),
|
||||
Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)),
|
||||
Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)),
|
||||
|
||||
@@ -190,8 +190,10 @@ impl Indices {
|
||||
if self.lo >= self.hi {
|
||||
return Ok(None);
|
||||
}
|
||||
// The object may have become one of a host class with an indexer meanwhile, whose
|
||||
// elements are not properties: the rest of the range is then visited index by index.
|
||||
if self.sparse.as_ref().is_some_and(|s| s.epoch != interp.heap.index_epoch) {
|
||||
self.sparse = self.gather(interp)?;
|
||||
self.sparse = if interp.host_indexer(self.obj)?.is_some() { None } else { self.gather(interp)? };
|
||||
}
|
||||
let k = match &mut self.sparse {
|
||||
None if self.ascending => self.lo,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! `AsyncFunction` and its prototype (ECMA-262 2017 section 25.5,
|
||||
//! <https://262.ecma-international.org/8.0/#sec-async-function-objects>), in realms with
|
||||
//! [`crate::Options::es2015`]: the prototype of every async function, and the constructor a script
|
||||
//! reaches through it. `AsyncFunction` is not a global.
|
||||
|
||||
use super::{create_dynamic_function, data, native};
|
||||
use crate::heap::{CONFIGURABLE, Class, NativeKind, Object, Prop};
|
||||
use crate::interp::{Interp, JsResult};
|
||||
use crate::value::Value;
|
||||
|
||||
/// Creates `AsyncFunction` and `AsyncFunction.prototype`, keeping the prototype for the async
|
||||
/// functions the realm makes.
|
||||
pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
let function_proto = interp.intrinsics.function_proto;
|
||||
let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto)));
|
||||
interp.promises.async_function_proto = Some(proto);
|
||||
let ctor = native(interp, "AsyncFunction", async_function_ctor, 1, NativeKind::Plain, true)?;
|
||||
interp.promises.async_function_ctor = Some(ctor);
|
||||
// The built-in `Function` is the constructor's prototype (section 25.5.2), even after a
|
||||
// script has replaced `Function.prototype.constructor`.
|
||||
let function_ctor = interp.intrinsics.function_ctor;
|
||||
if let Some(o) = interp.heap.object_mut(ctor) {
|
||||
o.proto = Some(function_ctor);
|
||||
}
|
||||
data(interp, ctor, "prototype", Value::Object(proto), 0)?;
|
||||
// Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary
|
||||
// built-in prototypes.
|
||||
data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE)?;
|
||||
// `AsyncFunction.prototype[@@toStringTag]` is "AsyncFunction", configurable only (section
|
||||
// 25.5.3.2).
|
||||
if let Some(tag) = interp.well_known(|w| &w.to_string_tag) {
|
||||
interp.define_sym(proto, tag, Prop::Data { value: Value::str("AsyncFunction"), flags: CONFIGURABLE })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1).
|
||||
fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
create_dynamic_function(interp, args, false, true)
|
||||
}
|
||||
@@ -47,5 +47,5 @@ pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> {
|
||||
|
||||
/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1).
|
||||
fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
super::create_dynamic_function(interp, args, true)
|
||||
super::create_dynamic_function(interp, args, true, false)
|
||||
}
|
||||
@@ -145,6 +145,8 @@ enum Then {
|
||||
Settle(ObjId, Option<Site>),
|
||||
/// An exception rejects through this resolving record.
|
||||
Reject(ObjId),
|
||||
/// An async function goes on after `await`; its own promise takes its result.
|
||||
Resume,
|
||||
/// The call was a `finally` callback that a reaction job runs in place of the Then Finally or
|
||||
/// Catch Finally function: `derived` is settled as that function's result settles it.
|
||||
Finally { derived: ObjId, value: Value, throws: bool },
|
||||
@@ -162,9 +164,11 @@ enum Kind {
|
||||
CatchFinally,
|
||||
ValueThunk,
|
||||
Thrower,
|
||||
AwaitFulfilled,
|
||||
AwaitRejected,
|
||||
}
|
||||
|
||||
const KINDS: [(Kind, NativeFn); 9] = [
|
||||
const KINDS: [(Kind, NativeFn); 11] = [
|
||||
(Kind::Resolve, resolve_function),
|
||||
(Kind::Reject, reject_function),
|
||||
(Kind::AllElement, all_element),
|
||||
@@ -174,6 +178,8 @@ const KINDS: [(Kind, NativeFn); 9] = [
|
||||
(Kind::CatchFinally, catch_finally),
|
||||
(Kind::ValueThunk, value_thunk),
|
||||
(Kind::Thrower, thrower),
|
||||
(Kind::AwaitFulfilled, await_continuation),
|
||||
(Kind::AwaitRejected, await_continuation),
|
||||
];
|
||||
|
||||
/// `Promise`'s objects and the run's job queue.
|
||||
@@ -192,11 +198,17 @@ pub(crate) struct Promises {
|
||||
rejected: Vec<ObjId>,
|
||||
/// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower).
|
||||
pub(crate) max_jobs: usize,
|
||||
/// `AsyncFunction.prototype` (ECMA-262 2017 section 25.5.3), the prototype of async functions.
|
||||
pub(crate) async_function_proto: Option<ObjId>,
|
||||
/// `AsyncFunction` (section 25.5.1), which is not a global.
|
||||
pub(crate) async_function_ctor: Option<ObjId>,
|
||||
}
|
||||
|
||||
impl Default for Promises {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
async_function_proto: None,
|
||||
async_function_ctor: None,
|
||||
proto: None,
|
||||
ctor: None,
|
||||
natives: Vec::new(),
|
||||
@@ -214,6 +226,7 @@ impl Promises {
|
||||
/// Adds what the queue and the promise objects hold to the collector's roots.
|
||||
pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) {
|
||||
roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected));
|
||||
roots.objects.extend(self.async_function_proto.iter().chain(&self.async_function_ctor));
|
||||
roots.values.extend(self.completion.iter());
|
||||
match &self.running {
|
||||
Some(Then::Settle(o, site)) => {
|
||||
@@ -225,7 +238,7 @@ impl Promises {
|
||||
roots.objects.push(*derived);
|
||||
roots.values.push(value);
|
||||
}
|
||||
None => {}
|
||||
Some(Then::Resume) | None => {}
|
||||
}
|
||||
for job in &self.queue {
|
||||
match job {
|
||||
@@ -282,7 +295,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
let n = native(interp, "", f, 1, NativeKind::Plain, false)?;
|
||||
interp.promises.natives.push(n);
|
||||
}
|
||||
Ok(())
|
||||
super::async_function::install(interp)
|
||||
}
|
||||
|
||||
/// Creates `Promise` in a realm made without [`crate::Options::es2015`], replacing a global
|
||||
@@ -575,6 +588,140 @@ fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult<Value>
|
||||
})
|
||||
}
|
||||
|
||||
// ---- async functions ----
|
||||
|
||||
/// The built-in a suspended async function's reactions are bound to. The job queue resumes the
|
||||
/// function instead of calling it, and scripts cannot reach it.
|
||||
fn await_continuation(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
Err(Abrupt::Internal("an await continuation was called".into()))
|
||||
}
|
||||
|
||||
impl Interp {
|
||||
/// Settles the promise of an async function whose frame ends: its return value resolves it,
|
||||
/// and the exception that leaves it rejects it.
|
||||
pub(crate) fn settle_async(&mut self, p: ObjId, r: Result<Value, Value>) -> JsResult<()> {
|
||||
match r {
|
||||
Ok(v) => resolve_promise(self, p, v),
|
||||
Err(e) => {
|
||||
let site = caught(self);
|
||||
reject_promise(self, p, e, site)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the promise of an async function whose frame has returned `v` and is already off
|
||||
/// the frames. Returning the promise itself rejects it with a `TypeError` at `site`, the
|
||||
/// return.
|
||||
pub(crate) fn resolve_async_return(&mut self, p: ObjId, v: Value, site: Option<Site>) -> JsResult<()> {
|
||||
if matches!(v, Value::Object(o) if o == p) {
|
||||
return scoped(self, |interp| {
|
||||
root(interp, &Value::Object(p));
|
||||
let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself");
|
||||
root(interp, &e);
|
||||
reject_promise(interp, p, e, site)
|
||||
});
|
||||
}
|
||||
resolve_promise(self, p, v)
|
||||
}
|
||||
|
||||
/// A new pending promise for the async function call whose frame is on top.
|
||||
pub(crate) fn new_async_promise(&mut self) -> JsResult<ObjId> {
|
||||
new_promise(self)
|
||||
}
|
||||
|
||||
/// `await v` in the async function the top frame runs (Await, ECMA-262 2017 section 6.2.3.1,
|
||||
/// with PromiseResolve as later editions have it): `v` becomes a built-in promise, the frame
|
||||
/// is suspended until it settles, and the function's call gives its promise, `Some` when the
|
||||
/// frame was the boundary frame. Throws at the `await` when reading `v`'s `constructor` throws.
|
||||
pub(crate) fn await_value(&mut self, v: Value) -> JsResult<Option<Value>> {
|
||||
if self.async_promise().is_none() {
|
||||
return Err(Abrupt::Internal("await outside an async function".into()));
|
||||
}
|
||||
let ctor = self.promises.ctor.map_or(Value::Undefined, Value::Object);
|
||||
scoped(self, |interp| {
|
||||
let p = promise_resolve(interp, &ctor, v)?;
|
||||
root(interp, &p);
|
||||
let Value::Object(p) = p else { return Err(Abrupt::Internal("PromiseResolve gave a value that is not a promise".into())) };
|
||||
let bytes = interp.suspend_bytes();
|
||||
interp.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?;
|
||||
let act = interp.heap.alloc_object(Object::new(Class::Activation(None), None));
|
||||
root(interp, &Value::Object(act));
|
||||
let on_fulfilled = record_function(interp, Kind::AwaitFulfilled, act, 1)?;
|
||||
root(interp, &on_fulfilled);
|
||||
let on_rejected = record_function(interp, Kind::AwaitRejected, act, 1)?;
|
||||
root(interp, &on_rejected);
|
||||
// The reactions settle no promise of their own; this one stays pending and unseen.
|
||||
let derived = new_promise(interp)?;
|
||||
root(interp, &Value::Object(derived));
|
||||
promise_data(interp, derived)?.handled = true;
|
||||
// The allocations above used up the room checked for at the start, so the reaction or
|
||||
// job and the frame's bytes are checked again, with the frame still on top, before the
|
||||
// awaited promise gets its reaction.
|
||||
let then_bytes = if promise_data(interp, p)?.state == State::Pending { REACTION_BYTES } else { JOB_BYTES };
|
||||
interp.reserve_heap(then_bytes.saturating_add(bytes))?;
|
||||
perform_then(interp, p, on_fulfilled, on_rejected, derived)?;
|
||||
let (a, boundary) = interp.suspend_frame()?;
|
||||
let promise = a.promise;
|
||||
let held = a.bytes();
|
||||
if let Some(o) = interp.heap.object_mut(act) {
|
||||
o.class = Class::Activation(Some(Box::new(a)));
|
||||
}
|
||||
interp.heap.bytes = interp.heap.bytes.saturating_add(held);
|
||||
if boundary {
|
||||
return Ok(Some(Value::Object(promise)));
|
||||
}
|
||||
interp.push(Value::Object(promise))?;
|
||||
Ok(None)
|
||||
})
|
||||
}
|
||||
|
||||
/// The activation `handler` resumes when it is a suspended async function's reaction, and
|
||||
/// whether it is the rejection's.
|
||||
fn await_activation(&self, handler: &Value) -> Option<(ObjId, bool)> {
|
||||
let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| self.heap.object(o)).map(|o| &o.class) else {
|
||||
return None;
|
||||
};
|
||||
let reject = if self.promises.natives.get(Kind::AwaitFulfilled as usize) == Some(target) {
|
||||
false
|
||||
} else if self.promises.natives.get(Kind::AwaitRejected as usize) == Some(target) {
|
||||
true
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
match args.first() {
|
||||
Some(Value::Object(act)) => Some((*act, reject)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resumes the async function `handler` belongs to with the settled value: its frame goes back
|
||||
/// on top as a boundary frame the caller runs, and a rejection is thrown at its `await`. A job
|
||||
/// that finds the frame already resumed does nothing.
|
||||
fn resume_async(&mut self, handler: &Value, argument: Value, reject: bool, site: Option<Site>) -> JsResult<()> {
|
||||
let Some((act, _)) = self.await_activation(handler) else { return Err(Abrupt::Internal("not an await reaction".into())) };
|
||||
let taken = match self.heap.object_mut(act).map(|o| &mut o.class) {
|
||||
Some(Class::Activation(slot)) => slot.take(),
|
||||
_ => return Err(Abrupt::Internal("an await reaction lost its activation".into())),
|
||||
};
|
||||
let Some(a) = taken else { return Ok(()) };
|
||||
self.heap.bytes = self.heap.bytes.saturating_sub(a.bytes());
|
||||
self.restore_frame(*a)?;
|
||||
self.promises.running = Some(Then::Resume);
|
||||
if !reject {
|
||||
return self.push(argument);
|
||||
}
|
||||
if site.is_some() {
|
||||
self.throw_site = site;
|
||||
}
|
||||
match self.unwind_or_abort(argument) {
|
||||
Ok(Some(v)) => self.finish_job(Ok(v)),
|
||||
Ok(None) => Ok(()),
|
||||
Err(Abrupt::Throw(e)) => self.finish_job(Err(e)),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the job queue ----
|
||||
|
||||
impl Interp {
|
||||
@@ -660,6 +807,10 @@ impl Interp {
|
||||
self.use_fuel()?;
|
||||
scoped(self, |interp| {
|
||||
let (f, this, args, then) = match job {
|
||||
Job::Reaction { handler, argument, reject, site, .. } if interp.await_activation(&handler).is_some() => {
|
||||
root(interp, &argument);
|
||||
return interp.resume_async(&handler, argument, reject, site);
|
||||
}
|
||||
Job::Reaction { handler, argument, reject, derived, site } => {
|
||||
if !interp.is_callable(&handler) {
|
||||
return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) };
|
||||
@@ -700,7 +851,7 @@ impl Interp {
|
||||
match (then, r) {
|
||||
(Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v),
|
||||
(Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site),
|
||||
(Then::Reject(_), Ok(_)) => Ok(()),
|
||||
(Then::Reject(_), Ok(_)) | (Then::Resume, _) => Ok(()),
|
||||
(Then::Reject(rec), Err(e)) => scoped(self, |interp| {
|
||||
root(interp, &Value::Object(rec));
|
||||
reject_through(interp, rec, e, site)
|
||||
@@ -935,8 +1086,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<V
|
||||
}
|
||||
|
||||
/// `v` is a constructor: a function written in JavaScript other than an arrow function, generator
|
||||
/// function or method, a built-in or registered host constructor, or a bound function whose target
|
||||
/// is one.
|
||||
/// function, async function or method, a built-in or registered host constructor, or a bound
|
||||
/// function whose target is one.
|
||||
fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult<bool> {
|
||||
let mut v = v.clone();
|
||||
loop {
|
||||
@@ -945,7 +1096,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult<bool> {
|
||||
_ => return Ok(false),
|
||||
};
|
||||
match func {
|
||||
Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator),
|
||||
Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator && !code.is_async),
|
||||
Func::Native { constructor, .. } => return Ok(constructor),
|
||||
Func::Data { read: ArgRead::Hosted, .. } => return Ok(v.as_object().is_some_and(|o| interp.is_constructible_host_class(o))),
|
||||
Func::Bound { target, .. } => {
|
||||
|
||||
@@ -334,6 +334,9 @@ pub(crate) enum Op {
|
||||
DelegateResult(u32),
|
||||
/// `mode value` → `value`; for `return`, jumps with it.
|
||||
DelegateDone(u32),
|
||||
/// `value` → its awaited value: suspends the running async function until the value settles,
|
||||
/// and goes on with its fulfillment value or throws its rejection reason here.
|
||||
Await,
|
||||
}
|
||||
|
||||
/// The names a block declares, entered with [`Op::PushBlock`].
|
||||
@@ -406,6 +409,11 @@ pub(crate) struct Code {
|
||||
pub(crate) vars: Vec<Key>,
|
||||
/// Function declarations to instantiate on entry: their names and indices in `functions`.
|
||||
pub(crate) fun_decls: Vec<(Key, u32)>,
|
||||
/// In script and eval code, the variables of block functions (Annex B.3.3.2 and B.3.3.3) that
|
||||
/// the code does not declare otherwise: each is declared, and its function assigned to it, only
|
||||
/// when no `let`, `const` or block function between the code and its variable environment has
|
||||
/// the name and the variable can be declared.
|
||||
pub(crate) annex_vars: Vec<Key>,
|
||||
/// The body refers to `arguments` or calls `eval`.
|
||||
pub(crate) uses_arguments: bool,
|
||||
pub(crate) source: Rc<Source>,
|
||||
@@ -453,6 +461,8 @@ pub(crate) struct Code {
|
||||
/// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]),
|
||||
/// and it is not a constructor.
|
||||
pub(crate) generator: bool,
|
||||
/// The code is an async function's: a call returns a promise, and it may run [`Op::Await`].
|
||||
pub(crate) is_async: bool,
|
||||
/// What `super` and `new.target` may do in eval code a direct `eval` in this code runs: the
|
||||
/// rules of the function's body, of the code around an arrow function, or those eval code was
|
||||
/// read with (ECMA-262 2015 section 18.2.1.1).
|
||||
@@ -596,7 +606,7 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
|
||||
Op::SuperCall(n) => e(n.checked_add(1).ok_or("operand too large")?, 1),
|
||||
Op::SuperCallSpread => e(2, 1),
|
||||
Op::BindThis => e(1, 1),
|
||||
Op::ToStr | Op::GetIterator | Op::IterSkip | Op::RequireObjectCoercible => e(1, 1),
|
||||
Op::ToStr | Op::Await | Op::GetIterator | Op::IterSkip | Op::RequireObjectCoercible => e(1, 1),
|
||||
Op::IterStep(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] },
|
||||
Op::IterValue(n) | Op::IterRest(n) => e(n.checked_add(1).ok_or("operand too large")?, n.checked_add(2).ok_or("operand too large")?),
|
||||
Op::PatternGet(n) => e(n.checked_add(2).ok_or("operand too large")?, n.checked_add(3).ok_or("operand too large")?),
|
||||
|
||||
@@ -155,7 +155,7 @@ impl Interp {
|
||||
return p.constructor;
|
||||
}
|
||||
match self.func_of(&v) {
|
||||
Some(Func::Closure { code, .. }) => return !(code.arrow || code.method || code.generator),
|
||||
Some(Func::Closure { code, .. }) => return !(code.arrow || code.method || code.generator || code.is_async),
|
||||
Some(Func::Native { constructor, .. }) => return constructor,
|
||||
Some(Func::Data { read: crate::host::ArgRead::Hosted, .. }) => return v.as_object().is_some_and(|o| self.is_host_constructor(o)),
|
||||
Some(Func::Bound { target, .. }) => v = Value::Object(target),
|
||||
@@ -320,6 +320,7 @@ impl Interp {
|
||||
match self.func_of(&f) {
|
||||
Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")),
|
||||
Some(Func::Closure { code, .. }) if code.generator => Err(self.type_error("a generator function is not a constructor")),
|
||||
Some(Func::Closure { code, .. }) if code.is_async => Err(self.type_error("an async function is not a constructor")),
|
||||
Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")),
|
||||
Some(Func::Closure { code, env }) if code.derived => {
|
||||
self.stack.truncate(start);
|
||||
@@ -413,6 +414,11 @@ impl Interp {
|
||||
let v = self.call_data(&host, &name, &Value::Undefined, &args, &read);
|
||||
self.constructing = was;
|
||||
let v = v?;
|
||||
// `new` gives an object ([[Construct]]): a constructor that gives another value
|
||||
// is a TypeError.
|
||||
if !matches!(v, Value::Object(_)) {
|
||||
return Err(self.type_error(&format!("the constructor {name} did not give an object")));
|
||||
}
|
||||
if let Value::Object(o) = &v
|
||||
&& matches!(self.object(*o)?.class, Class::Ordinary)
|
||||
&& let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))?
|
||||
|
||||
@@ -124,6 +124,9 @@ struct FnCompiler<'a> {
|
||||
struct Hoisted {
|
||||
vars: Vec<Key>,
|
||||
fun_decls: Vec<(Key, u32)>,
|
||||
/// The names of block functions (Annex B.3.3) that are neither a `var` nor a function at the
|
||||
/// top of the body.
|
||||
annex_vars: Vec<Key>,
|
||||
}
|
||||
|
||||
fn key_of(name: &str) -> Key {
|
||||
@@ -273,7 +276,8 @@ impl<'a> FnCompiler<'a> {
|
||||
/// hoisted; one in a block is instantiated when the block is entered, and outside strict mode
|
||||
/// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter or with
|
||||
/// a `let` or a `const` of the body or of a block or loop around the declaration, or with a
|
||||
/// function of a block around the one that holds it.
|
||||
/// function of a block around the one that holds it. Such a name that the body does not also
|
||||
/// declare with `var` or as a function at its top goes in [`Hoisted::annex_vars`].
|
||||
fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult<Hoisted> {
|
||||
let mut out = Hoisted::default();
|
||||
let mut seen = HashSet::new();
|
||||
@@ -290,6 +294,7 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
};
|
||||
let mut annex: Vec<(Key, usize, StmtId)> = Vec::new();
|
||||
let mut annex_seen = HashSet::new();
|
||||
while let Some((id, nested, scope)) = work.pop() {
|
||||
let Some(stmt) = self.ast.stmt(id) else { return internal("statement out of range") };
|
||||
let inner = self.es2015;
|
||||
@@ -301,13 +306,15 @@ impl<'a> FnCompiler<'a> {
|
||||
Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))),
|
||||
Stmt::Lexical(..) | Stmt::Class(_) => {}
|
||||
Stmt::FunctionDecl(fid) => {
|
||||
let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else {
|
||||
let Some(f) = self.ast.function(*fid) else { return internal("function out of range") };
|
||||
let Some(name) = f.name.as_ref() else {
|
||||
return internal("function declaration without a name");
|
||||
};
|
||||
let k = key_of(&name.name);
|
||||
if self.es2015 && nested {
|
||||
// Annex B.3.3 gives plain function declarations only a var binding too.
|
||||
if !self.strict && !generator {
|
||||
// Annex B.3.3 gives plain function declarations a variable, not generator
|
||||
// or async ones.
|
||||
if !self.strict && !f.generator && !f.is_async {
|
||||
annex.push((k, scope, id));
|
||||
}
|
||||
} else {
|
||||
@@ -415,7 +422,9 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
if !clash {
|
||||
self.annex.insert(id);
|
||||
add_var(&mut out, k);
|
||||
if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) {
|
||||
out.annex_vars.push(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
@@ -1396,6 +1405,11 @@ impl<'a> FnCompiler<'a> {
|
||||
self.uses_new_target = true;
|
||||
self.emit(Op::NewTarget);
|
||||
}
|
||||
Expr::Await(arg) => {
|
||||
self.expr(*arg)?;
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
self.emit(Op::Await);
|
||||
}
|
||||
Expr::Update { op, prefix, target } => self.update(*op, *prefix, *target)?,
|
||||
Expr::Unary { .. } => self.unary(id)?,
|
||||
Expr::Binary { .. } | Expr::Logical { .. } => self.binary_chain(id)?,
|
||||
@@ -2400,6 +2414,7 @@ impl<'a> FnCompiler<'a> {
|
||||
params: meta.params,
|
||||
vars: hoisted.vars,
|
||||
fun_decls: hoisted.fun_decls,
|
||||
annex_vars: hoisted.annex_vars,
|
||||
uses_arguments: self.uses_arguments,
|
||||
source: self.source.clone(),
|
||||
span: meta.span,
|
||||
@@ -2419,6 +2434,7 @@ impl<'a> FnCompiler<'a> {
|
||||
own_name: meta.own_name,
|
||||
method: meta.method,
|
||||
generator: self.generator,
|
||||
is_async: meta.is_async,
|
||||
supers: self.supers,
|
||||
};
|
||||
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
|
||||
@@ -2443,6 +2459,7 @@ struct Meta {
|
||||
pattern_names: Vec<Key>,
|
||||
own_name: Option<Key>,
|
||||
method: bool,
|
||||
is_async: bool,
|
||||
}
|
||||
|
||||
fn len_u32(n: usize) -> u32 {
|
||||
@@ -2478,7 +2495,10 @@ pub(crate) fn compile_function(
|
||||
let rest = f.rest.as_ref().map(|r| param_key(&c, f.params.len(), r));
|
||||
let pattern_names: Vec<Key> = f.params.iter().chain(&f.rest).filter(|p| matches!(p, Binding::Pattern(_))).flat_map(|p| c.bound_keys(p)).collect();
|
||||
let all_params: Vec<Key> = f.params.iter().chain(&f.rest).flat_map(|p| c.bound_keys(p)).collect();
|
||||
let hoisted = c.hoist(&f.body, &all_params)?;
|
||||
let mut hoisted = c.hoist(&f.body, &all_params)?;
|
||||
// A function's block functions always have their variable (Annex B.3.3.1).
|
||||
let annex = std::mem::take(&mut hoisted.annex_vars);
|
||||
hoisted.vars.extend(annex);
|
||||
let top_scope = c.list_scope(&f.body, false)?;
|
||||
// Default values are expressions (ContainsExpression, ECMA-262 2015 section 14.1.5), and a
|
||||
// destructured parameter is bound by code of its own: a rest parameter alone leaves the
|
||||
@@ -2551,6 +2571,7 @@ pub(crate) fn compile_function(
|
||||
}),
|
||||
method: (f.home && !f.is_class_constructor())
|
||||
|| (es2015 && matches!(f.kind, FunctionKind::Method | FunctionKind::Getter | FunctionKind::Setter)),
|
||||
is_async: f.is_async,
|
||||
};
|
||||
c.finish(hoisted, meta)
|
||||
}
|
||||
|
||||
@@ -181,6 +181,28 @@ fn a_block_function_inside_another_of_its_name_leaves_the_variable_alone() {
|
||||
truth("function g() { { function f() { return 1; } { function f() { return 2; } } } return f(); } g() === 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() {
|
||||
// A block function of a script or of eval code gets no variable when a `let`, a `const` or a
|
||||
// block function out to the variable environment has its name, or when the global object
|
||||
// cannot take it (Annex B.3.3.2 and B.3.3.3); its block still has it, and a `var` of the name
|
||||
// is still a SyntaxError.
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("let f = 1; 0"), Ok(JsValue::Number(0.0)));
|
||||
assert_eq!(realm.run("var inner; { function f() { return 2; } inner = f(); } inner + f"), Ok(JsValue::Number(3.0)));
|
||||
assert!(is_thrown(&realm.run("{ function f() {} } var f;"), "SyntaxError"));
|
||||
assert_eq!(realm.run("(0, eval)('{ function f() { return 4; } }'); f"), Ok(JsValue::Number(1.0)));
|
||||
truth("function t() { let h = 1; { eval('{ function h() { return 2; } }'); } return h; } t() === 1");
|
||||
truth("function t() { let h = 1; eval('{ function h() {} }'); return h; } t() === 1");
|
||||
// A `catch` parameter does not stop the variable (Annex B.3.5).
|
||||
truth("try { throw 1; } catch (c) { eval('{ function c() { return 5; } }'); } c() === 5");
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("var out; Object.preventExtensions(this); 0"), Ok(JsValue::Number(0.0)));
|
||||
let kept = realm.run("{ function n() { return 6; } out = n(); } out + typeof n");
|
||||
assert_eq!(kept, Ok(JsValue::String("6undefined".into())));
|
||||
assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() {
|
||||
truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0");
|
||||
@@ -333,6 +355,17 @@ fn a_global_var_makes_its_own_property_over_an_inherited_one() {
|
||||
assert_eq!(realm.run("var inherited; !this.hasOwnProperty('inherited') && inherited === 1"), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_var_an_inherited_property_declared_does_not_stop_a_later_let() {
|
||||
// Without the option, `var x` uses the inherited `x` and makes no own property, so a later
|
||||
// run with the option may declare `x` with `let`.
|
||||
let mut realm = Realm::new();
|
||||
assert_eq!(realm.run("Object.prototype.x = 1; 0"), Ok(JsValue::Number(0.0)));
|
||||
assert_eq!(realm.run("var x; delete this.x"), Ok(JsValue::Bool(true)));
|
||||
realm.set_es2015(true);
|
||||
assert_eq!(realm.run("let x = 2; x"), Ok(JsValue::Number(2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_function_that_cannot_be_declared_declares_nothing() {
|
||||
let mut realm = es();
|
||||
@@ -454,6 +487,38 @@ fn a_global_var_that_cannot_be_declared_declares_nothing() {
|
||||
assert_eq!(realm.run("let x = 2; var kept; x + kept"), Ok(JsValue::Number(3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_stopped_by_the_frame_limit_declares_no_let() {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { frames: 0, ..Limits::default() });
|
||||
let stopped = realm.run("let early = 1; const fixed = 2;");
|
||||
assert!(matches!(&stopped, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Frames)), "{stopped:?}");
|
||||
realm.set_limits(Limits::default());
|
||||
assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_stopped_by_the_heap_limit_declares_no_let() {
|
||||
// The `let` and `const` names of a script go in before its functions are made; a heap too
|
||||
// small for both stops the script before any name is declared.
|
||||
let lets: String = (0..200).map(|i| format!("let a_long_lexical_name_{i} = {i}; ")).collect();
|
||||
let decls: String = (0..40).map(|i| format!("function f{i}() {{ return {i}; }} ")).collect();
|
||||
let src = format!("let early = 1; const fixed = 2; {lets}{decls}");
|
||||
let mut stopped = 0;
|
||||
for spare in (40_000..200_000).step_by(97) {
|
||||
let mut realm = es();
|
||||
let live = realm.collect_garbage();
|
||||
realm.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() });
|
||||
match realm.run(&src) {
|
||||
Ok(_) => continue,
|
||||
Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => stopped += 1,
|
||||
Err(e) => panic!("{spare}: {e:?}"),
|
||||
}
|
||||
realm.set_limits(Limits::default());
|
||||
assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0)), "{spare}");
|
||||
}
|
||||
assert!(stopped > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_code_keeps_its_let_and_const_to_itself() {
|
||||
truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'");
|
||||
@@ -866,6 +931,37 @@ fn spread_stops_at_the_heap_limit_before_the_next_step_runs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_template_object_stays_within_the_heap_limit() {
|
||||
// The template object's two arrays, the index name of each string and the `raw` property are
|
||||
// reserved before they are made, so the heap stays within each limit tried.
|
||||
let setup = "function t(s) { return s.length; } 0";
|
||||
let run = format!("t`{}`", (0..10).map(|i| format!("p{i}${{{i}}}")).collect::<String>());
|
||||
let mut measure = Realm::with_options(es_options(), Limits::default());
|
||||
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
|
||||
measure.interp().collect_garbage();
|
||||
let base = measure.interp().heap.bytes;
|
||||
assert_eq!(measure.run(&run), Ok(JsValue::Number(11.0)));
|
||||
let need = measure.interp().settled_heap_bytes() - base;
|
||||
let mut stopped = 0;
|
||||
for heap_bytes in (base..=base + need).step_by(4) {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
|
||||
if realm.run(setup).is_err() {
|
||||
continue;
|
||||
}
|
||||
realm.interp().collect_garbage();
|
||||
let r = realm.run(&run);
|
||||
stopped += usize::from(r.is_err());
|
||||
assert!(
|
||||
matches!(&r, Ok(JsValue::Number(_))) || matches!(&r, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)),
|
||||
"{heap_bytes}: {r:?}"
|
||||
);
|
||||
let bytes = realm.interp().settled_heap_bytes();
|
||||
assert!(bytes <= heap_bytes, "{bytes} > {heap_bytes}");
|
||||
}
|
||||
assert!(stopped > 0, "no limit stopped the run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spreading_other_values_is_a_type_error() {
|
||||
throws("[...1];", "TypeError");
|
||||
@@ -972,6 +1068,47 @@ fn spreading_a_rope_counts_its_flattened_length_first() {
|
||||
assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spreading_a_string_counts_the_string_it_makes_for_each_character() {
|
||||
// Each of the 16,384 elements is a property and a one-character string of its own. The
|
||||
// smaller heap has room for the properties alone but not for the strings as well, so the
|
||||
// spread stops with the heap limit. The larger heap holds the array, its keys and the
|
||||
// strings. The spread steps the string's iterator, so the fuel is set well above what it
|
||||
// takes.
|
||||
const N: usize = 16_384;
|
||||
let property = crate::heap::PROP_BYTES;
|
||||
let string = crate::heap::string_bytes(1);
|
||||
let setup = "var s = 'x'; for (var i = 0; i < 14; i++) s = s + s; s[0]; 0";
|
||||
let cases = [(property + string / 2, N * 1000, Err(LimitKind::Heap)), (2 * (property + string) + 8, N * 1000, Ok(N as f64))];
|
||||
for (per_element, fuel, expected) in cases {
|
||||
let mut r = es();
|
||||
assert_eq!(r.run(setup), Ok(JsValue::Number(0.0)));
|
||||
r.interp().collect_garbage();
|
||||
let heap_bytes = r.interp().heap.bytes + N * per_element;
|
||||
r.set_limits(Limits { heap_bytes, fuel: fuel as u64, ..Limits::default() });
|
||||
match (r.run("var a = [...s]; a.length"), expected) {
|
||||
(Ok(JsValue::Number(n)), Ok(m)) if n == m => {}
|
||||
(Err(e), Err(kind)) if e.kind == RunErrorKind::Limit(kind) => {}
|
||||
(result, expected) => panic!("{per_element} bytes for each element: {result:?}, expected {expected:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_strings_a_string_spread_makes_stay_counted_while_the_array_holds_them() {
|
||||
const N: u32 = 4096;
|
||||
let mut r = es();
|
||||
assert_eq!(r.run("var s = 'x'; for (var i = 0; i < 12; i++) s = s + s; s[0]; 0"), Ok(JsValue::Number(0.0)));
|
||||
r.interp().collect_garbage();
|
||||
let before = r.interp().heap.bytes;
|
||||
assert_eq!(r.run("var a = [...s]; a.length"), Ok(JsValue::Number(f64::from(N))));
|
||||
// Takes the bytes the spread held while it ran off the estimate.
|
||||
r.interp().reserve_heap(0).unwrap();
|
||||
let element = |i: u32| crate::heap::PROP_BYTES + crate::heap::string_bytes(i.to_string().len()) + crate::heap::string_bytes(1);
|
||||
let least = before + (0..N).map(element).sum::<usize>();
|
||||
assert!(r.interp().heap.bytes >= least, "{} < {least}", r.interp().heap.bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rest_parameter_checks_the_heap_before_its_array_is_made() {
|
||||
// The 20,000 arguments fit in the room left over, and the rest array of them does not, so
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::LimitKind;
|
||||
use crate::builtins::iterator::iter_result;
|
||||
use crate::bytecode::Code;
|
||||
use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key};
|
||||
use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal};
|
||||
use crate::interp::{Abrupt, AnnexOff, Frame, Interp, JsResult, Prepared, ThrowSite, internal};
|
||||
use crate::value::Value;
|
||||
|
||||
/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4).
|
||||
@@ -305,6 +305,8 @@ impl Interp {
|
||||
completion,
|
||||
boundary,
|
||||
generator: Some(generator),
|
||||
async_promise: None,
|
||||
annex_off: AnnexOff::new(),
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
|
||||
+22
-2
@@ -301,6 +301,8 @@ pub(crate) enum Class {
|
||||
Promise(Box<crate::builtins::promise::PromiseData>),
|
||||
/// The state that the functions a promise operation makes share; scripts never see it.
|
||||
PromiseRecord(Box<crate::builtins::promise::Record>),
|
||||
/// An async function's frame waiting at `await`, until it is resumed; scripts never see it.
|
||||
Activation(Option<Box<crate::interp::async_function::Activation>>),
|
||||
/// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added.
|
||||
Map(Box<Coll>),
|
||||
/// A `Set` (section 23.2): its values in the order they were added, each with `undefined`.
|
||||
@@ -609,7 +611,7 @@ impl Class {
|
||||
Class::XmlList(_) => "XMLList",
|
||||
Class::Namespace(_) => "Namespace",
|
||||
Class::QName { .. } => "QName",
|
||||
Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) => "Object",
|
||||
Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) | Class::Activation(_) => "Object",
|
||||
Class::Promise(_) => "Promise",
|
||||
Class::Math => "Math",
|
||||
Class::Json => "JSON",
|
||||
@@ -1105,6 +1107,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
|
||||
+ code.params.len()
|
||||
+ code.pattern_names.len()
|
||||
+ code.vars.len()
|
||||
+ code.annex_vars.len()
|
||||
+ 2 * code.fun_decls.len()
|
||||
+ code.templates.iter().map(|t| 2 + t.cooked.len() + t.raw.len()).sum::<usize>();
|
||||
let tables = code.finally_tables.iter().map(|t| 24 + 4 * t.len()).sum::<usize>();
|
||||
@@ -1128,7 +1131,14 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
|
||||
strings.add(pattern);
|
||||
strings.add(flags);
|
||||
}
|
||||
let keys = code.names.iter().chain(&code.params).chain(&code.pattern_names).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
|
||||
let keys = code
|
||||
.names
|
||||
.iter()
|
||||
.chain(&code.params)
|
||||
.chain(&code.pattern_names)
|
||||
.chain(&code.vars)
|
||||
.chain(&code.annex_vars)
|
||||
.chain(code.fun_decls.iter().map(|(k, _)| k));
|
||||
for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) {
|
||||
strings.add_key(k);
|
||||
}
|
||||
@@ -1298,6 +1308,16 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
}
|
||||
extra = crate::builtins::promise::RECORD_BYTES;
|
||||
}
|
||||
Class::Activation(Some(a)) => {
|
||||
for v in a.values() {
|
||||
mark_value(v, work, strings);
|
||||
}
|
||||
work.extend(a.ids());
|
||||
for code in a.codes() {
|
||||
mark_code(code, strings);
|
||||
}
|
||||
extra = a.bytes();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra
|
||||
|
||||
@@ -9,8 +9,9 @@
|
||||
//! 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.
|
||||
//! read of an ancestor or descendant of the held object's class with the same handle gives the
|
||||
//! object the script holds, now of the class that read names. A read of a class on another branch
|
||||
//! gives a new object, and the held object keeps its class.
|
||||
//!
|
||||
//! 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
|
||||
@@ -170,6 +171,18 @@ pub(crate) struct Reflected {
|
||||
pub(crate) info: MemberInfo,
|
||||
}
|
||||
|
||||
/// Whether class `a` is class `b` or descends from it, both indexes into `classes`.
|
||||
fn descends(classes: &[Entry], a: u32, b: u32) -> bool {
|
||||
let mut at = Some(a);
|
||||
while let Some(c) = at {
|
||||
if c == b {
|
||||
return true;
|
||||
}
|
||||
at = classes.get(c as usize).and_then(|e| e.parent);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
pub(crate) fn objects(&self) -> [ObjId; 2] {
|
||||
[self.proto, self.ctor]
|
||||
@@ -179,8 +192,9 @@ impl Entry {
|
||||
/// 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>;
|
||||
/// The objects made for each family of classes and handle ([`Interp::host_objects`]), one for each
|
||||
/// branch of the family a read named, oldest first.
|
||||
pub(crate) type Made = std::collections::HashMap<MadeKey, Vec<ObjId>>;
|
||||
|
||||
/// Whether `id` is still the object made for `key`, and not a freed cell or another object that
|
||||
/// was given its cell.
|
||||
@@ -195,7 +209,10 @@ fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey
|
||||
|
||||
/// 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));
|
||||
made.retain(|key, ids| {
|
||||
ids.retain(|id| is_made(heap, classes, *id, key));
|
||||
!ids.is_empty()
|
||||
});
|
||||
}
|
||||
|
||||
/// The [`Data`] that stands for the object of host class `class` with `handle`.
|
||||
@@ -295,16 +312,33 @@ impl Interp {
|
||||
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`.
|
||||
// The held object of `class` itself, or else the newest of an ancestor or descendant class,
|
||||
// which becomes one of `class`. An object of a class on another branch of the family keeps
|
||||
// its class, and a read of `class` with no such object gives a new object.
|
||||
let mut found = None;
|
||||
for &id in self.host_objects.get(&made).map(Vec::as_slice).unwrap_or_default() {
|
||||
if !is_made(&self.heap, &self.host_classes, id, &made) {
|
||||
continue;
|
||||
}
|
||||
let Class::Host(h) = &self.object(id)?.class else { continue };
|
||||
if h.class == class {
|
||||
found = Some(id);
|
||||
break;
|
||||
}
|
||||
if descends(&self.host_classes, h.class, class) || descends(&self.host_classes, class, h.class) {
|
||||
found = Some(id);
|
||||
}
|
||||
}
|
||||
if let Some(id) = found {
|
||||
// Its indexer and the indices its prototypes hold can change with its class, so a list
|
||||
// of the indices it has is made again ([`crate::heap::Heap::index_epoch`]).
|
||||
let o = self.object_mut(id)?;
|
||||
if let Class::Host(h) = &mut o.class
|
||||
&& h.class != class
|
||||
{
|
||||
h.class = class;
|
||||
o.proto = Some(proto);
|
||||
self.heap.index_epoch = self.heap.index_epoch.wrapping_add(1);
|
||||
}
|
||||
return Ok(Value::Object(id));
|
||||
}
|
||||
@@ -314,7 +348,13 @@ impl Interp {
|
||||
o.extensible = false;
|
||||
let id = self.heap.alloc_object(o);
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(extra);
|
||||
self.host_objects.insert(made, id);
|
||||
if let Some(ids) = self.host_objects.get_mut(&made) {
|
||||
let (heap, classes) = (&self.heap, &self.host_classes);
|
||||
ids.retain(|&old| old != id && is_made(heap, classes, old, &made));
|
||||
ids.push(id);
|
||||
} else {
|
||||
self.host_objects.insert(made, vec![id]);
|
||||
}
|
||||
Ok(Value::Object(id))
|
||||
}
|
||||
|
||||
@@ -452,9 +492,9 @@ struct Undo {
|
||||
/// replaced values stay in the interpreter's temporary roots until [`install`] returns, so a
|
||||
/// collection during the call does not free them.
|
||||
globals: Vec<(Key, Option<Prop>)>,
|
||||
/// The class and prototype of the object made for each family and handle before the call. An
|
||||
/// The class and prototype of each object made for a family and handle before the call. An
|
||||
/// instance of the call can give such an object one of the call's classes.
|
||||
objects: Vec<(MadeKey, u32, Option<ObjId>)>,
|
||||
objects: Vec<(MadeKey, ObjId, u32, Option<ObjId>)>,
|
||||
}
|
||||
|
||||
impl Undo {
|
||||
@@ -486,9 +526,9 @@ impl Undo {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (made, class, proto) in self.objects {
|
||||
let Some(&id) = i.host_objects.get(&made) else { continue };
|
||||
if is_made(&i.heap, &i.host_classes, id, &made)
|
||||
for (made, id, class, proto) in self.objects {
|
||||
if i.host_objects.get(&made).is_some_and(|ids| ids.contains(&id))
|
||||
&& is_made(&i.heap, &i.host_classes, id, &made)
|
||||
&& let Ok(o) = i.object_mut(id)
|
||||
&& let Class::Host(h) = &mut o.class
|
||||
{
|
||||
@@ -534,12 +574,14 @@ fn install_checked(
|
||||
install_class(i, class, members, undo)?;
|
||||
}
|
||||
if !instances.is_empty() {
|
||||
for (made, &id) in &i.host_objects {
|
||||
if is_made(&i.heap, &i.host_classes, id, made)
|
||||
&& let Ok(o) = i.object(id)
|
||||
&& let Class::Host(h) = &o.class
|
||||
{
|
||||
undo.objects.push((made.clone(), h.class, o.proto));
|
||||
for (made, ids) in &i.host_objects {
|
||||
for &id in ids {
|
||||
if is_made(&i.heap, &i.host_classes, id, made)
|
||||
&& let Ok(o) = i.object(id)
|
||||
&& let Class::Host(h) = &o.class
|
||||
{
|
||||
undo.objects.push((made.clone(), id, h.class, o.proto));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -931,6 +931,57 @@ fn the_handles_of_host_objects_given_to_the_host_count_toward_the_data_limits()
|
||||
assert_eq!(r.run("thing.take([thing, thing]) === undefined").unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_of_a_class_on_another_branch_gives_a_new_object() {
|
||||
let mut r = realm(1_000_000);
|
||||
let class = |name: &str, parent: Option<&str>| HostClass {
|
||||
name: name.into(),
|
||||
parent: parent.map(Into::into),
|
||||
members: Vec::new(),
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
let get: HostFunction = Rc::new(|a| match a.get(1) {
|
||||
Some(Data::String(name)) => Ok(host_ref(name, &[1.0])),
|
||||
_ => Ok(Data::Null),
|
||||
});
|
||||
let mut maker = class("Maker", None);
|
||||
maker.members.push(("get".into(), HostMember::Method(get)));
|
||||
let classes = vec![class("Base", None), class("Left", Some("Base")), class("Right", Some("Base")), class("Leaf", Some("Left")), maker];
|
||||
r.define_host_classes(classes, vec![("maker".into(), host_ref("Maker", &[]))]).unwrap();
|
||||
let script = "function get(n) { return maker.get(n); } var l = get('Left'), b = get('Base'), f = get('Leaf'); var r = get('Right'); \
|
||||
[l === b, b === f, f instanceof Leaf, r === l, r instanceof Right, l instanceof Leaf, get('Leaf') === l, \
|
||||
get('Right') === r, get('Base') === r].join()";
|
||||
assert_eq!(r.run(script).unwrap(), JsValue::String("true,true,true,false,true,true,true,true,true".into()));
|
||||
}
|
||||
|
||||
/// The path of a `File` a member of a host class gives is charged to the heap.
|
||||
#[test]
|
||||
fn the_path_of_a_file_a_host_class_gives_is_charged_to_the_heap() {
|
||||
let bytes_after = |len: usize| {
|
||||
let mut r = realm(1_000_000);
|
||||
let current: HostFunction = Rc::new(|_| Ok(Data::String("d".into())));
|
||||
// The host's `parse` gives the path it is handed as the platform path.
|
||||
let parse: HostFunction = Rc::new(|a| {
|
||||
let text = match a.first() {
|
||||
Some(Data::String(s)) => s.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
Ok(Data::Object(vec![("fs".into(), Data::String(text))]))
|
||||
});
|
||||
r.define_file_classes(vec![("current".into(), HostItem::Function(current)), ("parse".into(), HostItem::Function(parse))]).unwrap();
|
||||
let file: HostFunction = Rc::new(move |_| Ok(file_ref(&"p".repeat(len))));
|
||||
let members = vec![("file".to_string(), HostMember::Method(file))];
|
||||
let maker = HostClass { name: "Maker".into(), parent: None, members, info: Vec::new(), index: None, construct: None };
|
||||
r.define_host_classes(vec![maker], vec![("maker".into(), host_ref("Maker", &[]))]).unwrap();
|
||||
assert_eq!(r.run("var f = maker.file(); f instanceof File"), Ok(JsValue::Bool(true)));
|
||||
r.interp().heap.bytes
|
||||
};
|
||||
let (short, long) = (bytes_after(1), bytes_after(100_000));
|
||||
assert!(long >= short + 2 * 99_999, "{short} {long}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_class_constructor_called_with_new_cannot_wait() {
|
||||
let mut r = realm(1_000_000);
|
||||
@@ -946,6 +997,61 @@ fn a_host_class_constructor_called_with_new_cannot_wait() {
|
||||
assert_eq!(could.get(), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_on_a_host_constructor_that_gives_a_value_other_than_an_object_throws() {
|
||||
let mut r = realm(1_000_000);
|
||||
let make: HostFunction = Rc::new(|_| Ok(Data::Undefined));
|
||||
with_thing(&mut r, Some(make));
|
||||
let out = r.run("var e; try { new Thing(); } catch (x) { e = x; } [e instanceof TypeError, typeof Thing()].join()").unwrap();
|
||||
assert_eq!(out, JsValue::String("true,undefined".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_array_method_visits_every_element_after_its_object_takes_a_class_with_an_indexer() {
|
||||
let mut r = realm(10_000_000);
|
||||
// `Base` has a length of 5,000, an element `0` on its prototype and no indexer; `Indexed`, of
|
||||
// the same family, gives `list[i]` for each index. `upgrade()` gives the same object as an
|
||||
// `Indexed`.
|
||||
let length: HostFunction = Rc::new(|_| Ok(Data::Number(5_000.0)));
|
||||
let zero: HostFunction = Rc::new(|_| Ok(Data::Number(0.0)));
|
||||
let upgrade: HostFunction = Rc::new(|_| Ok(host_ref("Indexed", &[1.0])));
|
||||
let members = vec![
|
||||
("length".to_string(), HostMember::Get(length)),
|
||||
("0".to_string(), HostMember::Get(zero)),
|
||||
("upgrade".to_string(), HostMember::Method(upgrade)),
|
||||
];
|
||||
let base = HostClass { name: "Base".into(), parent: None, members, info: Vec::new(), index: None, construct: None };
|
||||
let index: HostFunction = Rc::new(|a| Ok(a.get(1).cloned().unwrap_or(Data::Undefined)));
|
||||
let indexed =
|
||||
HostClass { name: "Indexed".into(), parent: Some("Base".into()), members: Vec::new(), info: Vec::new(), index: Some(index), construct: None };
|
||||
r.define_host_classes(vec![base, indexed], vec![("list".into(), host_ref("Base", &[1.0]))]).unwrap();
|
||||
let out = r
|
||||
.run("var n = 0; Array.prototype.forEach.call(list, function () { if (n === 0) list.upgrade(); n++; }); [list instanceof Indexed, n].join()")
|
||||
.unwrap();
|
||||
assert_eq!(out, JsValue::String("true,5000".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_methods_visit_every_element_of_a_long_host_list() {
|
||||
let mut r = realm(10_000_000);
|
||||
// `list[i]` is `i` below 5,000, past the span the array methods visit without listing.
|
||||
let index: HostFunction = Rc::new(|a| {
|
||||
let i = a.get(1).and_then(|i| if let Data::Number(n) = i { Some(*n) } else { None });
|
||||
Ok(i.filter(|n| *n < 5_000.0).map_or(Data::Undefined, Data::Number))
|
||||
});
|
||||
let length: HostFunction = Rc::new(|_| Ok(Data::Number(5_000.0)));
|
||||
let members = vec![("length".to_string(), HostMember::Get(length))];
|
||||
let class = HostClass { name: "List".into(), parent: None, members, info: Vec::new(), index: Some(index), construct: None };
|
||||
r.define_host_classes(vec![class], vec![("list".into(), host_ref("List", &[1.0]))]).unwrap();
|
||||
let out = r
|
||||
.run(
|
||||
"var n = 0; Array.prototype.forEach.call(list, function () { n++; });\
|
||||
[Array.prototype.indexOf.call(list, 4999), Array.prototype.lastIndexOf.call(list, 0), n].join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, JsValue::String("4999,0,5000".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_of_a_host_class_report_its_available_members_as_their_own() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
+210
-31
@@ -123,6 +123,9 @@ impl ErrorType {
|
||||
pub(crate) struct Intrinsics {
|
||||
pub(crate) object_proto: ObjId,
|
||||
pub(crate) function_proto: ObjId,
|
||||
/// The built-in `Function`, which a script can replace as the global or as the prototype's
|
||||
/// `constructor`.
|
||||
pub(crate) function_ctor: ObjId,
|
||||
pub(crate) array_proto: ObjId,
|
||||
pub(crate) string_proto: ObjId,
|
||||
pub(crate) number_proto: ObjId,
|
||||
@@ -150,6 +153,7 @@ impl Intrinsics {
|
||||
Self {
|
||||
object_proto: o,
|
||||
function_proto: o,
|
||||
function_ctor: o,
|
||||
array_proto: o,
|
||||
string_proto: o,
|
||||
number_proto: o,
|
||||
@@ -186,6 +190,7 @@ impl Intrinsics {
|
||||
let mut v = vec![
|
||||
self.object_proto,
|
||||
self.function_proto,
|
||||
self.function_ctor,
|
||||
self.array_proto,
|
||||
self.string_proto,
|
||||
self.number_proto,
|
||||
@@ -207,6 +212,9 @@ impl Intrinsics {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of [`Frame::annex_off`], looked up once for each block function a frame assigns.
|
||||
pub(crate) type AnnexOff = std::collections::HashSet<Key>;
|
||||
|
||||
pub(crate) struct Frame {
|
||||
pub(crate) code: Rc<Code>,
|
||||
pub(crate) pc: usize,
|
||||
@@ -236,6 +244,12 @@ pub(crate) struct Frame {
|
||||
pub(crate) boundary: bool,
|
||||
/// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it.
|
||||
pub(crate) generator: Option<ObjId>,
|
||||
/// The promise of the async function the frame runs: a return resolves it, an exception
|
||||
/// that leaves the frame rejects it, and the call's value is the promise.
|
||||
pub(crate) async_promise: Option<ObjId>,
|
||||
/// The block functions of script or eval code ([`Code::annex_vars`]) whose variable was not
|
||||
/// declared: [`Op::AnnexB`] leaves them alone.
|
||||
pub(crate) annex_off: AnnexOff,
|
||||
/// The frame runs a module that another module of the same run waits under (ECMA-262 2015
|
||||
/// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception
|
||||
/// that leaves it ends the run at the boundary frame without stopping in the frames between.
|
||||
@@ -246,6 +260,8 @@ pub(crate) struct Frame {
|
||||
/// Where the exception being thrown was raised: the code and the instruction.
|
||||
pub(crate) type ThrowSite = (Rc<Code>, usize);
|
||||
|
||||
pub(crate) mod async_function;
|
||||
|
||||
/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time.
|
||||
pub(crate) type CodeObserver = Rc<dyn Fn(&[u16])>;
|
||||
|
||||
@@ -330,6 +346,10 @@ pub(crate) struct Interp {
|
||||
/// ECMAScript 2015 gives them ([`crate::builtins::es2015_names`]): set once the realm first
|
||||
/// reads code with [`Options::es2015`], and kept after that.
|
||||
pub(crate) builtin_names: bool,
|
||||
/// The [`Options::es2017`] a host set while a run was going, for the runs after it. It is
|
||||
/// applied after [`Self::next_es2015`], and the setters keep the two consistent with the
|
||||
/// order they were called in.
|
||||
pub(crate) next_es2017: Option<bool>,
|
||||
/// The template objects tagged templates have made, by code and template index, each with
|
||||
/// its code (ECMA-262 2015 section 12.2.9.3 keeps one object for each site).
|
||||
pub(crate) template_objects: std::collections::HashMap<(usize, u32), (Rc<Code>, ObjId)>,
|
||||
@@ -375,9 +395,9 @@ pub(crate) struct Interp {
|
||||
pub(crate) host_classes: Vec<crate::host_classes::Entry>,
|
||||
/// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`].
|
||||
pub(crate) write_hosted: bool,
|
||||
/// The object made for each 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.
|
||||
/// The objects 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 object that 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.
|
||||
@@ -675,7 +695,7 @@ fn declaration_bytes(code: &Code) -> usize {
|
||||
let closure = code.functions.get(*fi as usize).map_or(0, |f| closure_bytes(f));
|
||||
total.saturating_add(binding_bytes(name.len()) + closure)
|
||||
});
|
||||
code.vars.iter().fold(funs, |total, v| total.saturating_add(binding_bytes(v.len())))
|
||||
code.vars.iter().chain(&code.annex_vars).fold(funs, |total, v| total.saturating_add(binding_bytes(v.len())))
|
||||
}
|
||||
|
||||
/// At least the bytes that [`Interp::block_env`] adds to the heap for `code.scopes[i]`: the
|
||||
@@ -754,7 +774,8 @@ fn is(k: &[u16], s: &str) -> bool {
|
||||
}
|
||||
|
||||
impl Interp {
|
||||
pub(crate) fn new(options: Options, limits: Limits) -> Self {
|
||||
pub(crate) fn new(mut options: Options, limits: Limits) -> Self {
|
||||
options.es2015 = options.modern();
|
||||
let mut heap = Heap::default();
|
||||
let global = heap.alloc_object(Object::new(Class::Ordinary, None));
|
||||
let global_env = heap.alloc_env(Env::Obj { object: global, with_this: false, outer: None });
|
||||
@@ -774,6 +795,7 @@ impl Interp {
|
||||
next_es2015: None,
|
||||
es2015_installed: false,
|
||||
builtin_names: false,
|
||||
next_es2017: None,
|
||||
template_objects: std::collections::HashMap::new(),
|
||||
intrinsics: Intrinsics::placeholder(),
|
||||
fuel: u64::MAX,
|
||||
@@ -1074,7 +1096,9 @@ impl Interp {
|
||||
for f in &self.frames {
|
||||
roots.values.push(&f.this);
|
||||
roots.values.push(&f.completion);
|
||||
roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.new_target.iter()).chain(f.generator.iter()));
|
||||
roots
|
||||
.objects
|
||||
.extend(f.callee.iter().chain(f.construct.iter()).chain(f.new_target.iter()).chain(f.generator.iter()).chain(f.async_promise.iter()));
|
||||
roots.envs.extend(f.this_env);
|
||||
roots.envs.push(f.env);
|
||||
roots.envs.push(f.var_env);
|
||||
@@ -1119,7 +1143,11 @@ impl Interp {
|
||||
match self.step() {
|
||||
Ok(Some(v)) => return Ok(v),
|
||||
Ok(None) => {}
|
||||
Err(Abrupt::Throw(v)) => self.unwind(v)?,
|
||||
Err(Abrupt::Throw(v)) => {
|
||||
if let Some(v) = self.unwind_or_abort(v)? {
|
||||
return Ok(v);
|
||||
}
|
||||
}
|
||||
Err(other) => {
|
||||
self.note_site();
|
||||
self.abort_to_boundary();
|
||||
@@ -1138,7 +1166,11 @@ impl Interp {
|
||||
match self.step() {
|
||||
Ok(Some(v)) => return Ok(Some(v)),
|
||||
Ok(None) => {}
|
||||
Err(Abrupt::Throw(v)) => self.unwind(v)?,
|
||||
Err(Abrupt::Throw(v)) => {
|
||||
if let Some(v) = self.unwind_or_abort(v)? {
|
||||
return Ok(Some(v));
|
||||
}
|
||||
}
|
||||
Err(other) => {
|
||||
self.note_site();
|
||||
self.abort_to_boundary();
|
||||
@@ -1184,10 +1216,26 @@ impl Interp {
|
||||
}
|
||||
Op::GeneratorStart => self.op_generator_start(),
|
||||
Op::Yield(raw) => self.op_yield(raw),
|
||||
Op::Await => {
|
||||
let v = self.pop()?;
|
||||
self.await_value(v)
|
||||
}
|
||||
_ => self.exec(op).map(|()| None),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::unwind`], ending the frames down to the boundary frame when it fails with a limit
|
||||
/// or an internal error, which leaves the frame it was in on top.
|
||||
pub(crate) fn unwind_or_abort(&mut self, v: Value) -> JsResult<Option<Value>> {
|
||||
match self.unwind(v) {
|
||||
Err(e @ (Abrupt::Limit(_) | Abrupt::Internal(_))) => {
|
||||
self.abort_to_boundary();
|
||||
Err(e)
|
||||
}
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
fn note_site(&mut self) {
|
||||
if self.throw_site.is_none()
|
||||
&& let Some(f) = self.frames.last()
|
||||
@@ -1198,7 +1246,10 @@ impl Interp {
|
||||
|
||||
/// Finds the handler for an exception: in the top frame, or in the frames below it up to the
|
||||
/// boundary frame. Returns the exception when no handler takes it before the boundary frame.
|
||||
fn unwind(&mut self, v: Value) -> JsResult<()> {
|
||||
/// An async function's frame without a handler rejects its promise with the exception and
|
||||
/// returns the promise as a `return` would: `Some` with it when that frame was the boundary
|
||||
/// frame.
|
||||
fn unwind(&mut self, v: Value) -> JsResult<Option<Value>> {
|
||||
self.note_site();
|
||||
let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b);
|
||||
if !passed
|
||||
@@ -1237,11 +1288,26 @@ impl Interp {
|
||||
if let (false, Some(site)) = (caught, site) {
|
||||
self.finally_sites.push((site, target_len));
|
||||
}
|
||||
return Ok(());
|
||||
return Ok(None);
|
||||
}
|
||||
// The promise is settled while the frame is still on top, so a limit reached doing it
|
||||
// ends the frames the way any other limit does.
|
||||
let promise = frame.async_promise;
|
||||
if let Some(p) = promise {
|
||||
self.settle_async(p, Err(v.clone()))?;
|
||||
}
|
||||
let Some(frame) = self.pop_frame() else { return Err(Abrupt::Throw(v)) };
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
if let Some(p) = promise {
|
||||
self.drop_left_finally_marks();
|
||||
self.drop_left_finally_sites(frame.base);
|
||||
if frame.boundary {
|
||||
return Ok(Some(Value::Object(p)));
|
||||
}
|
||||
self.push(Value::Object(p))?;
|
||||
return Ok(None);
|
||||
}
|
||||
if frame.chained {
|
||||
// The modules under it have not started, so no handler of theirs takes it.
|
||||
self.abort_to_boundary();
|
||||
@@ -1305,9 +1371,24 @@ impl Interp {
|
||||
};
|
||||
let Some(frame) = self.pop_frame() else { return internal("return without a frame") };
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
|
||||
self.drop_left_finally_sites(frame.base);
|
||||
// An async function's return resolves its promise after the frame is off the frames, so
|
||||
// a `then` getter the resolution reads runs without it, and the call gives the promise.
|
||||
// Settling roots the promise and the value, and a rejection for returning the promise
|
||||
// itself is reported at the return. When settling fails, the frame goes back on top, so
|
||||
// the error is reported at the return and ends the frames down to its boundary.
|
||||
let v = match frame.async_promise {
|
||||
Some(p) => match self.resolve_async_return(p, v, Some((frame.code.clone(), frame.pc.saturating_sub(1)))) {
|
||||
Ok(()) => Value::Object(p),
|
||||
Err(e) => {
|
||||
self.frames.push(frame);
|
||||
return Err(e);
|
||||
}
|
||||
},
|
||||
None => v,
|
||||
};
|
||||
self.end_generator(frame.generator);
|
||||
let v = match frame.construct {
|
||||
Some(o) if !matches!(v, Value::Object(_)) => Value::Object(o),
|
||||
_ => v,
|
||||
@@ -1520,7 +1601,9 @@ impl Interp {
|
||||
Op::DelegateCall(t) => self.op_delegate_call(t),
|
||||
Op::DelegateResult(t) => self.op_delegate_result(t),
|
||||
Op::DelegateDone(t) => self.op_delegate_done(t),
|
||||
Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"),
|
||||
Op::Return | Op::ReturnCompletion | Op::Await | Op::GeneratorStart | Op::Yield(_) => {
|
||||
internal("a frame-ending instruction reached the dispatcher")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3018,8 +3101,13 @@ impl Interp {
|
||||
Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }),
|
||||
None => env,
|
||||
};
|
||||
let is_async = code.is_async;
|
||||
let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten();
|
||||
let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto);
|
||||
let proto = match (generator, self.promises.async_function_proto) {
|
||||
(Some((function_proto, _)), _) => function_proto,
|
||||
(None, Some(p)) if is_async => p,
|
||||
_ => self.intrinsics.function_proto,
|
||||
};
|
||||
let length = code.length;
|
||||
let strict = code.strict;
|
||||
let arrow = code.arrow;
|
||||
@@ -3052,6 +3140,15 @@ impl Interp {
|
||||
if arrow || method || class_ctor {
|
||||
return Ok(f);
|
||||
}
|
||||
// An async function has no `prototype` and cannot be constructed (ECMA-262 2017 section
|
||||
// 25.5.4), and must not have own `caller` or `arguments` properties, restricted or not, in
|
||||
// sloppy code too (section 16.2).
|
||||
if is_async {
|
||||
if let Some(name) = self_name {
|
||||
self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?;
|
||||
}
|
||||
return Ok(f);
|
||||
}
|
||||
let p = self.new_object();
|
||||
self.define(p, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?;
|
||||
self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?;
|
||||
@@ -3238,9 +3335,13 @@ impl Interp {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Assigns a function declared in a block to the variable of the same name.
|
||||
/// Assigns a function declared in a block to the variable of the same name, unless the
|
||||
/// variable of script or eval code was not declared.
|
||||
fn op_annex_b(&mut self, n: u32) -> JsResult<()> {
|
||||
let name = self.name(n)?;
|
||||
if self.frame()?.annex_off.contains(&name) {
|
||||
return self.pop().map(drop);
|
||||
}
|
||||
let v = self.peek(0)?;
|
||||
let var_env = self.frame()?.var_env;
|
||||
match self.heap.env(var_env) {
|
||||
@@ -3805,6 +3906,7 @@ impl Interp {
|
||||
/// the stack.
|
||||
pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
|
||||
let Entry { callee, code, env, this, args, new_target } = entry;
|
||||
let code_is_async = code.is_async;
|
||||
self.check_frame_room()?;
|
||||
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
|
||||
// An arrow function reads the `arguments` object of the function around it.
|
||||
@@ -3866,6 +3968,8 @@ impl Interp {
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
async_promise: None,
|
||||
annex_off: AnnexOff::new(),
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
@@ -3873,7 +3977,16 @@ impl Interp {
|
||||
};
|
||||
let r = enter();
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
r?;
|
||||
// An async function's call makes its promise first thing (section 25.5.5.2); the frame
|
||||
// keeps what the function holds reachable while it is made.
|
||||
if code_is_async && let Err(e) = self.start_async_call() {
|
||||
if let Some(frame) = self.frames.pop() {
|
||||
self.stack.truncate(frame.base);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Declaration binding instantiation for function code (section 10.5). Each parameter and
|
||||
@@ -4268,10 +4381,11 @@ impl Interp {
|
||||
};
|
||||
self.stack.truncate(start);
|
||||
self.check_frame_room()?;
|
||||
let env = self.instantiate_pending(&code, env, var_env, true)?;
|
||||
let (env, annex_off) = self.instantiate_pending(&code, env, var_env, true)?;
|
||||
self.push_code_frame(code, env, var_env, this, false)?;
|
||||
// The eval code reads `this` the way the code that called it does (section 18.2.1.1).
|
||||
let frame = self.frame_mut()?;
|
||||
frame.annex_off = annex_off;
|
||||
// The eval code reads `this` the way the code that called it does (section 18.2.1.1).
|
||||
frame.this_in_env = this_in_env;
|
||||
frame.new_target = new_target.and_then(|v| v.as_object());
|
||||
Ok(())
|
||||
@@ -4280,7 +4394,7 @@ impl Interp {
|
||||
/// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the
|
||||
/// code counted against the heap, until its frame holds them: the scopes and functions it
|
||||
/// makes can collect.
|
||||
fn instantiate_pending(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
|
||||
fn instantiate_pending(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> {
|
||||
let mark = self.temp_envs.len();
|
||||
self.temp_envs.push(env);
|
||||
self.temp_codes.push(code.clone());
|
||||
@@ -4306,7 +4420,9 @@ impl Interp {
|
||||
r
|
||||
}
|
||||
|
||||
/// Declares `code`'s variables and functions and pushes its boundary frame, ready to run.
|
||||
/// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. The
|
||||
/// frame limit and the heap, with a script's `let` and `const` names, are checked before
|
||||
/// anything is declared.
|
||||
pub(crate) fn enter_global(&mut self, code: Rc<Code>, is_eval: bool) -> JsResult<()> {
|
||||
// A script's `let` and `const` names are counted with its declarations, so none of them
|
||||
// is declared unless all of them fit.
|
||||
@@ -4322,8 +4438,10 @@ impl Interp {
|
||||
// The frame limit is checked before anything is declared, so a script that cannot start
|
||||
// leaves the global scope as it was.
|
||||
self.check_frame_room()?;
|
||||
let env = self.instantiate_pending(&code, env, var_env, is_eval)?;
|
||||
self.push_code_frame(code, env, var_env, Value::Object(global), true)
|
||||
let (env, annex_off) = self.instantiate_pending(&code, env, var_env, is_eval)?;
|
||||
self.push_code_frame(code, env, var_env, Value::Object(global), true)?;
|
||||
self.frame_mut()?.annex_off = annex_off;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The environment global code runs in: the one that holds the scripts' `let` and `const`
|
||||
@@ -4332,10 +4450,18 @@ impl Interp {
|
||||
self.global_lex
|
||||
}
|
||||
|
||||
/// Sets [`Options::es2015`] for the next runs. The first run with it on gives the built-in
|
||||
/// functions their ECMAScript 2015 `name` and `length` ([`crate::builtins::es2015_names`]).
|
||||
/// Sets [`Options::es2015`] for the next runs; turning it off turns [`Options::es2017`] off too.
|
||||
/// The first run with it on gives the built-in functions their ECMAScript 2015 `name` and
|
||||
/// `length` ([`crate::builtins::es2015_names`]).
|
||||
pub(crate) fn set_es2015(&mut self, es2015: bool) {
|
||||
self.options.es2015 = es2015;
|
||||
self.options.es2017 &= es2015;
|
||||
}
|
||||
|
||||
/// Sets [`Options::es2017`] for the next runs; turning it on turns [`Options::es2015`] on too.
|
||||
pub(crate) fn set_es2017(&mut self, es2017: bool) {
|
||||
self.options.es2017 = es2017;
|
||||
self.options.es2015 |= es2017;
|
||||
}
|
||||
|
||||
/// Declares a script's top-level `let` and `const` names in the global scope, uninitialized
|
||||
@@ -4446,6 +4572,8 @@ impl Interp {
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
async_promise: None,
|
||||
annex_off: AnnexOff::new(),
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
@@ -4463,7 +4591,8 @@ impl Interp {
|
||||
let scope = self.global_lex;
|
||||
let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
|
||||
self.temp_envs.push(env);
|
||||
let lex = self.instantiate_global(code, env, env, true)?;
|
||||
// Module code is strict, so no block function needs its variable left alone.
|
||||
let (lex, _annex_off) = self.instantiate_global(code, env, env, true)?;
|
||||
self.temp_envs.push(lex);
|
||||
Ok((lex, env))
|
||||
}
|
||||
@@ -4575,7 +4704,9 @@ impl Interp {
|
||||
/// global scope ([`Self::declare_global_lexical`]). Eval code outside strict mode code is
|
||||
/// checked against the `let` and `const` names around it ([`Self::check_eval_vars`]) with the
|
||||
/// option on or off, so it also meets the names that earlier runs of a kept realm declared.
|
||||
fn instantiate_global(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
|
||||
/// Also gives the names of [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not
|
||||
/// declare.
|
||||
fn instantiate_global(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> {
|
||||
// Strict eval code's own environment is in no frame yet, so it is a root while the
|
||||
// declarations reserve heap.
|
||||
let mark = self.temp_envs.len();
|
||||
@@ -4586,7 +4717,7 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// [`Self::instantiate_global`] with `env` and `var_env` in [`Self::temp_envs`].
|
||||
fn instantiate_global_rooted(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
|
||||
fn instantiate_global_rooted(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> {
|
||||
let configurable = if is_eval { CONFIGURABLE } else { 0 };
|
||||
if is_eval && !code.strict {
|
||||
self.check_eval_vars(code, env, var_env)?;
|
||||
@@ -4608,7 +4739,8 @@ impl Interp {
|
||||
// some of it (a script's names in the global scope were checked with the declarations
|
||||
// before they were added). Their environment stays reachable if the check collects.
|
||||
self.temp_envs.push(lex);
|
||||
let r = self.reserve_heap(declaration_bytes(code)).and_then(|()| self.declare_global_functions_and_vars(code, lex, var_env, configurable));
|
||||
let r =
|
||||
self.reserve_heap(declaration_bytes(code)).and_then(|()| self.declare_global_functions_and_vars(code, (env, lex), var_env, configurable));
|
||||
self.temp_envs.pop();
|
||||
if r.is_err() && global_lets {
|
||||
// A script that stops before it runs, at a limit, leaves none of its `let` and `const`
|
||||
@@ -4620,12 +4752,19 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
}
|
||||
r.map(|()| lex)
|
||||
r.map(|annex_off| (lex, annex_off))
|
||||
}
|
||||
|
||||
/// Declares the functions and variables of global or eval code for
|
||||
/// [`Self::instantiate_global_rooted`], each taking a unit of fuel.
|
||||
fn declare_global_functions_and_vars(&mut self, code: &Rc<Code>, lex: EnvId, var_env: EnvId, configurable: u8) -> JsResult<()> {
|
||||
/// [`Self::instantiate_global_rooted`], each taking a unit of fuel, and gives the names of
|
||||
/// [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not declare.
|
||||
fn declare_global_functions_and_vars(
|
||||
&mut self,
|
||||
code: &Rc<Code>,
|
||||
(env, lex): (EnvId, EnvId),
|
||||
var_env: EnvId,
|
||||
configurable: u8,
|
||||
) -> JsResult<AnnexOff> {
|
||||
// Functions close over the code's own environment with ES2015's scoping, and over its
|
||||
// variable environment otherwise (ECMA-262 5.1 section 13). When that is the global
|
||||
// object's, they close over the global scope inside it, which also holds the scripts'
|
||||
@@ -4656,7 +4795,47 @@ impl Interp {
|
||||
self.declare(var_env, v, None, configurable)?;
|
||||
self.note_global_var(on_global, v)?;
|
||||
}
|
||||
Ok(())
|
||||
let mut annex_off = AnnexOff::new();
|
||||
for v in &code.annex_vars {
|
||||
self.use_fuel()?;
|
||||
if !self.annex_var_declarable(v, env, var_env)? {
|
||||
annex_off.insert(v.clone());
|
||||
continue;
|
||||
}
|
||||
self.declare(var_env, v, None, configurable)?;
|
||||
if on_global {
|
||||
self.global_vars.insert(v.clone());
|
||||
}
|
||||
}
|
||||
Ok(annex_off)
|
||||
}
|
||||
|
||||
/// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and
|
||||
/// B.3.3.3, <https://tc39.es/ecma262/#sec-web-compat-globaldeclarationinstantiation>): no
|
||||
/// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch`
|
||||
/// parameter does not count, and on the global object the name is its own property or the
|
||||
/// object is extensible. Each environment passed takes a unit of fuel.
|
||||
fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult<bool> {
|
||||
let mut cur = Some(env).filter(|&e| e != var_env);
|
||||
while let Some(e) = cur {
|
||||
self.use_fuel()?;
|
||||
cur = match self.heap.env(e) {
|
||||
Some(Env::Decl { bindings, outer }) => {
|
||||
if bindings.get(name).is_some_and(|b| b.lexical) {
|
||||
return Ok(false);
|
||||
}
|
||||
*outer
|
||||
}
|
||||
Some(Env::Obj { outer, .. }) => *outer,
|
||||
None => return internal("environment out of range"),
|
||||
}
|
||||
.filter(|&o| o != var_env);
|
||||
}
|
||||
if var_env != self.global_env {
|
||||
return Ok(true);
|
||||
}
|
||||
let global = self.global;
|
||||
Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible)
|
||||
}
|
||||
|
||||
/// Adds `name`, which global code just declared, to [`Self::global_vars`] when `on_global`
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! An async function's frame while it waits at `await` (ECMA-262 2017 sections 25.5 and 6.2.3.1,
|
||||
//! <https://262.ecma-international.org/8.0/#await>): [`Interp::suspend_frame`] moves the running
|
||||
//! frame, its operands and its pending `finally` state into an [`Activation`], which lives on the
|
||||
//! heap inside the functions that resume it, and [`Interp::restore_frame`] puts it back on top of
|
||||
//! the frames to go on. An activation that nothing can resume any more is collected like any
|
||||
//! other object.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::{Frame, Interp, JsResult, ThrowSite, internal};
|
||||
use crate::bytecode::Code;
|
||||
use crate::heap::{EnvId, ObjId};
|
||||
use crate::value::Value;
|
||||
|
||||
/// The estimated bytes of an activation, beyond the object and its operands.
|
||||
pub(crate) const ACTIVATION_BYTES: usize = 128;
|
||||
/// The estimated bytes of each operand, `finally` mark or `finally` site an activation keeps.
|
||||
pub(crate) const SLOT_BYTES: usize = 16;
|
||||
|
||||
/// A suspended frame. Stack slots in `marks` and `sites` count from the frame's first operand.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Activation {
|
||||
code: Rc<Code>,
|
||||
pc: usize,
|
||||
env: EnvId,
|
||||
var_env: EnvId,
|
||||
env_depth: u32,
|
||||
this: Value,
|
||||
this_in_env: bool,
|
||||
strict_class: bool,
|
||||
callee: Option<ObjId>,
|
||||
new_target: Option<ObjId>,
|
||||
this_env: Option<EnvId>,
|
||||
completion: Value,
|
||||
/// The promise the async function's call returned.
|
||||
pub(crate) promise: ObjId,
|
||||
stack: Vec<Value>,
|
||||
marks: Vec<(ObjId, u32, usize)>,
|
||||
sites: Vec<(ThrowSite, usize)>,
|
||||
}
|
||||
|
||||
impl Activation {
|
||||
/// The values the activation holds, for the collector.
|
||||
pub(crate) fn values(&self) -> impl Iterator<Item = &Value> {
|
||||
self.stack.iter().chain([&self.this, &self.completion])
|
||||
}
|
||||
|
||||
/// The objects and environments the activation holds, for the collector.
|
||||
pub(crate) fn ids(&self) -> impl Iterator<Item = u32> {
|
||||
self.callee
|
||||
.iter()
|
||||
.chain(self.new_target.iter())
|
||||
.chain([&self.promise])
|
||||
.chain(self.marks.iter().map(|(o, _, _)| o))
|
||||
.map(|o| o.0)
|
||||
.chain([self.env.0, self.var_env.0])
|
||||
.chain(self.this_env.iter().map(|e| e.0))
|
||||
}
|
||||
|
||||
/// The code the activation runs and the code of its `finally` sites, for the collector.
|
||||
pub(crate) fn codes(&self) -> impl Iterator<Item = &Code> {
|
||||
std::iter::once(&*self.code).chain(self.sites.iter().map(|((code, _), _)| &**code))
|
||||
}
|
||||
|
||||
/// The estimated bytes of the activation, beyond the object.
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(self.stack.len() + self.marks.len() + self.sites.len()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Interp {
|
||||
/// The promise of the async function the top frame runs, when it runs one.
|
||||
pub(crate) fn async_promise(&self) -> Option<ObjId> {
|
||||
self.frames.last().and_then(|f| f.async_promise)
|
||||
}
|
||||
|
||||
/// Makes the promise of the async function call whose frame was just pushed.
|
||||
pub(crate) fn start_async_call(&mut self) -> JsResult<()> {
|
||||
let p = self.new_async_promise()?;
|
||||
match self.frames.last_mut() {
|
||||
Some(f) => {
|
||||
f.async_promise = Some(p);
|
||||
Ok(())
|
||||
}
|
||||
None => internal("an async call without a frame"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes [`Self::suspend_frame`] will move off the operand stack, for the heap check made
|
||||
/// before it.
|
||||
pub(crate) fn suspend_bytes(&self) -> usize {
|
||||
let Some(f) = self.frames.last() else { return ACTIVATION_BYTES };
|
||||
let n = self.stack.len().saturating_sub(f.base)
|
||||
+ self.finally_marks.iter().filter(|&&(_, _, s)| s >= f.base).count()
|
||||
+ self.finally_sites.iter().filter(|&&(_, s)| s >= f.base).count();
|
||||
ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(n))
|
||||
}
|
||||
|
||||
/// Takes the top frame, which runs an async function, off the frames with its operands and
|
||||
/// its `finally` state. Gives the activation and whether the frame was a boundary frame.
|
||||
pub(crate) fn suspend_frame(&mut self) -> JsResult<(Activation, bool)> {
|
||||
let Some(frame) = self.frames.pop() else { return internal("await without a frame") };
|
||||
let Some(promise) = frame.async_promise else { return internal("await outside an async function") };
|
||||
let base = frame.base;
|
||||
if self.stack.len() < base {
|
||||
return internal("frame operands below the stack");
|
||||
}
|
||||
let stack = self.stack.split_off(base);
|
||||
let mut marks = Vec::new();
|
||||
self.finally_marks.retain(|&(o, mark, slot)| {
|
||||
if slot < base {
|
||||
return true;
|
||||
}
|
||||
marks.push((o, mark, slot - base));
|
||||
false
|
||||
});
|
||||
let at = self.finally_sites.iter().position(|&(_, slot)| slot >= base).unwrap_or(self.finally_sites.len());
|
||||
let sites = self.finally_sites.split_off(at).into_iter().map(|(site, slot)| (site, slot - base)).collect();
|
||||
let activation = Activation {
|
||||
code: frame.code,
|
||||
pc: frame.pc,
|
||||
env: frame.env,
|
||||
var_env: frame.var_env,
|
||||
env_depth: frame.env_depth,
|
||||
this: frame.this,
|
||||
this_in_env: frame.this_in_env,
|
||||
strict_class: frame.strict_class,
|
||||
callee: frame.callee,
|
||||
new_target: frame.new_target,
|
||||
this_env: frame.this_env,
|
||||
completion: frame.completion,
|
||||
promise,
|
||||
stack,
|
||||
marks,
|
||||
sites,
|
||||
};
|
||||
Ok((activation, frame.boundary))
|
||||
}
|
||||
|
||||
/// Puts a suspended frame back on top of the frames as a boundary frame, with its operands at
|
||||
/// the top of the operand stack.
|
||||
pub(crate) fn restore_frame(&mut self, a: Activation) -> JsResult<()> {
|
||||
if self.frames.len() >= self.limits.frames {
|
||||
return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Frames));
|
||||
}
|
||||
let base = self.stack.len();
|
||||
for v in a.stack {
|
||||
self.push(v)?;
|
||||
}
|
||||
self.finally_marks.extend(a.marks.into_iter().map(|(o, mark, slot)| (o, mark, slot + base)));
|
||||
self.finally_sites.extend(a.sites.into_iter().map(|(site, slot)| (site, slot + base)));
|
||||
self.frames.push(Frame {
|
||||
code: a.code,
|
||||
pc: a.pc,
|
||||
base,
|
||||
env: a.env,
|
||||
var_env: a.var_env,
|
||||
env_depth: a.env_depth,
|
||||
this: a.this,
|
||||
this_in_env: a.this_in_env,
|
||||
strict_class: a.strict_class,
|
||||
callee: a.callee,
|
||||
construct: None,
|
||||
new_target: a.new_target,
|
||||
this_env: a.this_env,
|
||||
completion: a.completion,
|
||||
boundary: true,
|
||||
generator: None,
|
||||
async_promise: Some(a.promise),
|
||||
annex_off: super::AnnexOff::new(),
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1029,6 +1029,7 @@ fn code(ops: Vec<Op>) -> Code {
|
||||
params: Vec::new(),
|
||||
vars: Vec::new(),
|
||||
fun_decls: Vec::new(),
|
||||
annex_vars: Vec::new(),
|
||||
uses_arguments: false,
|
||||
source,
|
||||
span: (0, 0),
|
||||
@@ -1048,6 +1049,7 @@ fn code(ops: Vec<Op>) -> Code {
|
||||
own_name: None,
|
||||
method: false,
|
||||
generator: false,
|
||||
is_async: false,
|
||||
supers: crate::parser::SuperRules::default(),
|
||||
}
|
||||
}
|
||||
|
||||
+25
-1
@@ -126,6 +126,10 @@
|
||||
//! ECMAScript 2020 defines them (sections 26.1 and 26.2 and 9.5,
|
||||
//! <https://262.ecma-international.org/11.0/>), with string and Symbol property keys: a trap is
|
||||
//! given either kind of key, an `ownKeys` trap may return both, and `Reflect.ownKeys` lists both.
|
||||
//!
|
||||
//! With [`Options::es2017`], the parser and the realm also read and run async functions and
|
||||
//! `await` (ECMA-262 2017 section 25.5, <https://262.ecma-international.org/8.0/#sec-async-function-objects>).
|
||||
//! An `await` suspends its function's frame until the value settles, and a promise job resumes it.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
@@ -220,11 +224,29 @@ pub struct Options {
|
||||
/// `Promise` to a realm made without it. Runs with it on also convert `0b` and `0o` strings to
|
||||
/// numbers.
|
||||
pub es2015: bool,
|
||||
/// Also read and run async functions and `await` (ECMAScript 2017). It turns on
|
||||
/// [`Options::es2015`] too, whatever that field says. Off, `async` and `await` are identifiers.
|
||||
pub es2017: bool,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
/// [`Options::es2015`], which [`Options::es2017`] turns on too.
|
||||
pub(crate) fn modern(&self) -> bool {
|
||||
self.es2015 || self.es2017
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false }
|
||||
Self {
|
||||
strict: false,
|
||||
preprocessor_lines: false,
|
||||
max_depth: DEFAULT_MAX_DEPTH,
|
||||
max_source_units: 64 << 20,
|
||||
e4x: false,
|
||||
es2015: false,
|
||||
es2017: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,6 +377,8 @@ impl LineTable {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod async_tests;
|
||||
#[cfg(test)]
|
||||
mod builtins_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
+258
-45
@@ -47,6 +47,23 @@ struct Context {
|
||||
/// The code is a generator function's body or parameters: `yield` starts a yield expression
|
||||
/// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4).
|
||||
generator: bool,
|
||||
/// The code is an async function's body: `await` is an operator, not an identifier.
|
||||
in_async: bool,
|
||||
/// The code is an async function's parameters: `await` is neither an operator nor an
|
||||
/// identifier there (ECMA-262 2017 section 14.6.1).
|
||||
async_params: bool,
|
||||
}
|
||||
|
||||
/// What the parser noted about a parenthesized expression or a call to `async` that may turn out
|
||||
/// to be an arrow function's head.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Head {
|
||||
/// A line break comes between `async` and `(`.
|
||||
line_break: bool,
|
||||
/// The parentheses hold an `await` expression or the identifier `await`.
|
||||
awaits: bool,
|
||||
/// A comma follows the last item in the parentheses.
|
||||
trailing_comma: bool,
|
||||
}
|
||||
|
||||
/// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations
|
||||
@@ -104,6 +121,8 @@ enum BinKind {
|
||||
enum Prefix {
|
||||
Unary(UnaryOp),
|
||||
Update(UpdateOp),
|
||||
/// `await`, in an async function's body.
|
||||
Await,
|
||||
}
|
||||
|
||||
pub(crate) struct Parser<'s> {
|
||||
@@ -154,11 +173,20 @@ pub(crate) struct Parser<'s> {
|
||||
/// Where each yield expression read so far starts, in the order read, so the parameters of a
|
||||
/// generator function and an arrow function's head can be checked for one.
|
||||
yields: Vec<u32>,
|
||||
/// Read async functions and `await` ([`crate::Options::es2017`]).
|
||||
es2017: bool,
|
||||
/// How many `await` expressions and `await` identifiers have been read.
|
||||
awaits: u32,
|
||||
/// The parenthesized expressions and calls to `async` read so far that may be arrow heads.
|
||||
heads: HashMap<ExprId, Head>,
|
||||
/// The last identifier expression read from an `async` written without escapes.
|
||||
async_ident: Option<ExprId>,
|
||||
}
|
||||
|
||||
impl<'s> Parser<'s> {
|
||||
pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result<Self> {
|
||||
let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(options.es2015);
|
||||
let es2015 = options.modern();
|
||||
let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(es2015);
|
||||
let placeholder =
|
||||
Token { kind: TokenKind::Eof, span: Span::default(), line: 1, column: 1, newline_before: false, escaped: false, legacy_octal: false };
|
||||
let mut parser = Self {
|
||||
@@ -176,8 +204,12 @@ impl<'s> Parser<'s> {
|
||||
function_allowed: false,
|
||||
in_list: false,
|
||||
e4x: options.e4x,
|
||||
es2015: options.es2015,
|
||||
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
|
||||
es2015,
|
||||
scopes: if es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
|
||||
es2017: options.es2017,
|
||||
awaits: 0,
|
||||
heads: HashMap::new(),
|
||||
async_ident: None,
|
||||
supers: SuperRules::default(),
|
||||
module: false,
|
||||
cover_inits: Vec::new(),
|
||||
@@ -349,6 +381,9 @@ impl<'s> Parser<'s> {
|
||||
if self.ctx.generator && name == "yield" {
|
||||
return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function"));
|
||||
}
|
||||
if name == "await" && (self.ctx.in_async || self.ctx.async_params) {
|
||||
return Err(self.error_at_token(token, "'await' cannot be an identifier in an async function"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -358,6 +393,17 @@ impl<'s> Parser<'s> {
|
||||
self.yields.get(i).is_some_and(|&y| y < end)
|
||||
}
|
||||
|
||||
/// The current token is `async` written without escapes, read as the start of an async
|
||||
/// function or arrow function only with [`crate::Options::es2017`].
|
||||
fn at_async(&self) -> bool {
|
||||
self.es2017 && self.tok.ident() == Some("async") && !self.tok.escaped
|
||||
}
|
||||
|
||||
/// The current token is `async` and `function` follows it on the same line: an async function.
|
||||
fn at_async_function(&self) -> bool {
|
||||
self.at_async() && self.peek().is_some_and(|t| t.is_keyword(Keyword::Function) && !t.newline_before)
|
||||
}
|
||||
|
||||
/// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does,
|
||||
/// and in strict code neither `eval` nor `arguments`.
|
||||
fn binding_identifier(&mut self) -> Result<Name> {
|
||||
@@ -369,6 +415,9 @@ impl<'s> Parser<'s> {
|
||||
if self.ctx.strict && is_eval_or_arguments(&name) {
|
||||
return Err(self.error_at_token(&self.tok, format!("'{name}' cannot be declared in strict mode")));
|
||||
}
|
||||
if name == "await" {
|
||||
self.awaits = self.awaits.saturating_add(1);
|
||||
}
|
||||
let token = self.bump()?;
|
||||
Ok(Name { name, span: token.span })
|
||||
}
|
||||
@@ -438,7 +487,11 @@ impl<'s> Parser<'s> {
|
||||
/// Declares a function declaration that stands in a statement list: var-scoped in a function
|
||||
/// body or the script, lexical in a block.
|
||||
fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> {
|
||||
let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) };
|
||||
let Some(f) = self.ast.function(id) else { return Ok(()) };
|
||||
let Some(name) = f.name.clone() else { return Ok(()) };
|
||||
// Only plain function declarations may repeat in a block (Annex B.3.3.4), not generator
|
||||
// or async ones.
|
||||
let plain = !f.is_async && !f.generator;
|
||||
if self.module && self.scopes.len() == 1 {
|
||||
return self.declare_lexical(&name, true);
|
||||
}
|
||||
@@ -450,8 +503,7 @@ impl<'s> Parser<'s> {
|
||||
scope.vars.insert(name.name);
|
||||
Ok(())
|
||||
}
|
||||
// Only plain function declarations may repeat in a block (Annex B.3.3.4).
|
||||
Some(_) => self.declare_lexical(&name, !generator),
|
||||
Some(_) => self.declare_lexical(&name, plain),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -565,7 +617,7 @@ impl<'s> Parser<'s> {
|
||||
|
||||
/// A source element: a function declaration or a statement.
|
||||
fn parse_statement_item(&mut self) -> Result<StmtId> {
|
||||
if self.at_keyword(Keyword::Function) {
|
||||
if self.at_keyword(Keyword::Function) || self.at_async_function() {
|
||||
self.enter()?;
|
||||
let result = self.parse_function_declaration();
|
||||
self.leave();
|
||||
@@ -631,6 +683,9 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
self.parse_function_declaration()
|
||||
}
|
||||
TokenKind::Ident(_) if self.at_async_function() => {
|
||||
Err(self.error_at_token(&self.tok, "an async function declaration cannot stand here; put it in a block"))
|
||||
}
|
||||
TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list),
|
||||
_ => self.plain_statement(start),
|
||||
}
|
||||
@@ -1138,10 +1193,13 @@ impl<'s> Parser<'s> {
|
||||
// ---- functions ----
|
||||
|
||||
fn parse_function_declaration(&mut self) -> Result<StmtId> {
|
||||
let start = self.expect_keyword(Keyword::Function)?.span;
|
||||
let generator = self.es2015 && self.eat(Punct::Star)?;
|
||||
let is_async = self.at_async();
|
||||
let start = if is_async { self.bump()?.span } else { self.tok.span };
|
||||
self.expect_keyword(Keyword::Function)?;
|
||||
// Async generators (ECMAScript 2018) stay syntax errors: the `*` is not read after `async`.
|
||||
let generator = !is_async && self.es2015 && self.eat(Punct::Star)?;
|
||||
let name = self.function_name()?;
|
||||
let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
|
||||
let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, is_async)?;
|
||||
Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start)))
|
||||
}
|
||||
|
||||
@@ -1157,20 +1215,22 @@ impl<'s> Parser<'s> {
|
||||
Ok((Name { name, span: token.span }, token))
|
||||
}
|
||||
|
||||
/// The parameters and body of a function, from `(`; with `generator`, a generator function's.
|
||||
/// The parameters and body of a function, from `(`; with `generator`, a generator function's,
|
||||
/// and with `is_async`, an async function's.
|
||||
fn parse_function_rest(
|
||||
&mut self,
|
||||
kind: FunctionKind,
|
||||
name: Option<(Name, Token)>,
|
||||
start: Span,
|
||||
generator: bool,
|
||||
is_async: bool,
|
||||
) -> Result<crate::ast::FunctionId> {
|
||||
self.parse_function_with(kind, name, start, false, generator)
|
||||
self.parse_function_with(kind, name, start, false, generator, is_async)
|
||||
}
|
||||
|
||||
/// The parameters and body of a function, from `(`; `home` for one defined in a class body or
|
||||
/// as a method of an object literal, where `super.property` may stand, and with `generator`, a
|
||||
/// generator function's.
|
||||
/// as a method of an object literal, where `super.property` may stand, with `generator`, a
|
||||
/// generator function's, and with `is_async`, an async function's.
|
||||
fn parse_function_with(
|
||||
&mut self,
|
||||
kind: FunctionKind,
|
||||
@@ -1178,6 +1238,7 @@ impl<'s> Parser<'s> {
|
||||
start: Span,
|
||||
home: bool,
|
||||
generator: bool,
|
||||
is_async: bool,
|
||||
) -> Result<crate::ast::FunctionId> {
|
||||
self.enter()?;
|
||||
let rules = SuperRules::function(home, kind == FunctionKind::DerivedConstructor);
|
||||
@@ -1185,7 +1246,16 @@ impl<'s> Parser<'s> {
|
||||
// The parameters are read with the function's own `yield` rule, not the enclosing code's.
|
||||
let outer_generator = std::mem::replace(&mut self.ctx.generator, generator);
|
||||
let yields = self.yields.len();
|
||||
let result = self.function_rest(kind, name, start, home, generator);
|
||||
// The parameters are read with `await` as the function has it, then the code around
|
||||
// them goes on as it was.
|
||||
// An `await` inside the function does not count for an arrow function's head around it.
|
||||
let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits);
|
||||
self.ctx.in_async = false;
|
||||
self.ctx.async_params = is_async;
|
||||
let result = self.function_rest(kind, name, start, home, generator, is_async);
|
||||
self.ctx.in_async = in_async;
|
||||
self.ctx.async_params = async_params;
|
||||
self.awaits = awaits;
|
||||
// The `yield` expressions of this function are not in the code around it.
|
||||
self.yields.truncate(yields);
|
||||
self.ctx.generator = outer_generator;
|
||||
@@ -1201,6 +1271,7 @@ impl<'s> Parser<'s> {
|
||||
start: Span,
|
||||
home: bool,
|
||||
generator: bool,
|
||||
is_async: bool,
|
||||
) -> Result<crate::ast::FunctionId> {
|
||||
let params_start = self.tok.span.start;
|
||||
self.expect(Punct::LParen)?;
|
||||
@@ -1254,7 +1325,7 @@ impl<'s> Parser<'s> {
|
||||
self.expect(Punct::LBrace)?;
|
||||
let names: Vec<String> = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect();
|
||||
let outer_strict = self.ctx.strict;
|
||||
let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() };
|
||||
let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, generator, ..Context::default() };
|
||||
let outer = std::mem::replace(&mut self.ctx, inner);
|
||||
self.push_scope(true, names);
|
||||
let body = self.parse_body(true);
|
||||
@@ -1263,14 +1334,18 @@ impl<'s> Parser<'s> {
|
||||
self.ctx = outer;
|
||||
let body = body?;
|
||||
self.expect(Punct::RBrace)?;
|
||||
let function =
|
||||
Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start), home };
|
||||
let span = self.span_from(start);
|
||||
let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, is_async, span, home };
|
||||
// An async declaration or expression takes FormalParameters as a plain function does
|
||||
// (ECMA-262 2017 section 14.6): repeated simple names are an error only in strict code.
|
||||
// Arrow functions and async methods reject every repeat.
|
||||
self.check_params(&function, use_strict)?;
|
||||
Ok(self.ast.push_function(function))
|
||||
}
|
||||
|
||||
/// An arrow function's body and the function, from `=>`, with its parameters read.
|
||||
fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool) -> Result<ExprId> {
|
||||
/// An arrow function's body and the function, from `=>`, with its parameters read; with
|
||||
/// `is_async`, an async arrow function's.
|
||||
fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool, is_async: bool) -> Result<ExprId> {
|
||||
if self.tok.newline_before {
|
||||
return Err(self.error_at_token(&self.tok, "a line break cannot come before '=>'"));
|
||||
}
|
||||
@@ -1278,8 +1353,10 @@ impl<'s> Parser<'s> {
|
||||
self.enter()?;
|
||||
let names: Vec<String> = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect();
|
||||
let outer_strict = self.ctx.strict;
|
||||
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
|
||||
let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() };
|
||||
let outer = std::mem::replace(&mut self.ctx, inner);
|
||||
// An `await` in the body does not count for an async arrow function's head around it.
|
||||
let awaits = self.awaits;
|
||||
self.push_scope(true, names);
|
||||
let block = self.at(Punct::LBrace);
|
||||
let body = if block {
|
||||
@@ -1288,6 +1365,7 @@ impl<'s> Parser<'s> {
|
||||
self.parse_assignment(no_in).map(|e| vec![self.ast.push_stmt(Stmt::Return(Some(e)), self.ast.expr_span(e))])
|
||||
};
|
||||
self.pop_scope();
|
||||
self.awaits = awaits;
|
||||
let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict);
|
||||
self.ctx = outer;
|
||||
self.leave();
|
||||
@@ -1305,6 +1383,7 @@ impl<'s> Parser<'s> {
|
||||
body,
|
||||
strict,
|
||||
generator: false,
|
||||
is_async,
|
||||
span: self.span_from(start),
|
||||
home: false,
|
||||
};
|
||||
@@ -1323,6 +1402,13 @@ impl<'s> Parser<'s> {
|
||||
Some(Expr::Sequence(list)) => list.clone(),
|
||||
_ => vec![*inner],
|
||||
};
|
||||
self.arrow_items(items)
|
||||
}
|
||||
|
||||
/// The parameters the items of an arrow function's head give: names, names with `= default`,
|
||||
/// and a last `...name`.
|
||||
fn arrow_items(&mut self, items: Vec<ExprId>) -> Result<Params> {
|
||||
let invalid = |p: &Self, at: ExprId| p.error_at_offset(p.ast.expr_span(at).start, "invalid arrow function parameters");
|
||||
let (mut params, mut defaults, mut rest) = (Vec::new(), Vec::new(), None);
|
||||
let count = items.len();
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
@@ -1426,10 +1512,12 @@ impl<'s> Parser<'s> {
|
||||
fn assignment(&mut self, no_in: bool) -> Result<ExprId> {
|
||||
let mut targets: Vec<(ExprId, AssignOp)> = Vec::new();
|
||||
loop {
|
||||
// `async` followed on its line by a name starts an async arrow function.
|
||||
let async_name = self.at_async() && self.peek().is_some_and(|t| matches!(t.kind, TokenKind::Ident(_)) && !t.newline_before);
|
||||
let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped {
|
||||
self.parse_yield(no_in)?
|
||||
} else {
|
||||
let mut expr = self.parse_conditional(no_in)?;
|
||||
let mut expr = if async_name { self.parse_async_name_arrow(no_in)? } else { self.parse_conditional(no_in)? };
|
||||
if self.es2015 && self.at(Punct::Arrow) {
|
||||
expr = self.arrow_from(expr, no_in)?;
|
||||
}
|
||||
@@ -1475,12 +1563,46 @@ impl<'s> Parser<'s> {
|
||||
if self.yield_between(start.start, start.end) {
|
||||
return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters"));
|
||||
}
|
||||
let params = match self.ast.expr(expr) {
|
||||
Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None),
|
||||
Some(Expr::Paren(_)) => self.arrow_params(expr)?,
|
||||
let head = self.heads.get(&expr).copied();
|
||||
let (params, is_async) = match self.ast.expr(expr) {
|
||||
Some(Expr::Ident(name)) => ((vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None), false),
|
||||
Some(Expr::Paren(_)) => (self.arrow_params(expr)?, false),
|
||||
// `async (…) =>` was read as a call to `async` (ECMA-262 2017 section 14.7).
|
||||
Some(Expr::Call { args, .. }) if head.is_some() => {
|
||||
if head.is_some_and(|h| h.line_break) {
|
||||
return Err(self.error_at_offset(start.start, "a line break cannot come after 'async' in an async arrow function"));
|
||||
}
|
||||
// No comma may follow a rest parameter (ECMA-262 2017 section 14.1).
|
||||
if let Some(&last) = args.last()
|
||||
&& head.is_some_and(|h| h.trailing_comma)
|
||||
&& matches!(self.ast.expr(last), Some(Expr::Spread(_)))
|
||||
{
|
||||
return Err(self.error_at_offset(self.ast.expr_span(last).start, "a rest parameter must be the last parameter"));
|
||||
}
|
||||
(self.arrow_items(args.clone())?, true)
|
||||
}
|
||||
_ => return Err(self.unexpected()),
|
||||
};
|
||||
self.parse_arrow(start, params, no_in)
|
||||
// `await` cannot be an arrow function's parameter, or stand in one's default value,
|
||||
// where it is an operator or in an async arrow function's head.
|
||||
if head.is_some_and(|h| h.awaits) && (is_async || self.ctx.in_async) {
|
||||
return Err(self.error_at_offset(start.start, "'await' cannot stand in an arrow function's parameters here"));
|
||||
}
|
||||
self.parse_arrow(start, params, no_in, is_async)
|
||||
}
|
||||
|
||||
/// `async name => …` from `async` (ECMA-262 2017 section 14.7): the one parameter is read as
|
||||
/// an async function's is.
|
||||
fn parse_async_name_arrow(&mut self, no_in: bool) -> Result<ExprId> {
|
||||
let start = self.bump()?.span;
|
||||
let async_params = std::mem::replace(&mut self.ctx.async_params, true);
|
||||
let param = self.binding_identifier();
|
||||
self.ctx.async_params = async_params;
|
||||
let param = param?;
|
||||
if !self.at(Punct::Arrow) {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok))));
|
||||
}
|
||||
self.parse_arrow(start, (vec![Binding::Name(param)], vec![None], None), no_in, true)
|
||||
}
|
||||
|
||||
/// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code
|
||||
@@ -1571,7 +1693,17 @@ impl<'s> Parser<'s> {
|
||||
/// Prefix operators, read with a loop and applied innermost first.
|
||||
fn parse_unary(&mut self) -> Result<ExprId> {
|
||||
let mut prefixes = Vec::new();
|
||||
while let Some(prefix) = prefix_op(&self.tok) {
|
||||
loop {
|
||||
// In an async function's body, `await` is a prefix operator (ECMA-262 2017 section 14.6).
|
||||
let prefix = if self.ctx.in_async && self.tok.ident() == Some("await") {
|
||||
if self.tok.escaped {
|
||||
return Err(self.error_at_token(&self.tok, "keyword 'await' must not contain escaped characters"));
|
||||
}
|
||||
Prefix::Await
|
||||
} else {
|
||||
let Some(prefix) = prefix_op(&self.tok) else { break };
|
||||
prefix
|
||||
};
|
||||
prefixes.push((prefix, self.tok.span));
|
||||
self.bump()?;
|
||||
}
|
||||
@@ -1589,6 +1721,10 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
self.ast.push_expr(Expr::Unary { op, arg: expr }, span)
|
||||
}
|
||||
Prefix::Await => {
|
||||
self.awaits = self.awaits.saturating_add(1);
|
||||
self.ast.push_expr(Expr::Await(expr), span)
|
||||
}
|
||||
};
|
||||
}
|
||||
Ok(expr)
|
||||
@@ -1650,12 +1786,23 @@ impl<'s> Parser<'s> {
|
||||
expr = self.ast.push_expr(Expr::TaggedTemplate { tag: expr, quasis, exprs }, span);
|
||||
}
|
||||
TokenKind::Punct(Punct::LParen) => {
|
||||
let args = self.parse_arguments()?;
|
||||
let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr);
|
||||
let line_break = self.tok.newline_before;
|
||||
let awaits = self.awaits;
|
||||
// The arguments of a possible async arrow function's head may be patterns
|
||||
// such as `{a = 1}`; they are checked as expressions once no `=>` follows.
|
||||
let mark = self.cover_inits.len();
|
||||
let (args, trailing_comma) = self.arguments(async_head)?;
|
||||
let span = Span::new(self.ast.expr_span(expr).start, self.prev_end);
|
||||
expr = match news.pop() {
|
||||
Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)),
|
||||
None => self.ast.push_expr(Expr::Call { callee: expr, args }, span),
|
||||
};
|
||||
if async_head && self.at(Punct::Arrow) {
|
||||
self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits, trailing_comma });
|
||||
} else if async_head {
|
||||
self.check_cover(mark)?;
|
||||
}
|
||||
}
|
||||
TokenKind::Punct(Punct::QuestionDot) => {
|
||||
if !news.is_empty() {
|
||||
@@ -1802,19 +1949,33 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
|
||||
fn parse_arguments(&mut self) -> Result<Vec<ExprId>> {
|
||||
Ok(self.arguments(false)?.0)
|
||||
}
|
||||
|
||||
/// An argument list, and whether a comma follows its last argument. With `cover`, the
|
||||
/// arguments may hold initializers such as `{a = 1}`, which the caller checks.
|
||||
fn arguments(&mut self, cover: bool) -> Result<(Vec<ExprId>, bool)> {
|
||||
self.expect(Punct::LParen)?;
|
||||
let mut args = Vec::new();
|
||||
let mut trailing_comma = false;
|
||||
if !self.at(Punct::RParen) {
|
||||
loop {
|
||||
if cover {
|
||||
self.cover_ok = true;
|
||||
}
|
||||
args.push(self.parse_element()?);
|
||||
// A comma may follow the last argument (ECMAScript 2017, section 12.3).
|
||||
if !self.eat(Punct::Comma)? || self.at(Punct::RParen) {
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
if self.at(Punct::RParen) {
|
||||
trailing_comma = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.expect(Punct::RParen)?;
|
||||
Ok(args)
|
||||
Ok((args, trailing_comma))
|
||||
}
|
||||
|
||||
fn parse_primary(&mut self) -> Result<ExprId> {
|
||||
@@ -1836,9 +1997,20 @@ impl<'s> Parser<'s> {
|
||||
let class = self.parse_class(false)?;
|
||||
return Ok(self.ast.push_expr(Expr::Class(Box::new(class)), self.span_from(start)));
|
||||
}
|
||||
TokenKind::Ident(_) if self.at_async_function() => return self.parse_function_expression(),
|
||||
TokenKind::Ident(name) => {
|
||||
let name = name.clone();
|
||||
self.check_identifier(&self.tok, &name)?;
|
||||
if name == "await" {
|
||||
self.awaits = self.awaits.saturating_add(1);
|
||||
}
|
||||
// With E4X, `async::name` is a qualified name.
|
||||
if self.at_async() && !(self.e4x && self.peek().is_some_and(|t| t.is_punct(Punct::ColonColon))) {
|
||||
let token = self.bump()?;
|
||||
let id = self.ast.push_expr(Expr::Ident(name), token.span);
|
||||
self.async_ident = Some(id);
|
||||
return Ok(id);
|
||||
}
|
||||
Expr::Ident(name)
|
||||
}
|
||||
TokenKind::Number(n) => {
|
||||
@@ -1887,9 +2059,11 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
|
||||
/// `( … )` with [`crate::Options::es2015`]: a parenthesized expression, or the head of an arrow
|
||||
/// function, which may also be `()` or end with `...name`; those two must come before `=>`.
|
||||
/// function, which may also be `()`, end with `...name` or end with a comma; those three must
|
||||
/// come before `=>`.
|
||||
fn parse_paren_or_arrow_head(&mut self) -> Result<ExprId> {
|
||||
let start = self.expect(Punct::LParen)?.span;
|
||||
let awaits = self.awaits;
|
||||
let mut items = Vec::new();
|
||||
let mut head_only = self.at(Punct::RParen);
|
||||
let mark = self.cover_inits.len();
|
||||
@@ -1906,8 +2080,11 @@ impl<'s> Parser<'s> {
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
// A comma may follow the last parameter (ECMA-262 2017 section 14.2), but not the
|
||||
// last item of a parenthesized expression.
|
||||
if self.at(Punct::RParen) {
|
||||
return Err(self.unexpected());
|
||||
head_only = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.expect(Punct::RParen)?;
|
||||
@@ -1924,7 +2101,11 @@ impl<'s> Parser<'s> {
|
||||
self.ast.push_expr(Expr::Sequence(items), span)
|
||||
}
|
||||
};
|
||||
Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start)))
|
||||
let paren = self.ast.push_expr(Expr::Paren(inner), self.span_from(start));
|
||||
if self.at(Punct::Arrow) {
|
||||
self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits, trailing_comma: false });
|
||||
}
|
||||
Ok(paren)
|
||||
}
|
||||
|
||||
/// A template literal from its first piece (the current token): its pieces and substitutions.
|
||||
@@ -1953,14 +2134,25 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
|
||||
fn parse_function_expression(&mut self) -> Result<ExprId> {
|
||||
let start = self.expect_keyword(Keyword::Function)?.span;
|
||||
let generator = self.es2015 && self.eat(Punct::Star)?;
|
||||
// A generator expression's name is read with its own `yield` rule.
|
||||
let is_async = self.at_async();
|
||||
let start = if is_async { self.bump()?.span } else { self.tok.span };
|
||||
self.expect_keyword(Keyword::Function)?;
|
||||
// Async generators (ECMAScript 2018) stay syntax errors: the `*` is not read after `async`.
|
||||
let generator = !is_async && self.es2015 && self.eat(Punct::Star)?;
|
||||
// A function expression's name is read as its own body reads names (ECMA-262 2017
|
||||
// section 14.6): `await` is a name for an ordinary one, and not for an async one, and a
|
||||
// generator expression's name is read with its own `yield` rule.
|
||||
// Nor does the name count for an arrow function's head around it.
|
||||
let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits);
|
||||
self.ctx.in_async = is_async;
|
||||
self.ctx.async_params = false;
|
||||
let outer_generator = std::mem::replace(&mut self.ctx.generator, generator);
|
||||
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) };
|
||||
self.ctx.generator = outer_generator;
|
||||
let name = name?;
|
||||
let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?;
|
||||
self.ctx.in_async = in_async;
|
||||
self.ctx.async_params = async_params;
|
||||
self.awaits = awaits;
|
||||
let id = self.parse_function_rest(FunctionKind::Expression, name?, start, generator, is_async)?;
|
||||
Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start)))
|
||||
}
|
||||
|
||||
@@ -2023,14 +2215,21 @@ impl<'s> Parser<'s> {
|
||||
self.bump()?;
|
||||
}
|
||||
let start = self.tok.span;
|
||||
let generator = self.eat(Punct::Star)?;
|
||||
// `async name(…) {…}` (ECMA-262 2017 section 14.6): an async method, with no line break
|
||||
// after `async`. Async generator methods (ECMAScript 2018) stay syntax errors.
|
||||
let is_async =
|
||||
self.at_async() && self.peek().is_some_and(|t| !t.newline_before && (property_key(&t).is_some() || t.is_punct(Punct::LBracket)));
|
||||
if is_async {
|
||||
self.bump()?;
|
||||
}
|
||||
let generator = !is_async && self.eat(Punct::Star)?;
|
||||
// `get` and `set` start an accessor only when written without escapes and followed by a name.
|
||||
let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) {
|
||||
Some("get") => Some(MethodKind::Get),
|
||||
Some("set") => Some(MethodKind::Set),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|_| !generator && self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket)));
|
||||
.filter(|_| !generator && !is_async && self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket)));
|
||||
if accessor.is_some() {
|
||||
self.bump()?;
|
||||
}
|
||||
@@ -2051,7 +2250,10 @@ impl<'s> Parser<'s> {
|
||||
return Err(self.error_at_offset(start.start, "a class constructor cannot be a generator"));
|
||||
}
|
||||
let ctor = if derived { FunctionKind::DerivedConstructor } else { FunctionKind::ClassConstructor };
|
||||
return Ok(Err(self.parse_function_with(ctor, None, start, true, false)?));
|
||||
if is_async {
|
||||
return Err(self.error_at_offset(start.start, "a class constructor cannot be async"));
|
||||
}
|
||||
return Ok(Err(self.parse_function_with(ctor, None, start, true, false, false)?));
|
||||
}
|
||||
if is_static && named("prototype") {
|
||||
return Err(self.error_at_offset(start.start, "a class cannot have a static method named 'prototype'"));
|
||||
@@ -2061,7 +2263,7 @@ impl<'s> Parser<'s> {
|
||||
MethodKind::Get => FunctionKind::Getter,
|
||||
MethodKind::Set => FunctionKind::Setter,
|
||||
};
|
||||
let function = self.parse_function_with(fkind, None, start, true, generator)?;
|
||||
let function = self.parse_function_with(fkind, None, start, true, generator, is_async)?;
|
||||
Ok(Ok(ClassElement { key, is_static, kind, function }))
|
||||
}
|
||||
|
||||
@@ -2078,8 +2280,19 @@ impl<'s> Parser<'s> {
|
||||
} else {
|
||||
(FunctionKind::ClassConstructor, None, Vec::new())
|
||||
};
|
||||
let function =
|
||||
Function { kind, name: None, params: Vec::new(), defaults: Vec::new(), rest, body, strict: true, generator: false, span, home: true };
|
||||
let function = Function {
|
||||
kind,
|
||||
name: None,
|
||||
params: Vec::new(),
|
||||
defaults: Vec::new(),
|
||||
rest,
|
||||
body,
|
||||
strict: true,
|
||||
generator: false,
|
||||
is_async: false,
|
||||
span,
|
||||
home: true,
|
||||
};
|
||||
self.ast.push_function(function)
|
||||
}
|
||||
|
||||
@@ -2162,7 +2375,7 @@ impl<'s> Parser<'s> {
|
||||
let word = self.bump()?;
|
||||
if property_key(&self.tok).is_some() {
|
||||
let (key, _) = self.parse_property_key()?;
|
||||
let function = self.parse_function_rest(kind, None, start, false)?;
|
||||
let function = self.parse_function_rest(kind, None, start, false, false)?;
|
||||
let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) };
|
||||
return Ok(Property { key, value, span: self.span_from(start) });
|
||||
}
|
||||
|
||||
@@ -317,7 +317,7 @@ impl Parser<'_> {
|
||||
(Name { name: DEFAULT_BINDING.into(), span: start }, keyword)
|
||||
};
|
||||
let local = name.0.name.clone();
|
||||
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
|
||||
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, false)?;
|
||||
let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start));
|
||||
Ok((stmt, fid, local))
|
||||
}
|
||||
|
||||
@@ -149,7 +149,15 @@ impl Parser<'_> {
|
||||
// `*name(…) {…}`: a generator method (ECMA-262 2015 section 14.4).
|
||||
if self.eat(Punct::Star)? {
|
||||
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
|
||||
let function = self.parse_function_with(FunctionKind::Method, None, start, true, true)?;
|
||||
let function = self.parse_function_with(FunctionKind::Method, None, start, true, true, false)?;
|
||||
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
|
||||
}
|
||||
// `async name(…) {…}` (ECMA-262 2017 section 14.6): an async method, with no line break
|
||||
// after `async`. Async generator methods (ECMAScript 2018) stay syntax errors.
|
||||
if self.at_async() && self.peek().is_some_and(|t| !t.newline_before && (property_key(&t).is_some() || t.is_punct(Punct::LBracket))) {
|
||||
self.bump()?;
|
||||
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
|
||||
let function = self.parse_function_with(FunctionKind::Method, None, start, true, false, true)?;
|
||||
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
|
||||
}
|
||||
// `get` and `set` start an accessor only when written without escapes and followed by a
|
||||
@@ -165,7 +173,7 @@ impl Parser<'_> {
|
||||
self.bump()?;
|
||||
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
|
||||
// An accessor is a method, whose home object is the literal's object.
|
||||
let function = self.parse_function_with(kind, None, start, true, false)?;
|
||||
let function = self.parse_function_with(kind, None, start, true, false, false)?;
|
||||
let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) };
|
||||
return Ok(Property { key, value, span: self.span_from(start) });
|
||||
}
|
||||
@@ -178,6 +186,10 @@ impl Parser<'_> {
|
||||
{
|
||||
let name = name.clone();
|
||||
self.check_identifier(&self.tok, &name)?;
|
||||
// A shorthand `await` counts as one in an async arrow function's head, as a name does.
|
||||
if name == "await" {
|
||||
self.awaits = self.awaits.saturating_add(1);
|
||||
}
|
||||
let token = self.bump()?;
|
||||
let target = self.ast.push_expr(Expr::Ident(name.clone()), token.span);
|
||||
let value = if self.at(Punct::Eq) {
|
||||
@@ -199,7 +211,7 @@ impl Parser<'_> {
|
||||
/// the value may still turn out to be a pattern.
|
||||
fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result<Property> {
|
||||
if self.at(Punct::LParen) {
|
||||
let function = self.parse_function_with(FunctionKind::Method, None, start, true, false)?;
|
||||
let function = self.parse_function_with(FunctionKind::Method, None, start, true, false, false)?;
|
||||
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
|
||||
}
|
||||
self.expect(Punct::Colon)?;
|
||||
|
||||
@@ -167,7 +167,7 @@ fn a_promise_resolved_with_itself_rejects_with_a_type_error() {
|
||||
|
||||
#[test]
|
||||
fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() {
|
||||
let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\
|
||||
let src = "var bad = 0, seen = 0; function check(e) { seen++; if (!(e instanceof TypeError)) bad++; }\n\
|
||||
for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }";
|
||||
let mut finished = 0;
|
||||
for spare in (40_000..240_000).step_by(641) {
|
||||
@@ -181,6 +181,7 @@ fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() {
|
||||
}
|
||||
r.set_limits(Limits::default());
|
||||
assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}");
|
||||
assert_eq!(r.run("seen"), Ok(JsValue::Number(200.0)), "{spare}");
|
||||
}
|
||||
assert!(finished > 0);
|
||||
}
|
||||
@@ -193,6 +194,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
|
||||
Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\
|
||||
Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\
|
||||
Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\
|
||||
Promise.all(new String('a\\uD83D\\uDE00')).then(function (v) { log.push('boxed ' + v.length + ' ' + v[1].length); });\n\
|
||||
Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\
|
||||
Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\
|
||||
Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });";
|
||||
@@ -205,6 +207,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
|
||||
"rejected:r fulfilled:4",
|
||||
"race fast",
|
||||
"chars 2",
|
||||
"boxed 2 2",
|
||||
"not a list true",
|
||||
"no length true",
|
||||
"bad length true",
|
||||
|
||||
@@ -269,12 +269,34 @@ impl Realm {
|
||||
pub fn set_es2015(&mut self, es2015: bool) {
|
||||
if self.is_running() || self.interp.waiting {
|
||||
self.interp.next_es2015 = Some(es2015);
|
||||
if !es2015 {
|
||||
self.interp.next_es2017 = Some(false);
|
||||
}
|
||||
} else {
|
||||
self.interp.next_es2015 = None;
|
||||
self.interp.next_es2017 = None;
|
||||
self.interp.set_es2015(es2015);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets [`Options::es2017`] for the next runs, and for the code they evaluate; on, it also
|
||||
/// sets [`Options::es2015`]. Async functions an earlier run made keep running when it is
|
||||
/// turned off. Call [`Realm::add_es2015`] too in a realm made without either option, since
|
||||
/// an async function needs `Promise`. Like [`Realm::set_es2015`], it applies once a run that
|
||||
/// is still going ends.
|
||||
pub fn set_es2017(&mut self, es2017: bool) {
|
||||
if self.is_running() || self.interp.waiting {
|
||||
self.interp.next_es2017 = Some(es2017);
|
||||
if es2017 {
|
||||
self.interp.next_es2015 = Some(true);
|
||||
}
|
||||
} else {
|
||||
self.interp.next_es2015 = None;
|
||||
self.interp.next_es2017 = None;
|
||||
self.interp.set_es2017(es2017);
|
||||
}
|
||||
}
|
||||
|
||||
/// The realm's interrupt flag. Setting it stops a running script, or the next one to start.
|
||||
pub fn interrupt(&self) -> Interrupt {
|
||||
Interrupt(self.interp.interrupt.clone())
|
||||
@@ -462,6 +484,9 @@ impl Realm {
|
||||
if let Some(es2015) = interp.next_es2015.take() {
|
||||
interp.set_es2015(es2015);
|
||||
}
|
||||
if let Some(es2017) = interp.next_es2017.take() {
|
||||
interp.set_es2017(es2017);
|
||||
}
|
||||
match result {
|
||||
Ok(v) => {
|
||||
self.rejections = interp.take_unhandled();
|
||||
|
||||
+169
-21
@@ -31,7 +31,8 @@
|
||||
//! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`,
|
||||
//! arrow functions, templates, default and rest parameters, classes, `super` and `new.target`,
|
||||
//! and from ECMAScript 2020 optional chains and `??`) without and with that option, and
|
||||
//! prints both counts; its failures with the option go to `es2015-failures.txt`. A sixth test runs
|
||||
//! prints both counts; its failures with the option, and the runs without it that panicked, go to
|
||||
//! `es2015-failures.txt`. A sixth test runs
|
||||
//! the module tests under `test/language/module-code`, `import` and `export` as modules, reading
|
||||
//! the fixture files they import from the suite, and as scripts for comparison; its failures as
|
||||
//! modules go to `module-failures.txt`.
|
||||
@@ -56,8 +57,8 @@
|
||||
//! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`:
|
||||
//! those whose feature tags name only `Promise`, `Promise.allSettled` and
|
||||
//! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests
|
||||
//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its
|
||||
//! failures go to `promise-failures.txt`.
|
||||
//! run with the suite's `doneprintHandle.js` and pass when they print the completion line and no
|
||||
//! line that starts with the failure prefix. Its failures go to `promise-failures.txt`.
|
||||
//!
|
||||
//! Another test runs the tests of `Symbol`, `Object.getOwnPropertySymbols` and the iterators of
|
||||
//! arrays and strings (the folders [`SYMBOL_BUILT_INS`] names) in a realm with
|
||||
@@ -473,7 +474,7 @@ fn uses_missing_builtin(lists: &[Vec<Token>], missing: &HashSet<&str>) -> bool {
|
||||
let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens));
|
||||
lists.iter().flatten().any(|t| match &t.kind {
|
||||
TokenKind::Ident(name) => missing.contains(name.as_str()),
|
||||
TokenKind::String(units) => {
|
||||
TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => {
|
||||
let text = String::from_utf16_lossy(units);
|
||||
missing.contains(text.as_str())
|
||||
|| (strings_are_code && text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')).any(|word| missing.contains(word)))
|
||||
@@ -483,12 +484,12 @@ fn uses_missing_builtin(lists: &[Vec<Token>], missing: &HashSet<&str>) -> bool {
|
||||
}
|
||||
|
||||
/// The tokens can run a string as code: they name `eval`, `Function` or a `constructor` property,
|
||||
/// as an identifier or as a string key (`this["eval"]`), called directly or through an alias.
|
||||
/// as an identifier or as a string or template key (`this["eval"]`), called directly or through an alias.
|
||||
/// `Function.prototype` alone does not count.
|
||||
fn runs_strings_as_code(tokens: &[Token]) -> bool {
|
||||
const RUNNERS: [&str; 3] = ["eval", "Function", "constructor"];
|
||||
tokens.iter().enumerate().any(|(i, t)| match &t.kind {
|
||||
TokenKind::String(units) => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())),
|
||||
TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())),
|
||||
TokenKind::Ident(name) if name == "eval" || name == "constructor" => true,
|
||||
TokenKind::Ident(name) if name == "Function" => {
|
||||
let prototype = tokens.get(i + 1).is_some_and(|d| d.is_punct(Punct::Dot))
|
||||
@@ -883,14 +884,26 @@ struct Es2015Counts {
|
||||
failures: String,
|
||||
}
|
||||
|
||||
impl Es2015Counts {
|
||||
/// The failures of the run with the option, then each run without it that panicked, marked
|
||||
/// with `without`.
|
||||
fn report(after: &Es2015Counts, before: &Es2015Counts, without: &str) -> String {
|
||||
let mut report = after.failures.clone();
|
||||
for line in before.failures.lines().filter(|l| l.ends_with(": PANIC")) {
|
||||
report.push_str(&format!("{line} ({without})\n"));
|
||||
}
|
||||
report
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the ES2015 subset: the tests under `test/language/` in [`ES2015_FOLDERS`], under
|
||||
/// `test/built-ins/` in [`ES2015_BUILT_INS`] and those [`es2015_name_test`] picks, whose feature
|
||||
/// tags are all in [`ES2015_FEATURES`], and the tests elsewhere under `test/language/` with feature
|
||||
/// tags that are all in it. Negative parse tests must give a `SyntaxError`; the other tests run in a
|
||||
/// new realm after the harness, as [`run_tests`] runs them, skipping module and asynchronous tests
|
||||
/// and those that need a missing built-in. Each test is read twice, without and with
|
||||
/// [`Options::es2015`], and the counts of both are printed; the failures with it go to
|
||||
/// `es2015-failures.txt`.
|
||||
/// [`Options::es2015`], and the counts of both are printed; the failures with it, and the runs
|
||||
/// without it that panicked, go to `es2015-failures.txt`.
|
||||
fn run_es2015(dir: &Path) {
|
||||
let language = or_fail(inside(dir, "test/language"));
|
||||
assert!(language.is_dir(), "{} is not a test262 checkout", dir.display());
|
||||
@@ -974,7 +987,7 @@ fn run_es2015(dir: &Path) {
|
||||
assert!(selected > 0, "no ES2015 tests under {}", language.display());
|
||||
let [before, after] = counts;
|
||||
let report = dir.join("es2015-failures.txt");
|
||||
if let Err(e) = std::fs::write(&report, &after.failures) {
|
||||
if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "without Options::es2015")) {
|
||||
println!("could not write {}: {e}", report.display());
|
||||
}
|
||||
let line = |c: &Es2015Counts| {
|
||||
@@ -1338,23 +1351,26 @@ fn promise_builtins_run() {
|
||||
|
||||
#[test]
|
||||
fn promise_async_completion_requires_an_exact_print_argument() {
|
||||
assert!(run_promise_one("print('not Test262:AsyncTestComplete');", None, true).is_err());
|
||||
assert!(run_promise_one("print('Test262:AsyncTestComplete suffix');", None, true).is_err());
|
||||
assert!(run_promise_one("print('message', 'Test262:AsyncTestComplete');", None, true).is_ok());
|
||||
assert!(run_promise_one("print('Test262:AsyncTestComplete');", None, true).is_ok());
|
||||
let es2015 = Options { es2015: true, ..Options::default() };
|
||||
assert!(run_promise_one("print('not Test262:AsyncTestComplete');", None, true, &es2015).is_err());
|
||||
assert!(run_promise_one("print('Test262:AsyncTestComplete suffix');", None, true, &es2015).is_err());
|
||||
assert!(run_promise_one("print('message', 'Test262:AsyncTestComplete');", None, true, &es2015).is_ok());
|
||||
assert!(run_promise_one("print('Test262:AsyncTestComplete');", None, true, &es2015).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_async_failure_checks_each_print_argument() {
|
||||
assert!(run_promise_one("print('Test262:AsyncTestComplete', 'Test262:AsyncTestFailure: failed');", None, true).is_err());
|
||||
assert!(run_promise_one("print('not Test262:AsyncTestFailure'); print('Test262:AsyncTestComplete');", None, true).is_ok());
|
||||
let es2015 = Options { es2015: true, ..Options::default() };
|
||||
assert!(run_promise_one("print('Test262:AsyncTestComplete', 'Test262:AsyncTestFailure: failed');", None, true, &es2015).is_err());
|
||||
assert!(run_promise_one("print('not Test262:AsyncTestFailure'); print('Test262:AsyncTestComplete');", None, true, &es2015).is_ok());
|
||||
}
|
||||
|
||||
/// Runs one Promise test with a global `print` that collects every argument. An `async` test
|
||||
/// needs an exact `Test262:AsyncTestComplete` argument and no `Test262:AsyncTestFailure` prefix.
|
||||
fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> {
|
||||
let options = Options { es2015: true, ..Options::default() };
|
||||
let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
|
||||
/// Runs one test that may be asynchronous in a new realm made with `options` and a global `print`
|
||||
/// that collects every argument; an `async` test without a runtime negative needs an exact
|
||||
/// `Test262:AsyncTestComplete` argument and no `Test262:AsyncTestFailure` prefix, and one with a
|
||||
/// runtime negative must throw that error.
|
||||
fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool, options: &Options) -> Result<(), String> {
|
||||
let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
|
||||
let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
let out = printed.clone();
|
||||
realm.define_function("print", move |args| {
|
||||
@@ -1439,7 +1455,8 @@ fn run_promise(dir: &Path) {
|
||||
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
|
||||
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
|
||||
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
|
||||
match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) {
|
||||
let es2015 = Options { es2015: true, ..Options::default() };
|
||||
match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, &es2015)) {
|
||||
Ok(Ok(())) => counts.passed += 1,
|
||||
Ok(Err(why)) => {
|
||||
counts.failed += 1;
|
||||
@@ -1740,6 +1757,125 @@ fn run_tagged_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, options: &
|
||||
counts
|
||||
}
|
||||
|
||||
/// The folders under `test/language/` that hold tests of async functions and `await`.
|
||||
const ASYNC_FOLDERS: &[&str] = &["expressions/async-function", "statements/async-function", "expressions/await", "expressions/async-arrow-function"];
|
||||
|
||||
/// The feature tags an async-function test may carry and still run: [`ES2015_FEATURES`],
|
||||
/// `async-functions` and `Promise`.
|
||||
const ASYNC_FEATURES: &[&str] = &["async-functions", "Promise"];
|
||||
|
||||
#[test]
|
||||
fn async_functions_run() {
|
||||
let Some(dir) = suite_dir() else {
|
||||
println!("test262 async functions: SKIPPED (no suite; run cargo xtask test262)");
|
||||
return;
|
||||
};
|
||||
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_async_functions(&dir)).unwrap();
|
||||
handle.join().unwrap();
|
||||
}
|
||||
|
||||
/// Runs the tests in [`ASYNC_FOLDERS`] whose feature tags are all in [`ES2015_FEATURES`] or
|
||||
/// [`ASYNC_FEATURES`], twice: with [`Options::es2015`] alone and with [`Options::es2017`]. Negative
|
||||
/// parse tests must not parse; the others run as [`run_promise`] runs them, `async` tests
|
||||
/// included, skipping module tests and those that need a missing built-in. Prints the counts of
|
||||
/// both and writes the failures with [`Options::es2017`], and the runs with [`Options::es2015`]
|
||||
/// alone that panicked, to `async-function-failures.txt`.
|
||||
fn run_async_functions(dir: &Path) {
|
||||
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
|
||||
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
|
||||
let done = harness("doneprintHandle.js");
|
||||
let missing = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]);
|
||||
let es2015 = Options { es2015: true, ..Options::default() };
|
||||
let es2017 = Options { es2015: true, es2017: true, ..Options::default() };
|
||||
let editions = [es2015, es2017.clone()];
|
||||
let mut counts = [Es2015Counts::default(), Es2015Counts::default()];
|
||||
let (mut selected, mut skipped, mut other_features) = (0usize, 0usize, 0usize);
|
||||
for folder in ASYNC_FOLDERS {
|
||||
let root = or_fail(inside(dir, &format!("test/language/{folder}")));
|
||||
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
|
||||
for path in or_fail(test_files(&root)) {
|
||||
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
|
||||
let source = or_fail(read_source(&path));
|
||||
let meta = meta(&source);
|
||||
if meta.features.iter().any(|f| !ES2015_FEATURES.contains(&f.as_str()) && !ASYNC_FEATURES.contains(&f.as_str())) {
|
||||
other_features += 1;
|
||||
continue;
|
||||
}
|
||||
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
|
||||
if has("module") || meta.negative_phase.as_deref() == Some("resolution") {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let asynchronous = has("async");
|
||||
let expect_error = meta.negative_phase.as_deref() == Some("parse");
|
||||
let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
|
||||
if asynchronous {
|
||||
includes.push_str(&done);
|
||||
includes.push('\n');
|
||||
}
|
||||
if !expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &es2017) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
selected += 1;
|
||||
for (options, counts) in editions.iter().zip(counts.iter_mut()) {
|
||||
for &strict in modes(&meta) {
|
||||
let mode = if strict { "strict" } else { "sloppy" };
|
||||
let outcome = if expect_error {
|
||||
let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() };
|
||||
if parse(&text, options).is_err() {
|
||||
counts.parse_passed += 1;
|
||||
continue;
|
||||
}
|
||||
counts.parse_failed += 1;
|
||||
"parsed; a SyntaxError was expected".to_string()
|
||||
} else {
|
||||
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
|
||||
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
|
||||
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
|
||||
match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, options)) {
|
||||
Ok(Ok(())) => {
|
||||
counts.run_passed += 1;
|
||||
continue;
|
||||
}
|
||||
Ok(Err(why)) => {
|
||||
counts.run_failed += 1;
|
||||
why
|
||||
}
|
||||
Err(_) => {
|
||||
counts.run_failed += 1;
|
||||
counts.panicked += 1;
|
||||
"PANIC".to_string()
|
||||
}
|
||||
}
|
||||
};
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(selected > 0, "no async-function tests under {}", dir.display());
|
||||
let [before, after] = counts;
|
||||
let report = dir.join("async-function-failures.txt");
|
||||
if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "with Options::es2015 alone")) {
|
||||
println!("could not write {}: {e}", report.display());
|
||||
}
|
||||
let line = |c: &Es2015Counts| {
|
||||
format!(
|
||||
"negative parse runs {} passed, {} failed; other runs {} passed, {} failed ({} panicked)",
|
||||
c.parse_passed, c.parse_failed, c.run_passed, c.run_failed, c.panicked
|
||||
)
|
||||
};
|
||||
println!(
|
||||
"test262 async functions: {selected} tests. With Options::es2015 alone: {}. With Options::es2017: {}. Skipped {skipped} module \
|
||||
or missing-built-in tests and {other_features} tests with other feature tags. Failures: {}",
|
||||
line(&before),
|
||||
line(&after),
|
||||
report.display()
|
||||
);
|
||||
assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display());
|
||||
}
|
||||
|
||||
/// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing.
|
||||
fn skips(sources: &[&str]) -> bool {
|
||||
let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect();
|
||||
@@ -1769,6 +1905,18 @@ fn a_source_that_does_not_tokenize_as_es2015_is_run_and_not_skipped() {
|
||||
assert!(needs_missing_builtin_in(&[unreadable, "var m = new Map();"], &missing, &modern));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_name_in_a_template_that_can_run_as_code_skips() {
|
||||
let missing: HashSet<&str> = ["Map"].into_iter().collect();
|
||||
let modern = Options { es2015: true, ..Options::default() };
|
||||
assert!(needs_missing_builtin_in(&[r#"eval("new Map()");"#], &missing, &modern));
|
||||
assert!(needs_missing_builtin_in(&["eval(`new Map()`);"], &missing, &modern));
|
||||
// A template key names the runner, as a string key does.
|
||||
assert!(needs_missing_builtin_in(&["this[`eval`](`new Map()`);"], &missing, &modern));
|
||||
assert!(needs_missing_builtin_in(&[r#"var F = this[`Function`]; F("return new Map()")();"#], &missing, &modern));
|
||||
assert!(!needs_missing_builtin_in(&["assert(true, `a Map`);"], &missing, &modern));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_name_in_code_skips() {
|
||||
assert!(skips(&["var m = new Map();"]));
|
||||
|
||||
@@ -1991,7 +1991,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (listed last in ui.inspect's `dialogs`, with key null; fields: the print.setup settings, `preset` (setting it loads that print preset; Save Preset… saves them as one), `printer` (a print.printers name, or PDF File, with which Print saves the job as a PDF), `section` and `sheet`; Print keeps the settings with the document and prints, Done (`choice`: done, then ui.dialog.confirm) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
"{} open the Print dialog (listed last in ui.inspect's `dialogs`, with key null; fields: the print.setup settings, `preset` (setting it loads that print preset; Save Preset… saves them as one), `printer` (a print.printers name, or PDF File, with which Print saves the job as a PDF), `section` and `sheet`; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (`choice`: done, then ui.dialog.confirm) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
|
||||
@@ -1098,7 +1098,7 @@ impl<'p> Builder<'p> {
|
||||
a.data,
|
||||
)
|
||||
.ok()?;
|
||||
let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
|
||||
let png = super::state::png(&raw)?;
|
||||
let blob = ImageBlob::new("image/png", png);
|
||||
let k = blob.content_key();
|
||||
self.images.insert(k.clone(), blob);
|
||||
|
||||
@@ -378,19 +378,25 @@ pub(super) fn bounds(nodes: &[Arc<Node>]) -> Option<Rect> {
|
||||
nodes.iter().try_fold(None, |acc, n| n.visual_bounds().map(|b| Some(acc.map_or(b, |a: Rect| a.union(b)))))?
|
||||
}
|
||||
|
||||
/// `img` as a PNG with fast compression, which keeps opening a file with large images quick.
|
||||
pub(super) fn png(img: &craft_image_codecs::Image) -> Option<Vec<u8>> {
|
||||
let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
|
||||
craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok()
|
||||
}
|
||||
|
||||
pub(super) fn rgba_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
|
||||
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?;
|
||||
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
|
||||
png(&img)
|
||||
}
|
||||
|
||||
pub(super) fn rgb_png(rgb: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
|
||||
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?;
|
||||
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
|
||||
png(&img)
|
||||
}
|
||||
|
||||
pub(super) fn gray_png(gray: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
|
||||
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?;
|
||||
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
|
||||
png(&img)
|
||||
}
|
||||
|
||||
pub(super) fn resize_alpha(a: &LumaData, w: u32, h: u32) -> Vec<u8> {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, ImageBlob, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
|
||||
|
||||
@@ -147,6 +147,56 @@ fn a_luminosity_soft_mask_of_an_image_keeps_the_images_colour() {
|
||||
assert_eq!(mask_image_pixels("Luminosity"), [[0, 0, 0, 255], [0, 0, 0, 0]]);
|
||||
}
|
||||
|
||||
/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2,
|
||||
/// FLEVEL 0).
|
||||
fn fastest_png(png: &[u8]) -> bool {
|
||||
let mut at = 8;
|
||||
while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) {
|
||||
if kind == b"IDAT" {
|
||||
return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0);
|
||||
}
|
||||
at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize;
|
||||
}
|
||||
panic!("a PNG with image data: {png:?}");
|
||||
}
|
||||
|
||||
/// Images come in as PNGs written with fast compression, which keeps a file with large images
|
||||
/// quick to open: an RGB image with a soft mask, the soft mask of a CMYK image as its opacity
|
||||
/// mask, a gray image and an image mask painted in a color.
|
||||
#[test]
|
||||
fn imported_images_are_stored_with_fast_compression() {
|
||||
let g = first_extra(1);
|
||||
let image = |space: &str, data: &str| {
|
||||
stream(
|
||||
&format!(
|
||||
"/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /{space} /BitsPerComponent 8 /Filter /ASCIIHexDecode /SMask {} 0 R",
|
||||
g + 4
|
||||
),
|
||||
data,
|
||||
)
|
||||
};
|
||||
let rgb = image("DeviceRGB", "FF000000FF00>");
|
||||
let cmyk = image("DeviceCMYK", "0A141E28 00667F08>");
|
||||
let gray =
|
||||
stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "2080>");
|
||||
let stencil = stream("/Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode", "F0>");
|
||||
let smask =
|
||||
stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "FF40>");
|
||||
let bytes = one_page(
|
||||
"q 40 0 0 40 0 0 cm /Im0 Do Q q 40 0 0 40 50 0 cm /Im1 Do Q q 40 0 0 40 0 50 cm /Im2 Do Q 0 0 1 rg q 40 0 0 40 50 50 cm /Im3 Do Q",
|
||||
&format!("/XObject << /Im0 {g} 0 R /Im1 {} 0 R /Im2 {} 0 R /Im3 {} 0 R >>", g + 1, g + 2, g + 3),
|
||||
&[&rgb, &cmyk, &gray, &stencil, &smask],
|
||||
);
|
||||
let d = open(&bytes);
|
||||
let masks = all(&d).iter().filter(|n| n.extras().mask.is_some()).count();
|
||||
assert_eq!(masks, 1, "the CMYK image's soft mask as an opacity mask");
|
||||
let pngs: Vec<&ImageBlob> = d.images.values().filter(|b| b.mime == "image/png").collect();
|
||||
assert_eq!(pngs.len(), 4, "the RGB image, the CMYK image's mask, the gray image and the image mask: {:?}", d.images.keys());
|
||||
for b in pngs {
|
||||
assert!(fastest_png(&b.bytes), "{:?}", &b.bytes[..b.bytes.len().min(48)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_luminosity_soft_mask_becomes_an_opacity_mask() {
|
||||
let d = open(&masked("/S /Luminosity", "1 1 1 rg 0 0 50 100 re f"));
|
||||
|
||||
@@ -262,7 +262,7 @@ impl VectorcraftApp {
|
||||
}
|
||||
// A filter plug-in run becomes Object › Plug-ins › Apply Last Filter.
|
||||
dialogs::plugin::after_command(self, id, ¶ms, &r, plugins_before);
|
||||
let copied = r.is_ok() && self.publish_copy(id);
|
||||
let copied = r.as_ref().is_ok_and(|v| self.publish_copy(id, v));
|
||||
self.sync_views();
|
||||
self.refresh_replace_font_warning(false);
|
||||
// File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh.
|
||||
@@ -328,10 +328,11 @@ impl VectorcraftApp {
|
||||
r
|
||||
}
|
||||
|
||||
/// After a Copy or Cut `id` that ran: offer what it copied to other apps
|
||||
/// ([`Self::publish_clipboard`]) → whether `id` is one.
|
||||
fn publish_copy(&mut self, id: &str) -> bool {
|
||||
let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut");
|
||||
/// After a Copy or Cut `id` that ran, or a script run to its end (`reply` without `running`)
|
||||
/// that reports `copied`: offer what it copied to other apps ([`Self::publish_clipboard`]) →
|
||||
/// whether it did.
|
||||
fn publish_copy(&mut self, id: &str, reply: &Value) -> bool {
|
||||
let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut") || (id == "script.run" && reply["copied"] == true);
|
||||
if copy {
|
||||
self.publish_clipboard(matches!(id, "edit.cut" | "artboard.cut"));
|
||||
}
|
||||
|
||||
@@ -1498,6 +1498,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val
|
||||
};
|
||||
match (set, answer) {
|
||||
(Some(Ok(_)), Some(answer)) => {
|
||||
if answer == "ui.dialog.confirm"
|
||||
&& let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms)
|
||||
{
|
||||
crate::dialogs::print::prepare_confirm(app, host, id);
|
||||
}
|
||||
craft::automation::dialogs::dialog_method(host, ctx, answer, &json!({ "dialog": params["dialog"] }))
|
||||
}
|
||||
// A set answers with the dialog it set, `{id, parent, key, fields}`, as production did.
|
||||
|
||||
@@ -24,7 +24,7 @@ use craft::print::ui::{
|
||||
};
|
||||
use craft::ui::buttons::ToggleButton;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, Politeness, Props as _, Show as _, ShowContainer as _, announce};
|
||||
use craft::ui::dialog::{DialogId, StackDialog as _};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::layout::empty_cell;
|
||||
@@ -119,6 +119,9 @@ struct Open {
|
||||
papers_pending: bool,
|
||||
/// The ids of the Size choices the dialog was last given.
|
||||
media: Vec<String>,
|
||||
/// The printer discovery still running on a background job. The dialog takes its list once it has arrived, so
|
||||
/// PDF File stays available while the system's printers are looked up.
|
||||
discovery: Option<mpsc::Receiver<Vec<Printer>>>,
|
||||
}
|
||||
|
||||
/// The document (uid, revision) and the settings a cached preview belongs to.
|
||||
@@ -292,13 +295,14 @@ fn start(
|
||||
) -> Result<Value, String> {
|
||||
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window to show the dialog in")?;
|
||||
let (printers, service) = destinations(app);
|
||||
let background = shared_printers(app).is_some();
|
||||
let (printers, service) = if background { (listed(Vec::new(), true), true) } else { destinations(app) };
|
||||
let mut state = State::default();
|
||||
state.settings.destination = Destination::Printer(
|
||||
printers.iter().find(|p| p.default).or(printers.first().filter(|_| service)).map_or_else(|| PDF_FILE.to_string(), |p| p.name.clone()),
|
||||
);
|
||||
state.printers = printers;
|
||||
let header = if service && cfg!(windows) {
|
||||
let mut header = if service && cfg!(windows) {
|
||||
vec![
|
||||
Param::new("directPdf", tl!("Send PDF directly (bypass driver)"), ParamKind::bool(false))
|
||||
.tooltip(tl!("Writes the print-ready PDF to the printer's TCP/IP RAW port, for PCL-only drivers that change the custom page size.")),
|
||||
@@ -306,6 +310,10 @@ fn start(
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
header.push(Param::custom("__discovery", "", |ui, fields, _| {
|
||||
let text = if fields.bool("__discovery") == Some(true) { tl!("Finding printers. PDF File and Done are available.") } else { "" };
|
||||
Text::new(text).show(ui)
|
||||
}));
|
||||
let taken: Vec<String> = taken_names(app);
|
||||
let named = editing.clone();
|
||||
let driver = driver(has_setup(app), &state.settings.destination);
|
||||
@@ -325,13 +333,30 @@ fn start(
|
||||
.json_form(|fields, out| out.extend(nested(form::json_of(&KEYS, fields))))
|
||||
.check_name(move |name: &str| refusal(&taken, &named, name).map(|_| PresetError::NameTaken))
|
||||
.held_ok();
|
||||
let discovery = (background && mode == PrintMode::Print).then(|| discover(app));
|
||||
if discovery.is_some() {
|
||||
hosted.set_settings_valid(false);
|
||||
hosted.set_field("__discovery", true.into());
|
||||
}
|
||||
// The name row is the dialog's own.
|
||||
if mode == PrintMode::PresetEditor {
|
||||
hosted.set_json_field(&ctx, "name", json!(name))?;
|
||||
}
|
||||
let id = dialogs.with(|h| h.open(hosted));
|
||||
app.print_dialog.open =
|
||||
Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver, papers: (printer, papers), papers_pending, media });
|
||||
app.print_dialog.open = Some(Open {
|
||||
id,
|
||||
mode,
|
||||
document,
|
||||
preset,
|
||||
editing,
|
||||
art: None,
|
||||
preview: None,
|
||||
driver,
|
||||
papers: (printer, papers),
|
||||
papers_pending,
|
||||
media,
|
||||
discovery,
|
||||
});
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -394,12 +419,49 @@ fn insert_at(map: &mut Map<String, Value>, path: &[&str], v: Value) {
|
||||
/// and PDF File last; and whether there is a print service.
|
||||
fn destinations(app: &mut VectorcraftApp) -> (Vec<Printer>, bool) {
|
||||
let service = app.services.print.is_some();
|
||||
let mut list: Vec<Printer> = app.services.print.as_mut().map(|s| s.printers()).unwrap_or_default();
|
||||
let list: Vec<Printer> = app.services.print.as_mut().map(|s| s.printers()).unwrap_or_default();
|
||||
(listed(list, service), service)
|
||||
}
|
||||
|
||||
/// The Printer list of the system's printers `list`: the default printer by itself when a print `service` names none,
|
||||
/// and PDF File last.
|
||||
fn listed(mut list: Vec<Printer>, service: bool) -> Vec<Printer> {
|
||||
if service && list.is_empty() {
|
||||
list.push(Printer::new("").label(tl!(DEFAULT_PRINTER)));
|
||||
}
|
||||
list.push(Printer::new(PDF_FILE).label(tl!(PDF_FILE)));
|
||||
(list, service)
|
||||
list
|
||||
}
|
||||
|
||||
/// The print service's background printer discovery, if it has one.
|
||||
fn shared_printers(app: &VectorcraftApp) -> Option<crate::print::SharedPrintersFn> {
|
||||
app.services.print.as_ref().and_then(|s| s.shared_printers())
|
||||
}
|
||||
|
||||
/// The Printer list for the dialog to take ([`HostedPrint::listen`]): found on a background job when the print service
|
||||
/// has a background discovery, otherwise listed here.
|
||||
fn discover(app: &mut VectorcraftApp) -> mpsc::Receiver<Vec<Printer>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
match shared_printers(app) {
|
||||
Some(find) => {
|
||||
let ctx = app.ui_ctx.clone();
|
||||
app.jobs().spawn(
|
||||
"printer-discovery",
|
||||
Box::new(move || {
|
||||
// The dialog may have closed and dropped the receiver; nothing waits for the list then.
|
||||
let _ = tx.send(listed(find(), true));
|
||||
if let Some(ctx) = ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
None => {
|
||||
// The receiver is held by the dialog, so the send cannot fail.
|
||||
let _ = tx.send(destinations(app).0);
|
||||
}
|
||||
}
|
||||
rx
|
||||
}
|
||||
|
||||
/// Whether the print service can open a printer's settings (`print.printerSetup`).
|
||||
@@ -456,9 +518,25 @@ fn on<R>(dialogs: &WindowDialogs, f: impl FnOnce(&mut HostedPrint) -> R) -> Opti
|
||||
dialogs.with(|h| h.get_mut::<HostedPrint>().map(f))
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_confirm(app: &VectorcraftApp, host: &mut craft::ui::dialog::DialogHost, id: DialogId) {
|
||||
if let Some(open) = &app.print_dialog.open
|
||||
&& open.id == id
|
||||
&& let Some(p) = host.get_mut::<HostedPrint>()
|
||||
{
|
||||
discovery_valid(p, open.mode, open.discovery.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
/// Enables Print unless the dialog prints to a printer while the printer list is still being looked up.
|
||||
fn discovery_valid(p: &mut HostedPrint, mode: PrintMode, pending: bool) {
|
||||
let physical = matches!(&p.state().settings.destination, Destination::Printer(name) if name != PDF_FILE);
|
||||
p.set_settings_valid(mode != PrintMode::Print || !(pending || p.state().discovering()) || !physical);
|
||||
}
|
||||
|
||||
/// One pass of the pump over the open dialog; false once it has closed.
|
||||
fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, open: &mut Open) -> bool {
|
||||
let setup = has_setup(app);
|
||||
// Setup… looks the printers up again on some systems, so the row shows it once the discovery has ended.
|
||||
let setup = has_setup(app) && open.discovery.is_none();
|
||||
let Some(mut d) = on(dialogs, |p| {
|
||||
// The printer row shows Setup… for the printer chosen, and none for PDF File.
|
||||
let driver = driver(setup, &p.state().settings.destination);
|
||||
@@ -576,6 +654,12 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
.collect();
|
||||
on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()]));
|
||||
}
|
||||
if d.refresh {
|
||||
if open.discovery.is_none() {
|
||||
open.discovery = Some(discover(app));
|
||||
}
|
||||
announce(ctx, tl!("Finding printers. PDF File and Done are available."), Politeness::Polite);
|
||||
}
|
||||
if open.document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) {
|
||||
let message = tl!("Return to the original drawing to print it");
|
||||
on(dialogs, |p| {
|
||||
@@ -592,12 +676,31 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
open.driver = d.driver;
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if d.refresh {
|
||||
let (list, _) = destinations(app);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
// The receiver is held by the dialog below, so the send cannot fail.
|
||||
let _ = tx.send(list);
|
||||
on(dialogs, |p| p.listen(rx));
|
||||
let discovery_pending = open.discovery.is_some();
|
||||
if let Some(rx) = &open.discovery {
|
||||
let found = match rx.try_recv() {
|
||||
Ok(list) => Some(Some(list)),
|
||||
Err(mpsc::TryRecvError::Disconnected) => Some(None),
|
||||
Err(mpsc::TryRecvError::Empty) => None,
|
||||
};
|
||||
if let Some(list) = found {
|
||||
open.discovery = None;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
// A discovery that stopped without a list leaves the default printer and PDF File.
|
||||
// The receiver is held by the dialog below, so the send cannot fail.
|
||||
let _ = tx.send(list.unwrap_or_else(|| listed(Vec::new(), true)));
|
||||
on(dialogs, |p| {
|
||||
p.listen(rx);
|
||||
p.state_mut().poll(ctx);
|
||||
let selected = match &p.state().settings.destination {
|
||||
Destination::Printer(name) if name.is_empty() => tl!(DEFAULT_PRINTER).to_string(),
|
||||
Destination::Printer(name) => name.clone(),
|
||||
_ => tl!(PDF_FILE).to_string(),
|
||||
};
|
||||
let message = crate::i18n::fmt(tl!("Printers are ready. Selected printer: {printer}."), &[("printer", &selected)]);
|
||||
announce(ctx, message, Politeness::Polite);
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(printer) = d.setup
|
||||
&& let Err(e) = app.run("print.printerSetup", json!({ "printer": printer }))
|
||||
@@ -630,7 +733,10 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
Err(_) => Some(tl!("Can't print these settings: see the Summary")),
|
||||
};
|
||||
on(dialogs, |p| {
|
||||
let pending = open.discovery.is_some() || p.state().discovering();
|
||||
p.set_sheet(sheet);
|
||||
discovery_valid(p, open.mode, pending);
|
||||
p.set_field("__discovery", pending.into());
|
||||
p.set_message(message.map(Into::into));
|
||||
});
|
||||
if changed {
|
||||
@@ -643,7 +749,15 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
p.set_field("__inks", FieldValue::Json(inks));
|
||||
});
|
||||
}
|
||||
if let Some(answer) = d.ok {
|
||||
// Physical printing waits until the dialog has applied the discovered list.
|
||||
if open.mode == PrintMode::Print
|
||||
&& discovery_pending
|
||||
&& d.ok.as_ref().is_some_and(|answer| {
|
||||
matches!(answer.finish, PrintFinish::Print) && matches!(&answer.settings.destination, Destination::Printer(name) if name != PDF_FILE)
|
||||
})
|
||||
{
|
||||
on(dialogs, HostedPrint::release_ok);
|
||||
} else if let Some(answer) = d.ok {
|
||||
let result = accept(app, open, &answer, &d.name);
|
||||
on(dialogs, |p| p.answer_ok(result.map_err(Into::into)));
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ use craft::ui::dialog::{
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::runtime::keys;
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::text::TextField;
|
||||
use egui::Ui;
|
||||
@@ -96,6 +97,8 @@ pub const PRINT_KIND: &str = "scriptPrint";
|
||||
|
||||
/// Why Allow Once and Always Allow are refused to automation.
|
||||
pub(crate) const BY_PERSON: &str = "Only the person at the keyboard can allow a script's file access";
|
||||
/// Why Yes to turning off the external script warning is refused to automation.
|
||||
pub(crate) const WARNING_BY_PERSON: &str = "Only the person at the keyboard can turn off the external script warning";
|
||||
|
||||
/// The note the file dialog shows when the person picked more files than a script is given.
|
||||
const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out";
|
||||
@@ -181,6 +184,8 @@ pub(crate) struct ScriptAnswer {
|
||||
pub(crate) answer: &'static str,
|
||||
/// The text of a prompt.
|
||||
pub(crate) value: String,
|
||||
/// Automation gave the answer: `ui.dialog.confirm`, or a click in a pass automation drove.
|
||||
pub(crate) automated: bool,
|
||||
}
|
||||
|
||||
/// What a script's file dialog answers with.
|
||||
@@ -223,11 +228,15 @@ pub(crate) struct ScriptNotice {
|
||||
no_as_default: bool,
|
||||
value: String,
|
||||
answer: Option<&'static str>,
|
||||
/// The confirm is the app's own question before the external script warning turns off
|
||||
/// ([`vectorcraft_engine::Session::script_dialog_turns_warning_off`]), not a script's.
|
||||
warning_off: bool,
|
||||
}
|
||||
|
||||
impl ScriptNotice {
|
||||
fn new(d: &ScriptDialog) -> Self {
|
||||
fn new(d: &ScriptDialog, warning_off: bool) -> Self {
|
||||
Self {
|
||||
warning_off,
|
||||
kind: d.kind.id().to_string(),
|
||||
message: d.message.clone(),
|
||||
title: d.title.clone(),
|
||||
@@ -273,6 +282,12 @@ impl ScriptNotice {
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog's message: a script's own text as it is, and the question the app asks before a
|
||||
/// script turns off the external script warning in the current language.
|
||||
fn notice_message(message: &str, warning_off: bool) -> String {
|
||||
if warning_off { crate::i18n::msg(message) } else { message.to_string() }
|
||||
}
|
||||
|
||||
impl StackDialog for ScriptNotice {
|
||||
type Result = ScriptAnswer;
|
||||
|
||||
@@ -286,7 +301,7 @@ impl StackDialog for ScriptNotice {
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<ScriptAnswer>> {
|
||||
let (answers, buttons): (Vec<&'static str>, Vec<FooterButton>) = self.choices().into_iter().unzip();
|
||||
let message = shown_text(&self.message, true);
|
||||
let message = shown_text(¬ice_message(&self.message, self.warning_off), true);
|
||||
let mut prompt = Prompt::new(self.heading(), message.clone()).answers(buttons);
|
||||
if self.error_icon {
|
||||
prompt = prompt.tone(Tone::Bad, tl!("The script reports an error."));
|
||||
@@ -307,12 +322,13 @@ impl StackDialog for ScriptNotice {
|
||||
self.value = cut_to(&self.value, MAX_PROMPT_BYTES).to_string();
|
||||
}
|
||||
let answer = *answers.get(picked?)?;
|
||||
Some(DialogResult::Ok(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone() }))
|
||||
let automated = WindowHost::of(ui.ctx()).injected_pass();
|
||||
Some(DialogResult::Ok(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone(), automated }))
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &egui::Context) -> Option<ScriptAnswer> {
|
||||
let answer = self.answer.unwrap_or_else(|| self.default_answer());
|
||||
Some(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone() })
|
||||
Some(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone(), automated: true })
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
@@ -344,6 +360,9 @@ impl StackDialog for ScriptNotice {
|
||||
let Some(answer) = answers_for(&self.kind).split(", ").find(|answer| *answer == wanted) else {
|
||||
return Err(format!("`answer` for this {} dialog must be one of: {}", self.kind, answers_for(&self.kind)));
|
||||
};
|
||||
if answer == "yes" && self.warning_off {
|
||||
return Err(WARNING_BY_PERSON.into());
|
||||
}
|
||||
self.answer = Some(answer);
|
||||
}
|
||||
_ => return Err(FieldRefusal::Unknown.message(field)),
|
||||
@@ -723,7 +742,7 @@ pub(crate) fn open_growth(app: &VectorcraftApp) {
|
||||
|
||||
/// Shows the dialog the running script waits at.
|
||||
pub(crate) fn open_notice(app: &VectorcraftApp, d: &ScriptDialog) {
|
||||
open_over_window(app, ScriptNotice::new(d));
|
||||
open_over_window(app, ScriptNotice::new(d, app.session.script_dialog_turns_warning_off()));
|
||||
}
|
||||
|
||||
/// Shows the file dialog the running script waits at.
|
||||
@@ -878,9 +897,20 @@ pub(crate) fn settle_notice(app: &mut VectorcraftApp, result: DialogResult<Scrip
|
||||
"confirm" => "no",
|
||||
_ => "stop",
|
||||
};
|
||||
ScriptAnswer { kind, answer, value: String::new() }
|
||||
ScriptAnswer { kind, answer, value: String::new(), automated: false }
|
||||
}
|
||||
};
|
||||
// Only the person at the keyboard turns off the external script warning: Yes that automation
|
||||
// gave, or taken in a pass automation drives, is refused, the warning stays on, and the
|
||||
// question opens again.
|
||||
let warning_off = app.session.script_dialog_turns_warning_off();
|
||||
if warning_off && answer.answer == "yes" && (answer.automated || app.automation_is_acting()) {
|
||||
app.status(WARNING_BY_PERSON);
|
||||
if let Some(d) = app.session.script_dialog() {
|
||||
open_notice(app, &d);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Err(e) = give(app, &answer) {
|
||||
app.status(e);
|
||||
if let Some(d) = app.session.script_dialog() {
|
||||
@@ -1146,3 +1176,29 @@ pub(crate) fn settle_print(app: &mut VectorcraftApp, result: DialogResult<PrintA
|
||||
pub(crate) const PRINT_BY_PERSON: &str = "Only the person at the keyboard can print a script's print jobs";
|
||||
/// The status after Cancel.
|
||||
pub(crate) const PRINTS_DROPPED: &str = "The script's print jobs were not sent";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_engine::script::DialogKind;
|
||||
use vectorcraft_engine::script::dom::preferences::WARNING_OFF_QUESTION;
|
||||
|
||||
#[test]
|
||||
fn automation_answers_yes_by_the_confirm_origin_not_its_text() {
|
||||
let d = ScriptDialog {
|
||||
kind: DialogKind::Confirm,
|
||||
message: WARNING_OFF_QUESTION.into(),
|
||||
title: None,
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
// A script's own confirm with the same text takes Yes.
|
||||
let mut script = ScriptNotice::new(&d, false);
|
||||
assert!(script.set_json_field(&ctx, "answer", json!("yes")).is_ok());
|
||||
// The app's question before the warning turns off does not.
|
||||
let mut app = ScriptNotice::new(&d, true);
|
||||
assert_eq!(app.set_json_field(&ctx, "answer", json!("yes")), Err(WARNING_BY_PERSON.to_string()));
|
||||
}
|
||||
}
|
||||
@@ -1117,6 +1117,232 @@ pub(super) fn field_names(out: &egui::FullOutput) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A print service with a background printer discovery, which counts the lists made on the UI thread.
|
||||
struct SlowDiscovery {
|
||||
/// How many times the dialog listed the printers on the UI thread.
|
||||
listed_here: Rc<Cell<usize>>,
|
||||
jobs: Jobs,
|
||||
printers: Vec<Printer>,
|
||||
}
|
||||
|
||||
impl PrintService for SlowDiscovery {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
self.listed_here.set(self.listed_here.get() + 1);
|
||||
MockPrint(Jobs::default()).printers()
|
||||
}
|
||||
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
MockPrint(self.jobs.clone()).print(job)
|
||||
}
|
||||
|
||||
fn shared_printers(&self) -> Option<crate::print::SharedPrintersFn> {
|
||||
let printers = self.printers.clone();
|
||||
Some(std::sync::Arc::new(move || printers.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The message the Print dialog shows while the printer discovery runs.
|
||||
const PENDING_MESSAGE: &str = "Finding printers. PDF File and Done are available.";
|
||||
|
||||
/// Checks the dialog's next frame: whether it shows the discovery message, and whether Print is enabled. Done always
|
||||
/// is.
|
||||
fn discovery_controls(app: &mut VectorcraftApp, pending: bool, enabled: bool) {
|
||||
use egui::accesskit::Role;
|
||||
let ctx = ctx(app);
|
||||
let out = crate::testing::app_frame(app, &ctx, Default::default());
|
||||
let nodes = out.platform_output.accesskit_update.expect("an accessibility tree").nodes;
|
||||
let button = |name| nodes.iter().map(|(_, node)| node).find(|node| node.role() == Role::Button && node.label() == Some(name)).unwrap();
|
||||
assert_eq!(!button("Print").is_disabled(), enabled, "Print availability follows discovery and destination");
|
||||
assert!(!button("Done").is_disabled(), "Done stays available");
|
||||
assert_eq!(nodes.iter().any(|(_, node)| node.label() == Some(PENDING_MESSAGE) || node.value() == Some(PENDING_MESSAGE)), pending);
|
||||
}
|
||||
|
||||
/// An app with a drawing whose print service finds `printers` on a background job that waits until the test runs it,
|
||||
/// as a slow print server would; with the count of lists made on the UI thread, the jobs printed, and the jobs.
|
||||
fn discovery_app(printers: Vec<Printer>) -> (VectorcraftApp, Rc<Cell<usize>>, Jobs, std::sync::Arc<craft::host::ManualJobs>) {
|
||||
let listed_here = Rc::new(Cell::new(0));
|
||||
let printed = Jobs::default();
|
||||
let service = SlowDiscovery { listed_here: listed_here.clone(), jobs: printed.clone(), printers };
|
||||
let services = Services { print: Some(Box::new(service)), ..Default::default() };
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
|
||||
let jobs = std::sync::Arc::new(craft::host::ManualJobs::new());
|
||||
app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs.clone()).build());
|
||||
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
|
||||
(app, listed_here, printed, jobs)
|
||||
}
|
||||
|
||||
/// The dialog opens and works while the printer discovery waits on a background job, and shows the system's printers
|
||||
/// once the job has run.
|
||||
#[test]
|
||||
fn printer_discovery_runs_off_the_ui_thread() {
|
||||
use egui::accesskit::Role;
|
||||
let (mut app, listed_here, printed, jobs) = discovery_app(MockPrint(Jobs::default()).printers());
|
||||
let pending_message = PENDING_MESSAGE;
|
||||
let controls = discovery_controls;
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
app.run("file.new", json!({"width": 180, "height": 100})).unwrap();
|
||||
let ctx = ctx(&app);
|
||||
let out = crate::testing::app_frame(&mut app, &ctx, Default::default());
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
assert!(
|
||||
nodes.iter().any(|(_, node)| node.role() == Role::Button && node.label() == Some("Print") && node.is_disabled()),
|
||||
"physical Print is disabled in the first frame"
|
||||
);
|
||||
assert!(
|
||||
nodes.iter().any(|(_, node)| {
|
||||
node.role() == Role::Status
|
||||
&& node.live() == Some(egui::accesskit::Live::Polite)
|
||||
&& node.label().is_some_and(|text| text.contains(pending_message))
|
||||
}),
|
||||
"printer discovery is announced before Print is pressed"
|
||||
);
|
||||
assert_eq!(listed_here.get(), 0, "the printers are not listed on the UI thread");
|
||||
assert_eq!(jobs.waiting(), 1, "discovery starts even after switching drawings before the first pump");
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, false);
|
||||
assert_eq!(jobs.waiting(), 1, "the discovery waits on a background job");
|
||||
assert_ne!(fields(&app)["printer"], "Proofer", "the list has not arrived");
|
||||
set(&mut app, "printer", json!("PDF File"));
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, true);
|
||||
let out = crate::testing::app_frame(&mut app, &ctx, Default::default());
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
assert!(nodes.iter().any(|(_, node)| node.label() == Some("Print preview image")), "PDF preview stays available during discovery");
|
||||
set(&mut app, "sheet", json!(0));
|
||||
pump(&mut app);
|
||||
assert_eq!(fields(&app)["sheet"], 0, "PDF preview accepts page selection during discovery");
|
||||
set(&mut app, "printer", json!(""));
|
||||
pump(&mut app);
|
||||
set(&mut app, "section", json!("Graphics"));
|
||||
pump(&mut app);
|
||||
assert_eq!(jobs.waiting(), 1, "one discovery at a time");
|
||||
confirm(&mut app);
|
||||
assert!(is_open(&app), "physical printing waits for discovery");
|
||||
assert!(printed.borrow().is_empty());
|
||||
let (id, _) = top(&app).unwrap();
|
||||
app.dialogs().unwrap().with(|host| {
|
||||
host.get_mut::<craft::print::ui::HostedPrint>().unwrap().set_settings_valid(true);
|
||||
let _ = host.confirm_by_id(&ctx, id);
|
||||
assert_eq!(host.held_state(id), Some(craft::ui::dialog::HeldOk::Waiting));
|
||||
});
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
// The frame's pump takes the list and announces it.
|
||||
let out = crate::testing::app_frame(&mut app, &ctx, Default::default());
|
||||
assert_eq!(app.dialogs().unwrap().with(|host| host.held_state(id)), None, "the pump discards the held physical answer");
|
||||
assert!(printed.borrow().is_empty(), "the captured placeholder must not submit to the default printer");
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
assert!(
|
||||
nodes.iter().any(|(_, node)| {
|
||||
node.role() == Role::Status
|
||||
&& node.live() == Some(egui::accesskit::Live::Polite)
|
||||
&& node.label().is_some_and(|text| text.contains("Printers are ready. Selected printer: Proofer."))
|
||||
}),
|
||||
"the applied printer list and selected queue are announced"
|
||||
);
|
||||
pump(&mut app);
|
||||
assert!(is_open(&app), "the held Print answer waits for the dialog to apply the list");
|
||||
assert!(printed.borrow().is_empty(), "the captured placeholder must not submit to the default printer");
|
||||
assert_eq!(fields(&app)["printer"], "Proofer", "the system's default printer, once the list arrives");
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
controls(&mut app, false, true);
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(printed.borrow().len(), 1);
|
||||
assert_eq!(printed.borrow()[0].0.as_deref(), Some("Proofer"));
|
||||
|
||||
let picker = crate::tests_picks::scripted(&mut app);
|
||||
let written: Written = Rc::default();
|
||||
let w = written.clone();
|
||||
app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {
|
||||
w.borrow_mut().push((path.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
}));
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
call(&mut app, "ui.dialog.set", json!({"dialog": "top", "field": "printer", "value": "PDF File", "action": "confirm"}));
|
||||
picker.answer_saved("/tmp/discovery-combined.pdf", None);
|
||||
crate::tests_picks::poll(&mut app, &ctx);
|
||||
assert_eq!(written.borrow().len(), 1, "PDF selection and confirmation work in one call before a frame");
|
||||
assert_eq!(printed.borrow().len(), 1, "PDF confirmation does not submit a physical job");
|
||||
assert_eq!(jobs.waiting(), 1, "PDF confirmation does not wait for discovery");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
}
|
||||
|
||||
/// While the printer discovery runs, Done keeps the settings and PDF File saves, and a held Print to a printer waits.
|
||||
#[test]
|
||||
fn done_and_pdf_file_work_while_printers_are_found() {
|
||||
let (mut app, listed_here, printed, jobs) = discovery_app(MockPrint(Jobs::default()).printers());
|
||||
let controls = discovery_controls;
|
||||
let ctx = ctx(&app);
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
assert_eq!(jobs.waiting(), 1);
|
||||
let (id, _) = top(&app).unwrap();
|
||||
let _ = app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id));
|
||||
set(&mut app, "printer", json!("PDF File"));
|
||||
super::print::pump(&mut app, &ctx);
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, true);
|
||||
assert_eq!(printed.borrow().len(), 0, "the held physical destination is checked even after selecting PDF File");
|
||||
set(&mut app, "printer", json!(""));
|
||||
set(&mut app, "copies", json!(2));
|
||||
set(&mut app, "choice", json!("done"));
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app), "Done can save settings while discovery is pending");
|
||||
assert_eq!(app.session.active().unwrap().doc.print_setup.as_ref().unwrap()["copies"], 2);
|
||||
assert_eq!(printed.borrow().len(), 0, "Done does not submit a print job");
|
||||
assert_eq!(jobs.waiting(), 1, "Done did not wait for discovery");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
|
||||
let picker = crate::tests_picks::scripted(&mut app);
|
||||
let written: Written = Rc::default();
|
||||
let w = written.clone();
|
||||
app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {
|
||||
w.borrow_mut().push((path.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
}));
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
set(&mut app, "printer", json!("PDF File"));
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, true);
|
||||
confirm(&mut app);
|
||||
picker.answer_saved("/tmp/discovery.pdf", None);
|
||||
crate::tests_picks::poll(&mut app, &ctx);
|
||||
assert_eq!(written.borrow().len(), 1, "PDF File saves while discovery is pending");
|
||||
assert_eq!(pages(&written.borrow()[0].1), 2, "PDF File keeps the copies saved by Done");
|
||||
assert_eq!(printed.borrow().len(), 0);
|
||||
assert_eq!(jobs.waiting(), 1, "PDF File does not wait for discovery");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
}
|
||||
|
||||
/// A discovery that finds no printers leaves Default Printer chosen, and Print goes to it once the list is applied.
|
||||
#[test]
|
||||
fn an_empty_discovery_keeps_the_default_printer() {
|
||||
let (mut app, listed_here, printed, jobs) = discovery_app(vec![]);
|
||||
let controls = discovery_controls;
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, false);
|
||||
confirm(&mut app);
|
||||
assert!(is_open(&app));
|
||||
assert_eq!(fields(&app)["printer"], "");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
pump(&mut app);
|
||||
pump(&mut app);
|
||||
controls(&mut app, false, true);
|
||||
assert_eq!(fields(&app)["printer"], "", "an empty result keeps Default Printer selected");
|
||||
let (id, _) = top(&app).unwrap();
|
||||
assert_eq!(app.dialogs().unwrap().with(|host| host.held_state(id)), None, "a blocked Print leaves no stale refusal");
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(printed.borrow().len(), 1);
|
||||
assert_eq!(printed.borrow()[0].0, None);
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
}
|
||||
|
||||
/// Every number and length field of the dialog's sections has a name that tells it from the others in its row.
|
||||
#[test]
|
||||
fn every_number_and_length_field_is_named() {
|
||||
|
||||
@@ -1319,6 +1319,7 @@ font-technology Variable Променливи
|
||||
@msg a drag or an undo group is open; finish it before running a script има отворено влачене или група за отмяна; завършете го, преди да изпълните скрипт
|
||||
@msg the script left a document that cannot be kept скриптът остави документ, който не може да се запази
|
||||
@msg the script is no longer in the Scripts folder скриптът вече не е в папката Scripts
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Скриптът иска да изключи предупреждението, което се показва преди изпълнението на скрипт, избран с Файл › Скриптове › Друг скрипт… След това избраните по-късно скриптове ще се изпълняват без него. Да се изключи ли предупреждението?
|
||||
@msg the script's run is no longer available изпълнението на скрипта вече не е налично
|
||||
@msg a failed command changed undo steps that could not be put back, so the script was stopped неуспешна команда промени стъпки за отмяна, които не можаха да се възстановят, затова скриптът беше спрян
|
||||
@msg a recovery copy could not be written, so the script was not run не можа да се запише копие за възстановяване, затова скриптът не беше изпълнен
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6476,6 +6476,7 @@ digits Malayalam Malaiàlam
|
||||
@msg a drag or an undo group is open; finish it before running a script hi ha un arrossegament o un grup de desfer obert; acabeu-lo abans d'executar un script
|
||||
@msg the script left a document that cannot be kept l'script ha deixat un document que no es pot conservar
|
||||
@msg the script is no longer in the Scripts folder l'script ja no és a la carpeta Scripts
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? L'script demana desactivar l'avís que es mostra abans que s'executi un script triat amb Fitxer › Scripts › Un altre script… Els scripts triats després s'executarien sense l'avís. Voleu desactivar l'avís?
|
||||
Some scripts were not listed Alguns scripts no s'han llistat
|
||||
The Scripts folder cannot be read No es pot llegir la carpeta Scripts
|
||||
Loading scripts… S’estan carregant els scripts…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5283,6 +5283,7 @@ imageTrace Outline Obrys
|
||||
@msg a drag or an undo group is open; finish it before running a script je otevřené tažení nebo skupina kroků zpět; před spuštěním skriptu ji dokončete
|
||||
@msg the script left a document that cannot be kept skript zanechal dokument, který nelze zachovat
|
||||
@msg the script is no longer in the Scripts folder skript už není ve složce Scripts
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Skript žádá o vypnutí upozornění, které se zobrazí před spuštěním skriptu vybraného příkazem Soubor › Skripty › Jiný skript… Později vybrané skripty by se pak spouštěly bez něj. Vypnout upozornění?
|
||||
Some scripts were not listed Některé skripty nebyly uvedeny
|
||||
The Scripts folder cannot be read Složku Scripts nelze přečíst
|
||||
Loading scripts… Načítání skriptů…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -64,6 +64,7 @@
|
||||
@msg a drag or an undo group is open; finish it before running a script en trækning eller en fortrydelsesgruppe er åben; afslut den, før du kører et script
|
||||
@msg the script left a document that cannot be kept scriptet efterlod et dokument, der ikke kan beholdes
|
||||
@msg the script is no longer in the Scripts folder scriptet ligger ikke længere i mappen Scripter
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Scriptet beder om at slå advarslen fra, som vises, før et script, der er valgt med Filer › Scripter › Andet script…, køres. Scripter, der vælges senere, ville så køre uden den. Vil du slå advarslen fra?
|
||||
@msg the script's run is no longer available scriptets kørsel er ikke længere tilgængelig
|
||||
@msg a failed command changed undo steps that could not be put back, so the script was stopped en mislykket kommando ændrede fortrydelsestrin, der ikke kunne genskabes, så scriptet blev stoppet
|
||||
@msg a recovery copy could not be written, so the script was not run en gendannelseskopi kunne ikke skrives, så scriptet blev ikke kørt
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4869,6 +4869,7 @@ theme Appearance Erscheinungsbild
|
||||
@msg a drag or an undo group is open; finish it before running a script ein Ziehvorgang oder eine Rückgängig-Gruppe ist offen; schließen Sie sie ab, bevor Sie ein Skript ausführen
|
||||
@msg the script left a document that cannot be kept das Skript hat ein Dokument hinterlassen, das nicht behalten werden kann
|
||||
@msg the script is no longer in the Scripts folder das Skript befindet sich nicht mehr im Ordner „Scripts“
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Das Skript möchte die Warnung ausschalten, die angezeigt wird, bevor ein mit „Datei › Skripte › Anderes Skript…“ gewähltes Skript ausgeführt wird. Später gewählte Skripte würden dann ohne sie ausgeführt. Warnung ausschalten?
|
||||
Some scripts were not listed Einige Skripte wurden nicht aufgeführt
|
||||
The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden
|
||||
Loading scripts… Skripte werden geladen…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2666,6 +2666,7 @@ axis Both Και τα δύο
|
||||
@msg a drag or an undo group is open; finish it before running a script είναι ανοιχτή μια μεταφορά ή ομάδα αναίρεσης· ολοκληρώστε την πριν εκτελέσετε σενάριο
|
||||
@msg the script left a document that cannot be kept το σενάριο άφησε ένα έγγραφο που δεν μπορεί να διατηρηθεί
|
||||
@msg the script is no longer in the Scripts folder το σενάριο δεν βρίσκεται πλέον στον φάκελο Scripts
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Το σενάριο ζητά να απενεργοποιηθεί η προειδοποίηση που εμφανίζεται πριν εκτελεστεί ένα σενάριο που επιλέχθηκε με Αρχείο › Δέσμες ενεργειών › Άλλο σενάριο… Τα σενάρια που θα επιλεγούν αργότερα θα εκτελούνται τότε χωρίς αυτήν. Να απενεργοποιηθεί η προειδοποίηση;
|
||||
Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα
|
||||
The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts
|
||||
Loading scripts… Φόρτωση σεναρίων…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4945,6 +4945,7 @@ axis Both Ambos
|
||||
@msg a drag or an undo group is open; finish it before running a script hay un arrastre o un grupo de deshacer abierto; termínelo antes de ejecutar un script
|
||||
@msg the script left a document that cannot be kept el script dejó un documento que no se puede conservar
|
||||
@msg the script is no longer in the Scripts folder el script ya no está en la carpeta Scripts
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? El script pide desactivar la advertencia que se muestra antes de que se ejecute un script elegido con Archivo › Scripts › Otro script… Los scripts elegidos después se ejecutarían sin ella. ¿Desactivar la advertencia?
|
||||
Some scripts were not listed Algunos scripts no se han incluido en la lista
|
||||
The Scripts folder cannot be read No se puede leer la carpeta Scripts
|
||||
Loading scripts… Cargando scripts…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5188,6 +5188,7 @@ imageTrace Outline Ääriviiva
|
||||
@msg a drag or an undo group is open; finish it before running a script vetäminen tai kumousryhmä on kesken; viimeistele se ennen komentosarjan suorittamista
|
||||
@msg the script left a document that cannot be kept komentosarja jätti asiakirjan, jota ei voi säilyttää
|
||||
@msg the script is no longer in the Scripts folder komentosarja ei ole enää Scripts-kansiossa
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Komentosarja pyytää poistamaan käytöstä varoituksen, joka näytetään ennen kuin komennolla Tiedosto › Komentosarjat › Muu komentosarja… valittu komentosarja suoritetaan. Myöhemmin valitut komentosarjat suoritettaisiin silloin ilman sitä. Poistetaanko varoitus käytöstä?
|
||||
Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu
|
||||
The Scripts folder cannot be read Scripts-kansiota ei voi lukea
|
||||
Loading scripts… Ladataan komentosarjoja…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4927,6 +4927,7 @@ axis Both Les deux
|
||||
@msg a drag or an undo group is open; finish it before running a script un glissement ou un groupe d’annulation est ouvert ; terminez-le avant d’exécuter un script
|
||||
@msg the script left a document that cannot be kept le script a laissé un document qui ne peut pas être conservé
|
||||
@msg the script is no longer in the Scripts folder le script ne se trouve plus dans le dossier Scripts
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Le script demande à désactiver l’avertissement affiché avant l’exécution d’un script choisi avec Fichier › Scripts › Autre script… Les scripts choisis ensuite s’exécuteraient alors sans lui. Désactiver l’avertissement ?
|
||||
Some scripts were not listed Certains scripts ne sont pas répertoriés
|
||||
The Scripts folder cannot be read Impossible de lire le dossier Scripts
|
||||
Loading scripts… Chargement des scripts…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7684,6 +7684,7 @@ arrowhead Feather पंख
|
||||
@msg a drag or an undo group is open; finish it before running a script कोई ड्रैग या पूर्ववत समूह खुला है; स्क्रिप्ट चलाने से पहले उसे पूरा करें
|
||||
@msg the script left a document that cannot be kept स्क्रिप्ट ने ऐसा दस्तावेज़ छोड़ा है जिसे रखा नहीं जा सकता
|
||||
@msg the script is no longer in the Scripts folder स्क्रिप्ट अब Scripts फ़ोल्डर में नहीं है
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? स्क्रिप्ट उस चेतावनी को बंद करना चाहती है जो फ़ाइल › स्क्रिप्ट्स › अन्य स्क्रिप्ट… से चुनी गई स्क्रिप्ट चलने से पहले दिखाई जाती है। इसके बाद चुनी गई स्क्रिप्ट्स उसके बिना चलेंगी। चेतावनी बंद करें?
|
||||
Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं
|
||||
The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता
|
||||
Loading scripts… स्क्रिप्ट लोड हो रही हैं…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5804,6 +5804,7 @@ imageTrace Outline Körvonal
|
||||
@msg a drag or an undo group is open; finish it before running a script húzás vagy visszavonási csoport van folyamatban; fejezze be a parancsfájl futtatása előtt
|
||||
@msg the script left a document that cannot be kept a parancsfájl olyan dokumentumot hagyott hátra, amely nem tartható meg
|
||||
@msg the script is no longer in the Scripts folder a parancsfájl már nincs a Scripts mappában
|
||||
@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? A parancsfájl ki szeretné kapcsolni azt a figyelmeztetést, amely a Fájl › Szkriptek › Másik szkript… paranccsal kiválasztott parancsfájl futása előtt jelenik meg. A később kiválasztott parancsfájlok ezután nélküle futnának. Kikapcsolja a figyelmeztetést?
|
||||
Some scripts were not listed Néhány szkript nem szerepel a listában
|
||||
The Scripts folder cannot be read A Scripts mappa nem olvasható
|
||||
Loading scripts… Szkriptek betöltése…
|
||||
|
||||
|
Can't render this file because it is too large.
|
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user