diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 7c96cc6104..77b9a4c747 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -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 } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6a331c6b77..cb8f077dae 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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; diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a39260ee91..c83f43fe56 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -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] diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index f462e18300..f5826634d7 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -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) -> Self { + let mut ids: Vec = 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 { + 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 { + 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![]); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 55bae794d3..586deb604c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -970,6 +970,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; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 21618367b6..0601124298 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -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, }; diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index a4e2892f39..f5b3d9fa38 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -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| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); let stroke_only = |m: &Arc| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None; let fill_only = |m: &Arc| 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 { fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box)> { 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 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 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 Result Result Result { 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(); diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 0edfc53c54..649e8944f8 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -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; diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 48a8c828ab..f44b390a70 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -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 { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index d1d60e55a9..fdba4260b4 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -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); } diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index cec025b69a..ed0034b99e 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -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() { diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 142cb8a654..afc1a85f3d 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -415,6 +415,10 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { Some(f) } +pub(crate) fn located_path(link: &LinkInfo, base: LinkBase) -> Option { + 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 diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 271012208f..b70e834594 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -99,11 +99,13 @@ use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; mod colors; mod defaults; +mod images; mod paths; mod print; mod save_open; mod tags; mod text; +mod tracing; mod variables; #[cfg(test)] @@ -126,6 +128,10 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec, 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>, } @@ -441,7 +452,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" => { @@ -581,16 +592,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 { - 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 }) @@ -601,6 +621,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", @@ -624,6 +645,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)), }, @@ -647,7 +673,10 @@ fn page_items(h: &Host, st: &DocState) -> std::result::Result>, 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); } } } @@ -684,9 +713,11 @@ fn top_items(d: &Document) -> Vec { 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. @@ -2305,6 +2336,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})) } @@ -2500,24 +2553,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 { + 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 { @@ -2686,6 +2741,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) @@ -2739,14 +2798,20 @@ struct Destination { fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { 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())); } @@ -2786,17 +2851,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) -> 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::>()).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, @@ -2812,7 +2924,14 @@ 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 }; + // 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) { @@ -2907,22 +3026,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) } @@ -3027,8 +3174,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { text::install_enums(realm)?; - paths::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)?; } @@ -3150,6 +3296,7 @@ fn classes(link: &Link) -> Vec { 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( @@ -3248,7 +3395,8 @@ fn classes(link: &Link) -> Vec { ); 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)); @@ -3259,6 +3407,9 @@ fn classes(link: &Link) -> Vec { 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( diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs new file mode 100644 index 0000000000..29adc7ad6a --- /dev/null +++ b/crates/engine/src/script/dom/images.rs @@ -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 +//! , +//! , +//! and +//! 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 +/// 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, Rc>, Rc>); + +/// 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>, + lists: RefCell>, +} + +/// 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, +} + +pub(super) fn bound_ref(h: &Host, st: &DocState, id: NodeId) -> Option { + 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 { + 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 { + 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>, 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_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 = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + let locks = st.doc.locked_artboards(); + let on_locked: Vec = 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::>().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::>().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::>()})))?; + } + 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 { + 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 { + 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 { + 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 { + 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), + ] +} diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 42754b2cf9..4c61292f71 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -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) -> 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) -> 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(h: &Host, f: impl FnOnce() -> Result) -> Result { h.disk.borrow_mut().exact = true; let r = f(); h.disk.borrow_mut().exact = false; diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs new file mode 100644 index 0000000000..a37a062849 --- /dev/null +++ b/crates/engine/src/script/dom/tracing.rs @@ -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 , +//! and +//! 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 +/// 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>, + /// `next` the other way round: for each replacing object, the object it replaced. + prev: RefCell>, + sources: RefCell>, + descendants: RefCell>>, + retraces: Cell, +} + +/// `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 { + 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(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) -> Result) -> Result { + 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 { + 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> = 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) -> 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> = 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 { + 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, 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 { + 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| { + 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 { + 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), + ] +} diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 058d37f35b..aaf1070d93 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -238,9 +238,10 @@ pub(crate) struct Files { entry_key: Option, } -/// 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 `;`. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index f5b5ee6eaf..fb46b7e2db 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2299,13 +2299,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(); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5250980f5f..5726348db1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -185,7 +185,9 @@ mod script_dialogs; mod script_dollar; mod script_dom; mod script_dom_defaults; +mod script_dom_images; mod script_dom_paths; +mod script_dom_tracing; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 68883942c2..eafc72b73c 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -134,6 +134,46 @@ 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 { 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 page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); @@ -1452,7 +1492,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])); @@ -1462,11 +1502,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] diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs new file mode 100644 index 0000000000..4103ab0bff --- /dev/null +++ b/crates/engine/src/tests/script_dom_images.rs @@ -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 { + 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 { + 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 { + 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)> { + 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 = 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 = 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); +} diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs new file mode 100644 index 0000000000..24223785dd --- /dev/null +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -0,0 +1,1304 @@ +//! Tracing in the script object model: `trace()` on placed and raster items, the `PluginItem`, its +//! `TracingObject` and its `TracingOptions`, and the checks on what a script gives them. + +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, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-dom-tracing-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A 60 × 60 PNG of a black disc on white. +fn disc_png() -> Vec { + vectorcraft_trace::Raster::from_fn(60, 60, |x, y| { + let (dx, dy) = (f64::from(x) + 0.5 - 30.0, f64::from(y) + 0.5 - 30.0); + if dx * dx + dy * dy <= 400.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] } + }) + .encode_png() +} + +/// A session with one 400 × 300 pt document holding the disc image, linked (`link`) or embedded. +fn session(base: &Path, link: bool) -> (Session, NodeId) { + let png = base.join("main/disc.png"); + std::fs::write(&png, disc_png()).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": link})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + (s, id) +} + +/// Runs `text` as `main/main.jsx` in `base`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + 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 { + let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The Image Trace objects of the active document. +fn traces(s: &Session) -> Vec { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if crate::cmd::is_trace_group(n) { + out.push(n.id); + } + }); + out +} + +/// The `trace` settings of the Image Trace object `id`. +fn trace_of(s: &Session, id: NodeId) -> Value { + s.active().unwrap().doc.node(id).and_then(|n| n.extras().trace.as_deref().cloned()).unwrap_or(Value::Null) +} + +/// Every top-level object of the active document's first layer. +fn top(s: &Session) -> Vec { + let d = &s.active().unwrap().doc; + d.children(Some(d.layers[0].id)).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default() +} + +/// Traces with the Default preset as a script does, which the script's counts should match: its +/// `paths` and `anchors`, and the different paints of the result. +fn command_counts(base: &Path, link: bool) -> (u64, u64, u64) { + let (mut s, id) = session(base, link); + let r = s.execute("imageTrace.make", &json!({"id": id.0})).unwrap(); + (r["paths"].as_u64().unwrap(), r["anchors"].as_u64().unwrap(), r["colors"].as_u64().unwrap()) +} + +#[test] +fn raster_trace_returns_plugin_with_counts() { + let base = folder("raster"); + let (mut s, image) = session(&base, false); + let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].clone(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, r = d.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing;\ + vc.log(p.typename); vc.log(p.isTracing); vc.log(t.typename); vc.log(t.sourceArt.name); vc.log(r.typename);\ + vc.log(t.pathCount); vc.log(t.anchorCount); vc.log(t.usedColorCount); vc.log(t.imageResolution);\ + vc.log(p.tracing.pathCount === t.pathCount); vc.log(t.parent.isTracing); vc.log(t.tracingOptions.typename);\ + vc.log(t.tracingOptions.parent.typename); vc.log(d.pageItems[0].typename); vc.log(t.tracingOptions.preset);", + ); + assert_eq!(out[..5], [json!("PluginItem"), json!(true), json!("TracingObject"), json!("src"), json!("RasterItem")]); + let (paths, anchors, colors) = command_counts(&base, false); + assert!(paths > 0 && anchors > 0, "{paths} {anchors}"); + assert_eq!(out[5], json!(paths)); + assert_eq!(out[6], json!(anchors)); + let used = out[7].as_u64().unwrap(); + assert!(used >= 1 && used <= colors, "{used} of {colors}"); + assert_eq!(out[8].as_f64(), ppi.as_f64()); + assert_eq!(out[9..], [json!(true), json!(true), json!("TracingOptions"), json!("TracingObject"), json!("PluginItem"), json!("Default")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_eq!(top(&s), groups); + assert_eq!(undo_steps(&s), 2, "the place and the run"); + let _ = std::fs::remove_dir_all(base); +} + +/// A group moved into a tracing above its paths counts even when its name and contents look like +/// seam fills: only the tracing's lowest item can be its seam fills. +#[test] +fn added_group_named_as_seam_fills_is_counted() { + let base = folder("seam-name"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(), t = p.tracing, n = t.pathCount, a = t.anchorCount;\ + var r = d.pathItems.rectangle(0, 0, 10, 10); r.filled = true; r.stroked = false; d.selection = [r]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Seam Fills'; vc.log(g.typename); g.move(p, ElementPlacement.PLACEATBEGINNING); vc.log(p.tracing.pathCount - n); vc.log(p.tracing.anchorCount - a);\ + var q = d.pathItems.rectangle(0, 0, 10, 10); q.move(p, ElementPlacement.PLACEATEND); vc.log(p.tracing.pathCount - n); vc.log(p.tracing.anchorCount - a);", + ); + assert_eq!(out, [json!("GroupItem"), json!(1), json!(4), json!(2), json!(8)]); + let d = &s.active().unwrap().doc; + let kids = d.children(Some(traces(&s)[0])).unwrap(); + assert!( + kids.iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. }) && crate::cmd::is_seam_fills(n)), + "the trace keeps its own seam fills, below the path placed at the end" + ); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_image_resolution_is_one_number_or_none() { + let base = folder("resolution"); + let (mut s, image) = session(&base, false); + let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].as_f64().unwrap(); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.width = r.width * 2; r.height = r.height * 2;\ + var t = r.trace().tracing; vc.log(t.imageResolution); t.releaseTracing(); r.width = r.width * 2;\ + var m = ''; try { r.trace().tracing.imageResolution; } catch (e) { m = e.message; } vc.log(m);", + ); + assert!((out[0].as_f64().unwrap() - ppi / 2.0).abs() < 1e-9, "{out:?}"); + assert_eq!(out[1], json!("the source image has no single resolution")); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_trace_returns_plugin_with_source_art() { + let base = folder("placed"); + let (mut s, image) = session(&base, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, pl = d.placedItems[0]; pl.name = 'src'; var p = pl.trace();\ + vc.log(p.typename); vc.log(p.tracing.sourceArt.name); vc.log(pl.typename); vc.log(pl.file.name);\ + var m = ''; try { pl.trace(); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!("PluginItem"), json!("src"), json!("PlacedItem"), json!("disc.png"), json!("The image is the source art of a tracing")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(image), Some(groups[0]), "the image is the tracing's source"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_checks_the_image_first() { + let base = folder("unbound"); + let (mut s, image) = session(&base, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\ + try { n.trace(); } catch (e) { m.push(e.message); } p.embed(); try { p.trace(); } catch (e) { m.push(e.message); }\ + try { PlacedItem.prototype.trace.call(d.rasterItems[0]); } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out, [json!(["PlacedItem.file is required", "Stale page item", "this is not a PlacedItem"])]); + assert!(traces(&s).is_empty()); + assert!(s.active().unwrap().doc.node(image).is_some()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_missing_link_refuses_preview() { + let base = folder("missing"); + let (mut s, image) = session(&base, true); + std::fs::remove_file(base.join("main/disc.png")).unwrap(); + let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.placedItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);"); + assert_eq!(out, [json!("Linked image is missing")]); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + assert_eq!(undo_steps(&s), 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_release_restores_source_kind() { + let base = folder("release"); + let (mut s, image) = session(&base, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.name = 'src';\ + var p = r.trace(), t = p.tracing, o = t.tracingOptions, back = t.releaseTracing();\ + vc.log(back.name); vc.log(back.typename); vc.log(r.hidden);\ + var m = []; try { p.name; } catch (e) { m.push(e.message); } try { t.pathCount; } catch (e) { m.push(e.message); }\ + try { o.threshold; } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out[..3], [json!("src"), json!("RasterItem"), json!(false)]); + assert_eq!(out[3], json!(["Stale page item", "Stale page item", "Stale page item"])); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_expand_returns_group_and_stales_plugin() { + let base = folder("expand"); + let (mut s, image) = session(&base, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0], p = r.trace(), t = p.tracing, m = [];\ + try { t.expandTracing(true); } catch (e) { m.push(e.message); }\ + try { t.expandTracing('yes'); } catch (e) { m.push(e.name); }\ + vc.log(m); vc.log(p.isTracing);\ + var g = t.expandTracing(); vc.log(g.typename); vc.log(p === g); m = [];\ + try { p.isTracing; } catch (e) { m.push(e.message); } try { t.anchorCount; } catch (e) { m.push(e.message); }\ + try { r.name; } catch (e) { m.push(e.message); } vc.log(m); vc.log(app.activeDocument.pageItems[0] === g);", + ); + assert_eq!(out[0], json!(["TracingObject.expandTracing(true) is not implemented", "TypeError"])); + assert_eq!(out[1..4], [json!(true), json!("GroupItem"), json!(false)], "the group is a new object"); + assert_eq!(out[4], json!(["Stale page item", "Stale page item", "Stale page item"])); + assert_eq!(out[5], json!(true), "the group read again is the object expandTracing gave"); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + assert!(d.node(image).is_none(), "the expanded group keeps no source image"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn expand_keeps_images_moved_and_duplicated_into_the_tracing() { + let base = folder("expand-other-images"); + let (mut s, source) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.name = 'other';\ + r.duplicate(p, ElementPlacement.PLACEATEND); r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var g = p.tracing.expandTracing(); vc.log(g.typename); vc.log(d.rasterItems.length); vc.log(r.name);", + ); + assert_eq!(out, [json!("GroupItem"), json!(2), json!("other")]); + let d = &s.active().unwrap().doc; + assert!(d.node(source).is_none()); + let group = top(&s)[0]; + let images: Vec<_> = d.children(Some(group)).unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Image(_))).collect(); + assert_eq!(images.len(), 2); + assert!(images.iter().all(|n| n.name.as_deref() == Some("other"))); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_replacements_refuse_protected_artwork() { + let base = folder("protected-replacements"); + for operation in ["trace", "retrace", "expand", "release", "view"] { + for protection in ["locked", "hidden", "locked-layer", "hidden-layer", "locked-artboard"] { + let (mut s, image) = session(&base, false); + let (target, action) = if operation == "trace" { + (image, "item.trace();") + } else { + let r = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let action = match operation { + "retrace" => "item.tracing.tracingOptions.threshold = 90;", + "expand" => "item.tracing.expandTracing();", + "view" => "item.tracing.tracingOptions.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES;", + _ => "item.tracing.releaseTracing();", + }; + (NodeId(r["id"].as_u64().unwrap()), action) + }; + s.edit("Protect artwork", |d, _| { + if protection == "locked-artboard" { + d.artboards[0].locked = true; + } else { + let protected = if protection.ends_with("-layer") { d.layers[0].id } else { target }; + let node = d.node_mut(protected).unwrap(); + node.locked = protection.starts_with("locked"); + node.visible = !protection.starts_with("hidden"); + } + Ok(()) + }) + .unwrap(); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!("var item = app.activeDocument.pageItems[0], m = ''; try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);"), + ); + assert_eq!(out, [json!(format!("Cannot edit page item {}", target.0))], "{operation}: {protection}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{operation}: {protection}"); + assert_eq!(s.active().unwrap().selection, selection); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_refuses_added_artwork_before_changing_the_document() { + let base = folder("retrace-added-artwork"); + for artwork in [ + "r.move(p, ElementPlacement.PLACEATEND);", + "r.duplicate(p, ElementPlacement.PLACEATEND);", + "d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);", + ] { + for action in ["o.threshold = 90;", "o.loadFromPreset('Silhouettes');"] { + let (mut s, _) = session(&base, false); + s.execute("file.place", &json!({"path": base.join("main/disc.png").to_string_lossy(), "link": false})).unwrap(); + let setup = format!("var d = app.activeDocument, r = d.rasterItems[0], p = d.rasterItems[1].trace(); {artwork}"); + let mut expected = Session::new(); + expected.docs = s.docs.clone(); + expected.active = s.active; + log(&mut expected, &base, &setup); + let before = vectorcraft_format::save(&expected.active().unwrap().doc, false); + let selection = expected.active().unwrap().selection.clone(); + let steps = undo_steps(&expected); + let out = log( + &mut s, + &base, + &format!( + "{setup} var items = app.activeDocument.pageItems;\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\ + var o = p.tracing.tracingOptions, m = '';\ + try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);" + ), + ); + assert_eq!(out, [json!("Cannot retrace a tracing containing added artwork")], "{artwork} {action}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(s.active().unwrap().selection, selection); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn copied_traces_remap_child_records_without_accepting_added_artwork() { + let base = folder("retrace-copied-artwork"); + for (added, retraced) in [(false, false), (true, false), (false, true), (true, true)] { + let (mut s, _) = session(&base, false); + let retrace = if retraced { "o.threshold = 100;" } else { "" }; + let artwork = if added { "d.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" }; + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[0].trace(), copy = p.duplicate(), o = copy.tracing.tracingOptions;\ + {retrace} {artwork}\ + var m = ''; try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }}\ + vc.log(m); vc.log(copy.isTracing); vc.log(o.threshold);" + ), + ); + let message = if added { "Cannot retrace a tracing containing added artwork" } else { "" }; + assert_eq!(out[..2], [json!(message), json!(true)], "added: {added}, retraced: {retraced}"); + if !added { + assert_eq!(out[2], json!(90)); + } + } + let _ = std::fs::remove_dir_all(base); +} + +/// The objects in the object `id` of the active document, without it, in order. +fn members(s: &Session, id: NodeId) -> Vec { + let mut out = vec![]; + if let Some(n) = s.active().unwrap().doc.node(id) { + n.walk(&mut |m| { + if m.id != id { + out.push(m.id); + } + }); + } + out +} + +/// A new session with the active document of `s`, saved and opened again. +fn reopened(s: &Session) -> Session { + let bytes = vectorcraft_format::save(&s.active().unwrap().doc, false); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "traced.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); + o +} + +/// Traces the Image Trace object `index` of the active document's page items again with a +/// threshold of 90, and logs the error, or `""`. +fn retrace_item(index: usize) -> String { + format!( + "(function () {{ var items = app.activeDocument.pageItems, found = [];\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') found.push(items[i]);\ + var o = found[{index}].tracing.tracingOptions, m = '';\ + try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }} vc.log(m); }})();" + ) +} + +const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork"; + +#[test] +fn retrace_refuses_artwork_added_before_the_run() { + let base = folder("retrace-earlier-artwork"); + for by_command in [false, true] { + for reopen in [false, true] { + let (mut s, image) = session(&base, false); + let trace = if by_command { + s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + "var p = app.activeDocument.pageItems[0];" + } else { + "var p = app.activeDocument.rasterItems[0].trace();" + }; + log(&mut s, &base, &format!("{trace} app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);")); + let mut s = if reopen { reopened(&s) } else { s }; + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log(&mut s, &base, &retrace_item(0)); + assert_eq!(out, [json!(ADDED_ARTWORK)], "by command: {by_command}, reopened: {reopen}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "by command: {by_command}, reopened: {reopen}"); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_takes_a_tracing_whose_traced_objects_were_edited() { + let base = folder("retrace-edited-artwork"); + for reopen in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let made = s.active().unwrap().doc.node(group).and_then(|g| g.trace_made()).expect("the trace records what it made"); + let held = members(&s, group); + assert!(held.len() > 1 && held.iter().all(|m| made.contains(*m)), "{held:?} {made:?}"); + assert!(!made.contains(group)); + let path = held[held.len() - 1]; + s.execute("object.move", &json!({"ids": [path.0], "dx": 5, "dy": 0})).unwrap(); + let mut s = if reopen { reopened(&s) } else { s }; + let out = log(&mut s, &base, &format!("{} vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.threshold);", retrace_item(0))); + assert_eq!(out, [json!(""), json!(90)], "reopened: {reopen}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_copied_tracing_retraces_in_a_later_run() { + let base = folder("retrace-copy-later"); + for added in [false, true] { + for reopen in [false, true] { + let (mut s, _) = session(&base, false); + let artwork = if added { "app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" }; + log(&mut s, &base, &format!("var p = app.activeDocument.rasterItems[0].trace(), copy = p.duplicate(); {artwork}")); + let groups = traces(&s); + assert_eq!(groups.len(), 2); + let records: Vec<_> = groups.iter().map(|g| s.active().unwrap().doc.node(*g).and_then(|n| n.trace_made()).unwrap()).collect(); + for (k, g) in groups.iter().enumerate() { + assert!(members(&s, *g).iter().all(|m| !records[1 - k].contains(*m)), "a tracing records none of the other's objects"); + } + let mut s = if reopen { reopened(&s) } else { s }; + let out = log(&mut s, &base, &format!("{} {}", retrace_item(0), retrace_item(1))); + let message = if added { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message), json!("")], "added: {added}, reopened: {reopen}"); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() { + let base = folder("retrace-legacy"); + for same_run in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + let add = "var r = app.activeDocument.pathItems.rectangle(20, 20, 10, 10); r.name = 'added'; r.move(app.activeDocument.pageItems[1], ElementPlacement.PLACEATEND);"; + let out = if same_run { + log(&mut s, &base, &format!("{add} {}", retrace_item(0))) + } else { + log(&mut s, &base, add); + log(&mut s, &base, &retrace_item(0)) + }; + let message = if same_run { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message)], "same run: {same_run}"); + let mut named = false; + s.active().unwrap().doc.walk(|n| named |= n.name.as_deref() == Some("added")); + assert_eq!(named, same_run, "tracing again drops what was added, as before"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn engine_trace_can_be_retraced_by_a_script() { + let base = folder("retrace-engine-artwork"); + let (mut s, image) = session(&base, false); + let made = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let group = NodeId(made["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.pageItems[0], o = p.tracing.tracingOptions;\ + o.threshold = 90; vc.log(o.threshold); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!(90), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_ne!(groups[0], group); + assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90)); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0])); + assert_eq!(undo_steps(&s), steps + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_limit_counts_retraces_of_an_undone_group() { + let base = folder("retrace-limit-undo"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions, count = 0, m = '';\ + try { for (; count < 10001; count++) { o.threshold = 90; app.undo(); } } catch (e) { m = e.message; }\ + vc.log(count); vc.log(m); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!(10000), json!("a run traces a tracing again at most 10000 times"), json!(true)]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_and_option_changes_log_command_warnings() { + let base = folder("trace-warnings"); + let (mut s, _) = session(&base, false); + let png = base.join("main/wide.png"); + std::fs::write(&png, vectorcraft_trace::Raster::from_fn(1501, 2, |_, _| [0, 0, 0, 255]).encode_png()).unwrap(); + let placed = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let image = placed["ids"][0].as_u64().unwrap(); + let made = s.execute("imageTrace.make", &json!({"id": image})).unwrap(); + let warnings = made["warnings"].as_array().unwrap().clone(); + assert!(!warnings.is_empty()); + s.execute("imageTrace.release", &json!({"id": made["id"]})).unwrap(); + let report = run(&mut s, &base, "var p = app.activeDocument.rasterItems[0].trace(); p.tracing.tracingOptions.threshold = 90;").unwrap(); + let lines = report["console"]["lines"].as_array().unwrap(); + let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect(); + assert_eq!(lines, &expected.iter().chain(&expected).cloned().collect::>()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn option_changes_log_why_no_paths_were_traced() { + let base = folder("trace-no-paths-warning"); + let (mut s, image) = session(&base, false); + let made = s.execute("imageTrace.make", &json!({"id": image.0, "params": {"keepColors": ["#ff00ff"]}})).unwrap(); + assert_eq!(made["paths"], json!(0)); + let warnings = made["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("Nothing was traced"))); + let report = run(&mut s, &base, "app.activeDocument.pageItems[0].tracing.tracingOptions.threshold = 90;").unwrap(); + let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect(); + assert_eq!(report["console"]["lines"], json!(expected)); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_parent_keeps_plugin_identity_after_retracing() { + let base = folder("parent-identity"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing;\ + vc.log(t.parent === p); t.tracingOptions.threshold = 90; vc.log(t.parent === p);\ + vc.log(p.tracing.parent === p); t.tracingOptions.threshold = 100; vc.log(t.parent === p);", + ); + assert_eq!(out, vec![json!(true); 4]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn plugin_is_tracing_refuses_a_replaced_source_without_reading_tracing() { + let base = folder("plugin-replaced-source"); + let (mut s, source) = session(&base, false); + s.execute("file.place", &json!({"path": base.join("main/disc.png").to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0];\ + r.move(p, ElementPlacement.PLACEATEND); vc.run('edit.clear', {{ids: [{}]}}); var m = [];\ + try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }}\ + try {{ p.tracing; }} catch (e) {{ m.push(e.message); }} vc.log(m);", + source.0 + ), + ); + assert_eq!(out, [json!(["Stale page item", "Stale page item"])]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_handle_is_stale_when_another_image_replaces_its_source() { + let base = folder("replaced-source"); + let (mut s, source) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[1].trace(), t = p.tracing, o = t.tracingOptions, r = d.rasterItems[0];\ + r.move(p, ElementPlacement.PLACEATEND); vc.run('edit.clear', {{ids: [{}]}}); var m = [];\ + try {{ t.sourceArt; }} catch (e) {{ m.push(e.message); }}\ + try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }}\ + try {{ o.threshold; }} catch (e) {{ m.push(e.message); }}\ + try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }} vc.log(m);", + source.0 + ), + ); + assert_eq!(out, [json!(vec!["Stale page item"; 4])]); + assert!(s.active().unwrap().doc.node(source).is_none()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_replacements_preserve_direct_selection_of_other_paths() { + for (name, finish) in [ + ("make", ""), + ("retrace", "p.tracing.tracingOptions.threshold = 90;"), + ("expand", "p.tracing.expandTracing();"), + ("release", "p.tracing.releaseTracing();"), + ] { + let base = folder(&format!("direct-selection-{name}")); + let (mut s, image) = session(&base, false); + let mut paths = vec![]; + for x in [100, 200] { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 20, "height": 20})).unwrap(); + paths.push(NodeId(r["id"].as_u64().unwrap())); + } + s.execute("select.anchors", &json!({"id": paths[0].0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.segments", &json!({"id": paths[1].0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.add", &json!({"ids": [image.0]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + log(&mut s, &base, &format!("var p = app.activeDocument.rasterItems[0].trace(); {finish}")); + let after = &s.active().unwrap().selection; + assert_eq!(after.anchors, before.anchors, "{name}"); + assert_eq!(after.segments, before.segments, "{name}"); + assert_eq!(after.objects.len(), before.objects.len(), "{name}"); + assert_eq!(after.objects[..2], paths, "{name}"); + if name == "release" { + assert_eq!(after.objects[2], image); + } else { + assert_ne!(after.objects[2], image, "{name}"); + assert!(matches!(s.active().unwrap().doc.node(after.objects[2]).unwrap().kind, NodeKind::Group { .. })); + } + let _ = std::fs::remove_dir_all(base); + } +} + +#[test] +fn trace_options_retrace_preserves_source_and_view() { + let base = folder("options"); + let (mut s, image) = session(&base, false); + let defaults = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap(); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing, o = t.tracingOptions;\ + vc.log([o.tracingMode, o.threshold, o.fills, o.strokes, o.maxColors, o.palette, o.ignoreWhite, o.minArea]);\ + vc.log([o.viewRaster, o.viewVector]);\ + o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE;\ + o.threshold = 200; o.minArea = 4;\ + vc.log([o.threshold, o.minArea, o.preset, o.viewRaster, o.viewVector]);\ + vc.log(t.sourceArt.name); vc.log(r.name); vc.log(p.isTracing); vc.log(p.tracing.tracingOptions.threshold); vc.log(t.pathCount > 0);", + ); + let mode = |m: &str| json!(format!("TracingModeType.TRACINGMODE{m}")); + let expected_mode = match defaults["mode"].as_str() { + Some("blackAndWhite") => mode("BLACKANDWHITE"), + Some("grayscale") => mode("GRAY"), + _ => mode("COLOR"), + }; + assert_eq!( + out[0], + json!([ + expected_mode, + defaults["threshold"], + defaults["fills"], + defaults["strokes"], + defaults["colors"], + "Limited", + defaults["ignoreWhite"], + defaults["noise"] + ]) + ); + assert_eq!(out[1], json!(["ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"])); + assert_eq!(out[2], json!([200, 4, "Custom", "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"])); + assert_eq!(out[3..], [json!("src"), json!("src"), json!(true), json!(200), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let t = trace_of(&s, groups[0]); + assert_eq!( + (t["params"]["threshold"].clone(), t["params"]["noise"].clone(), t["view"].clone()), + (json!(200), json!(4), json!("outlinesWithSourceImage")) + ); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0])); + + // Assigning the values the options have already changes nothing. + let before = (undo_steps(&s), traces(&s)); + let out = log( + &mut s, + &base, + "var o = app.activeDocument.pageItems[0].tracing.tracingOptions; o.threshold = 200; o.minArea = 4; o.fills = true;\ + o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; vc.log(o.threshold);", + ); + assert_eq!(out, [json!(200)]); + assert_eq!((undo_steps(&s), traces(&s)), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_invalid_option_is_atomic() { + let base = folder("invalid"); + let (mut s, _) = session(&base, false); + log(&mut s, &base, "app.activeDocument.rasterItems[0].trace();"); + let before = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); + let saved = vectorcraft_format::save(&s.active().unwrap().doc, false); + let cases = [ + ("o.threshold = 'x'", "TypeError"), + ("o.threshold = 256", "TracingOptions.threshold is out of range"), + ("o.threshold = -1", "TracingOptions.threshold is out of range"), + ("o.threshold = 1.5", "TracingOptions.threshold is out of range"), + ("o.threshold = NaN", "TypeError"), + ("o.maxColors = 1", "TracingOptions.maxColors is out of range"), + ("o.maxColors = 257", "TracingOptions.maxColors is out of range"), + ("o.minArea = 1e12", "TracingOptions.minArea is out of range"), + ("o.fills = 1", "TypeError"), + ("o.fills = false", "TracingOptions requires fills or strokes"), + ("o.tracingMode = 'color'", "TypeError"), + ("o.palette = 'Spectrum'", "TracingOptions.palette has an invalid value"), + ("o.palette = 3", "TypeError"), + ("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERADJUSTEDIMAGE", "TracingOptions.viewRaster has an invalid value"), + ("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "TracingOptions.viewRaster has an invalid value"), + ("o.viewVector = 'outlines'", "TypeError"), + ("o.pathFitting = 3", "TracingOptions.pathFitting is not implemented"), + ("o.cornerAngle", "TracingOptions.cornerAngle is not implemented"), + ("o.resampleResolution = 72", "TracingOptions.resampleResolution is not implemented"), + ("t.areaCount", "TracingObject.areaCount is not implemented"), + ("o.loadFromPreset('No Such Preset')", "no built-in or saved preset has that name"), + ("o.loadFromPreset('../Default')", "cannot hold"), + ("o.loadFromPreset('C:\\\\x')", "cannot hold"), + ("o.loadFromPreset('a\\u0000b')", "cannot hold"), + ("o.loadFromPreset(new Array(300).join('x'))", "at most 256 bytes"), + ("o.loadFromPreset(' ')", "the preset name is empty"), + ("o.loadFromPreset(5)", "TypeError"), + ("o.storeToPreset('Mine')", "a script cannot run `imageTrace.presets.save`"), + ("o.storeToPreset('../Mine')", "cannot hold"), + ]; + let mut wrong = vec![]; + for (code, message) in cases { + let out = log( + &mut s, + &base, + &format!( + "var t = app.activeDocument.pageItems[0].tracing, o = t.tracingOptions, m = 'none';\ + try {{ {code}; }} catch (e) {{ m = e.name + ': ' + e.message; }} vc.log(m); vc.log(o.threshold);" + ), + ); + let m = out[0].as_str().unwrap_or_default().to_string(); + let now = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); + let unchanged = vectorcraft_format::save(&s.active().unwrap().doc, false) == saved; + if !m.contains(message) || out[1] != before.2["params"]["threshold"] || now != before || !unchanged { + wrong.push(format!("{code}: {m}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + assert!(s.prefs.trace_presets.is_empty(), "no preset was saved"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_presets_load_and_locked_store() { + let base = folder("presets"); + let (mut s, _) = session(&base, false); + let silhouettes = serde_json::to_value(vectorcraft_trace::preset("Silhouettes").unwrap()).unwrap(); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\ + vc.log(o.loadFromPreset('Silhouettes')); vc.log(o.preset); vc.log(o.threshold);\ + vc.log(o.storeToPreset('Default')); vc.log(o.storeToPreset('custom')); vc.log(o.storeToPreset('Silhouettes'));", + ); + assert_eq!(out, [json!(true), json!("Silhouettes"), silhouettes["threshold"].clone(), json!(false), json!(false), json!(false)]); + let t = trace_of(&s, traces(&s)[0]); + assert_eq!(t["params"], silhouettes); + + // Loading the preset the tracing has already traces nothing again. + let before = (undo_steps(&s), traces(&s)); + let out = log(&mut s, &base, "vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.loadFromPreset('silhouettes'));"); + assert_eq!(out, [json!(true)]); + assert_eq!((undo_steps(&s), traces(&s)), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_external_retrace_undo_and_source_delete() { + let base = folder("stale"); + let (mut s, image) = session(&base, false); + let threshold = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap()["threshold"].clone(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, m = [];\ + var p = d.rasterItems[0].trace(), t = p.tracing; d.selection = p; vc.run('imageTrace.make', {{}});\ + try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }}\ + var q = d.pageItems[0], u = q.tracing, o = u.tracingOptions; o.threshold = 90; vc.log(o.threshold); vc.log(q.isTracing);\ + vc.run('edit.undo'); vc.log(q.isTracing); vc.log(o.threshold); vc.log(u.pathCount > 0);\ + var r = ''; try {{ u.sourceArt.remove(); }} catch (e) {{ r = e.message; }} vc.log(r); vc.log(u.pathCount > 0);\ + vc.run('edit.clear', {{ids: [{}]}});\ + try {{ u.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ q.isTracing; }} catch (e) {{ m.push(e.message); }}\ + vc.log(d.pageItems[0].typename); vc.log(m);", + image.0 + ), + ); + assert_eq!(out[..5], [json!(90), json!(true), json!(true), threshold, json!(true)], "the undo puts the first tracing back"); + assert!(out[5].as_str().is_some_and(|m| m.starts_with("cannot delete hidden or locked objects")), "{:?}", out[5]); + assert_eq!(out[6], json!(true), "the refused remove leaves the tracing"); + assert_eq!(out[7], json!("GroupItem"), "a group without its source image is no longer a tracing"); + assert_eq!(out[8], json!(vec!["Stale page item"; 4])); + let _ = std::fs::remove_dir_all(base); +} + +/// After two option changes, an Undo puts back the tracing the first change made, and the objects +/// of the first tracing follow it there. +#[test] +fn trace_undo_of_the_second_retrace_reaches_the_first() { + let base = folder("chain"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\ + o.threshold = 90; o.threshold = 60; vc.log(o.threshold); vc.run('edit.undo');\ + vc.log(o.threshold); vc.log(p.isTracing); vc.log(p.tracing.pathCount > 0);", + ); + assert_eq!(out, [json!(60), json!(90), json!(true), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90)); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_deleted_plugin_is_stale() { + let base = folder("deleted"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = []; p.remove();\ + try { p.name; } catch (e) { m.push(e.message); } try { t.sourceArt; } catch (e) { m.push(e.message); }\ + try { o.threshold = 10; } catch (e) { m.push(e.message); } try { t.releaseTracing(); } catch (e) { m.push(e.message); }\ + try { o.pathFitting; } catch (e) { m.push(e.message); } try { o.cornerAngle = 1; } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out, [json!(vec!["Stale page item"; 6])]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// A script's trace of an image past the tracer's source limit (`vectorcraft_trace::MAX_SOURCE_PIXELS`, +/// 192 megapixels) is refused from the image's header before its pixels are decoded, and the run +/// leaves the document as it was. +#[test] +fn trace_large_image_is_bounded() { + let base = folder("large"); + let png = base.join("main/wall.png"); + std::fs::write(&png, super::linkspanel::png_header(30_000, 30_000)).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let image = NodeId(r["ids"][0].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.rasterItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);"); + let m = out[0].as_str().unwrap_or_default(); + assert!(m.contains("30000 × 30000 pixels") && m.contains("(192 megapixels)"), "{m}"); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + assert_eq!(undo_steps(&s), steps); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_remove_all_takes_the_tracing() { + let base = folder("remove-all"); + let (mut s, _) = session(&base, false); + let out = log(&mut s, &base, "var d = app.activeDocument; d.rasterItems[0].trace(); d.pageItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, [json!(0)]); + assert!(traces(&s).is_empty()); + assert!(top(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_stop_rolls_back_long_work() { + let base = folder("stop"); + let (mut s, image) = session(&base, false); + let before = top(&s); + s.script_in_run = true; + let stop = s.script_interrupt(); + stop.set(); + let r = s.execute("imageTrace.make", &json!({"id": image.0})); + stop.clear(); + s.script_in_run = false; + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(top(&s), before); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_stop_rolls_back_a_handed_in_trace() { + let base = folder("stop-hand-off"); + let (mut s, image) = session(&base, false); + let before = top(&s); + let p = json!({"id": image.0}); + let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap(); + run.run(&|_, _| true).unwrap().hand_in(&mut s); + s.script_in_run = true; + let stop = s.script_interrupt(); + stop.set(); + let r = s.execute("imageTrace.make", &p); + stop.clear(); + s.script_in_run = false; + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(top(&s), before); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_trace_refuses_the_source_image_of_a_trace() { + let base = folder("source"); + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let e = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap_err().to_string(); + assert!(e.contains("source image of an Image Trace object"), "{e}"); + assert_eq!(traces(&s), [group]); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(group)); + + // With another image named after the source image, that other image is traced. + let png = base.join("main/disc.png"); + let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let other = NodeId(other["ids"][0].as_u64().unwrap()); + let r = s.execute("imageTrace.make", &json!({"ids": [image.0, other.0]})).unwrap(); + let second = NodeId(r["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(other), Some(second)); + assert_eq!(d.parent_of(image), Some(group)); + assert_eq!(traces(&s).len(), 2); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_of_another_image_inside_a_tracing() { + let base = folder("inside"); + let (mut s, image) = session(&base, false); + let png = base.join("main/disc.png"); + let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let other = NodeId(other["ids"][0].as_u64().unwrap()); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var q = r.trace(); vc.log(q.typename); vc.log(q.tracing.sourceArt === r); vc.log(p.tracing.pathCount > 0);\ + vc.log(p.tracing.pathCount === 2 * q.tracing.pathCount); vc.log(p.tracing.anchorCount === 2 * q.tracing.anchorCount);", + ); + // The two traces are of the same image with the same settings: the outer counts take in the + // inner trace's paths without its seam fills. + assert_eq!(out, [json!("PluginItem"), json!(true), json!(true), json!(true), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 2); + let d = &s.active().unwrap().doc; + let (a, b) = (d.parent_of(image).unwrap(), d.parent_of(other).unwrap()); + assert!(groups.contains(&a) && groups.contains(&b) && a != b, "each image is the source of its own tracing"); + assert!(d.parent_of(a) == Some(b) || d.parent_of(b) == Some(a), "one tracing is inside the other"); + let _ = std::fs::remove_dir_all(base); +} + +/// An object moved or duplicated to the end of a tracing goes directly above its source image, +/// which stays the tracing's first child. +#[test] +fn an_object_placed_at_the_end_of_a_tracing_stays_above_its_source() { + let base = folder("at-end"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, a = d.rasterItems[1]; a.name = 'src'; var p = a.trace(), r = d.rasterItems[0]; r.name = 'moved';\ + r.duplicate(p, ElementPlacement.PLACEATEND); r.move(p, ElementPlacement.PLACEATEND);\ + var s = p.tracing.sourceArt; s.hidden = false; s.move(p, ElementPlacement.PLACEATEND);\ + vc.log(p.tracing.sourceArt.name); vc.log(d.rasterItems.length); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!("src"), json!(2), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + let names: Vec> = d.children(Some(groups[0])).unwrap().iter().map(|n| n.name.clone()).collect(); + let name = |n: &str| Some(n.to_string()); + assert_eq!(names[..3], [name("src"), name("moved"), name("moved")], "the source stays first: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The source image stays a tracing's first child when it goes to the front of the tracing, and +/// when another object in the tracing is sent to the back or the source is brought to the front. +#[test] +fn reordering_inside_a_tracing_keeps_the_source_first() { + let base = folder("reorder"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, a = d.rasterItems[1]; a.name = 'src'; var p = a.trace(), r = d.rasterItems[0]; r.name = 'moved';\ + r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var s = p.tracing.sourceArt; s.hidden = false; s.move(p, ElementPlacement.PLACEATBEGINNING); vc.log(p.isTracing);\ + r.zOrder(ZOrderMethod.SENDTOBACK); vc.log(p.isTracing); r.zOrder(ZOrderMethod.SENDBACKWARD); vc.log(p.isTracing);\ + s.zOrder(ZOrderMethod.BRINGTOFRONT); s.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(p.isTracing); vc.log(p.tracing.sourceArt.name);", + ); + assert_eq!(out, [json!(true), json!(true), json!(true), json!(true), json!("src")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + let names: Vec> = d.children(Some(groups[0])).unwrap().iter().map(|n| n.name.clone()).collect(); + assert_eq!(names[..2], [Some("src".to_string()), Some("moved".to_string())], "the source stays first: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A tracing's source image cannot be moved out of its tracing, and the refused move leaves the +/// document as it was. +#[test] +fn the_source_image_cannot_leave_its_tracing() { + let base = folder("source-leaves"); + let (mut s, _) = session(&base, false); + log(&mut s, &base, "app.activeDocument.rasterItems[0].trace().tracing.sourceArt.hidden = false;"); + let saved = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.pageItems[0], m = 'none';\ + try { p.tracing.sourceArt.move(p, ElementPlacement.PLACEBEFORE); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!("a tracing's source image cannot leave its tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), saved); + assert_eq!(undo_steps(&s), steps); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_source_art_is_not_listed_with_the_images() { + let base = folder("lists"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument; d.rasterItems[0].trace(); var n = d.rasterItems.length, k = 0;\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename === 'RasterItem') k++; }\ + d.rasterItems.removeAll(); vc.log(n); vc.log(k); vc.log(d.rasterItems.length); vc.log(d.pageItems[0].typename);", + ); + assert_eq!(out, [json!(1), json!(1), json!(0), json!("PluginItem")]); + assert_eq!(traces(&s).len(), 1, "removing the raster items leaves the tracing"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_plugin_keeps_its_name() { + let base = folder("renamed"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(), t = p.tracing, m = '', n = p.name; p.name = n;\ + try { p.name = 'logo'; } catch (e) { m = e.message; } vc.log(m); vc.log(p.name === n); vc.log(p.typename); vc.log(t.pathCount > 0);", + ); + assert_eq!(out, [json!("The name of a tracing cannot be changed"), json!(true), json!("PluginItem"), json!(true)]); + assert_eq!(traces(&s).len(), 1); + assert_eq!(undo_steps(&s), 2, "the place and the run"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_group_holding_an_image_cannot_take_the_tracing_name() { + let base = folder("rename-to-trace"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, m = ''; d.selection = [d.rasterItems[0]]; vc.run('object.group'); var g = d.pageItems[0];\ + try { g.name = 'Image Trace'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.typename); g.name = 'Logo'; vc.log(g.name);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem"), json!("Logo")]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn an_image_cannot_move_first_into_a_group_named_as_a_tracing() { + let base = folder("move-into-trace-name"); + let (mut s, _) = session(&base, false); + let before = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, r = d.rasterItems[0], m = [];\ + d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); var g = d.pageItems[0];\ + g.name = 'Image Trace';\ + try { r.move(g, ElementPlacement.PLACEATEND); m.push('moved'); } catch (e) { m.push(e.message); }\ + try { r.duplicate(g, ElementPlacement.PLACEATEND); m.push('copied'); } catch (e) { m.push(e.message); }\ + vc.log(m); vc.log(d.rasterItems.length); vc.log(g.typename);\ + r.move(g, ElementPlacement.PLACEATBEGINNING); vc.log(g.typename);", + ); + let refused = json!("Only Image Trace can make a tracing"); + assert_eq!(out, [json!([refused, refused]), json!(1), json!("GroupItem"), json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + let g = top(&s)[0]; + let kids: Vec = d.children(Some(g)).unwrap().iter().map(|n| matches!(n.kind, crate::doc::NodeKind::Image(_))).collect(); + assert_eq!(kids, [false, true], "the image went in above the rectangle"); + assert_eq!(undo_steps(&s), before + 1, "the run is one step"); + let _ = std::fs::remove_dir_all(base); +} + +/// `move`, `remove()` and `zOrder` refuse to leave an image at the bottom of an ordinary group named +/// as a tracing, before the document changes, and allow the same moves when another object stays +/// at the bottom. +#[test] +fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() { + let base = folder("leave-trace-name"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], r = d.rasterItems[0], p = d.pathItems[0], m = [];\ + function t(f) { try { f(); m.push('done'); } catch (e) { m.push(e.message); } }\ + t(function () { p.move(g, ElementPlacement.PLACEBEFORE); });\ + t(function () { p.move(g, ElementPlacement.PLACEATBEGINNING); });\ + t(function () { p.remove(); });\ + t(function () { p.zOrder(ZOrderMethod.BRINGTOFRONT); });\ + t(function () { p.zOrder(ZOrderMethod.BRINGFORWARD); });\ + t(function () { r.zOrder(ZOrderMethod.SENDTOBACK); });\ + t(function () { r.zOrder(ZOrderMethod.SENDBACKWARD); });\ + vc.log(m); vc.log(g.typename);", + ); + assert_eq!(out, [json!(vec!["Only Image Trace can make a tracing"; 7]), json!("GroupItem")]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], p = d.pathItems[0];\ + d.pathItems.rectangle(40, 40, 5, 5).move(g, ElementPlacement.PLACEATEND);\ + p.move(g, ElementPlacement.PLACEBEFORE); vc.log(g.typename);", + ); + assert_eq!(out, [json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + let g = top(&s).into_iter().find(|i| d.node(*i).is_some_and(|n| n.name.as_deref() == Some(crate::cmd::TRACE_NAME))).unwrap(); + assert_eq!(d.children(Some(g)).unwrap().len(), 2, "the rectangle left the group"); + let _ = std::fs::remove_dir_all(base); +} + +/// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object +/// its trace did not make, before the document changes. +#[test] +fn release_refuses_added_artwork_before_changing_the_document() { + let base = folder("release-added-artwork"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(); d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var items = app.activeDocument.pageItems, p, m = '';\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\ + try { p.tracing.releaseTracing(); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!("Cannot release a tracing containing added artwork")]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + assert_eq!(traces(&s).len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// Retracing and releasing discard the objects the trace made, so both refuse a tracing that holds +/// a locked one, before the document changes. +#[test] +fn retrace_and_release_refuse_locked_traced_artwork() { + let base = folder("locked-traced-artwork"); + for action in ["p.tracing.tracingOptions.threshold = 90;", "p.tracing.releaseTracing();"] { + let (mut s, image) = session(&base, false); + let r = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let group = NodeId(r["id"].as_u64().unwrap()); + let made = s.active().unwrap().doc.node(group).unwrap().children().unwrap()[1].id; + s.edit("Lock traced artwork", |d, _| { + d.node_mut(made).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!("var p = app.activeDocument.pageItems[0], m = ''; try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);"), + ); + assert_eq!(out, [json!(format!("Cannot edit page item {}", made.0))], "{action}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{action}"); + assert_eq!(undo_steps(&s), steps, "{action}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// The `TracingOptions` and `TracingObject` members that are not implemented are left out of +/// `hasOwnProperty` and `reflect`, and still throw when read. +#[test] +fn unimplemented_tracing_members_are_not_reported() { + let base = folder("unimplemented-members"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = '';\ + vc.log([o.hasOwnProperty('pathFitting'), t.hasOwnProperty('areaCount'), t.hasOwnProperty('pathCount')]);\ + vc.log([o.reflect.find('pathFitting') === null, t.reflect.find('areaCount') === null, t.reflect.find('pathCount') === null]);\ + try { t.areaCount; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!([false, false, true]), json!([true, true, false]), json!("TracingObject.areaCount is not implemented")]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_keeps_the_tracing_opacity_and_blend_mode() { + let base = folder("retrace-appearance"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(); p.opacity = 50; p.blendingMode = BlendModes.MULTIPLY;\ + p.tracing.tracingOptions.threshold = 90; vc.log(p.opacity); vc.log(p.blendingMode === BlendModes.MULTIPLY);\ + p.tracing.tracingOptions.threshold = 100; vc.log(p.opacity); vc.log(p.blendingMode === BlendModes.MULTIPLY);", + ); + assert_eq!(out, [json!(50), json!(true), json!(50), json!(true)]); + let id = traces(&s)[0]; + assert_eq!(s.active().unwrap().doc.node(id).unwrap().opacity, 0.5); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retraced_plugin_is_the_same_object_as_its_collection_handle() { + let base = folder("retrace-identity"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(); vc.log(d.pageItems[0] === p);\ + p.tracing.tracingOptions.threshold = 90; vc.log(d.pageItems[0] === p); vc.log(app.selection[0] === p);\ + p.tracing.tracingOptions.threshold = 100; vc.log(d.pageItems[0] === p); vc.log(p.tracing.parent === d.pageItems[0]);", + ); + assert_eq!(out, vec![json!(true); 5]); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 2373640149..11bcd74225 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -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"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index a78fd82d75..edd38c8699 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -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(" 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, + "\ + ", + ) + .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 = + 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!(""), + ) + .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] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 38bd038e36..80799c0095 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -50,7 +50,8 @@ 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. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"), ("Window.", "alert confirm length prompt prototype"), @@ -89,9 +90,9 @@ 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 RasterItem RasterItems RulerUnits ScreenMode selection selection= \ + StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod", ), ("Application.", "prototype"), ( @@ -120,8 +121,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"), @@ -142,6 +143,37 @@ const INSIDE: &[(&str, &str)] = &[ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("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"), @@ -243,6 +275,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. ( "", @@ -457,11 +502,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` and `TextFrame`, the color classes, and the save and export option classes. +/// other than `PathItem`, `PlacedItem`, `RasterItem` and `TextFrame`, 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. diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 6c85414463..db310e0f01 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -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> { + 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 { diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 95606c9ebb..e0a46fccb0 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -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, 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)) } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 9ef4cbc840..fe425346d2 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -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::>(); + 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). diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index e9bf596eb3..c27dc3c3c6 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -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); diff --git a/crates/eps/src/import/preview.rs b/crates/eps/src/import/preview.rs index 36c0e5662c..87037fcd1a 100644 --- a/crates/eps/src/import/preview.rs +++ b/crates/eps/src/import/preview.rs @@ -46,7 +46,7 @@ fn image_doc(img: image::RgbaImage, frame: Rect) -> Option { } 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(); diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 011cb86ce3..f920a1c364 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -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> { d.layers[0].children().unwrap().clone() diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index e7fd734240..87a7560bfd 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -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] <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] diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index a587c74fbb..d4b687f1f0 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -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`. diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs new file mode 100644 index 0000000000..6438392335 --- /dev/null +++ b/crates/js/src/async_tests.rs @@ -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 = 78; 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, 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:?}"); +} diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index d13e08bfdc..69af7138fa 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -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 { - 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 { - 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 { + 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)), diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs new file mode 100644 index 0000000000..1baaeaad79 --- /dev/null +++ b/crates/js/src/builtins/async_function.rs @@ -0,0 +1,40 @@ +//! `AsyncFunction` and its prototype (ECMA-262 2017 section 25.5, +//! ), 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 { + create_dynamic_function(interp, args, false, true) +} diff --git a/crates/js/src/builtins/generator.rs b/crates/js/src/builtins/generator.rs index c8e46e09d6..506cf23182 100644 --- a/crates/js/src/builtins/generator.rs +++ b/crates/js/src/builtins/generator.rs @@ -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 { - super::create_dynamic_function(interp, args, true) + super::create_dynamic_function(interp, args, true, false) } diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 7f684fbbf5..8182fde016 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -145,6 +145,8 @@ enum Then { Settle(ObjId, Option), /// 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, /// 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, + /// `AsyncFunction` (section 25.5.1), which is not a global. + pub(crate) async_function_ctor: Option, } 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 }) } +// ---- 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 { + 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) -> 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) -> 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 { + 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> { + 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) -> 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 JsResult { let mut v = v.clone(); loop { @@ -945,7 +1096,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { _ => 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, .. } => { diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index cda3d45ece..6512b2e91c 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -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, /// 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, /// The body refers to `arguments` or calls `eval`. pub(crate) uses_arguments: bool, pub(crate) source: Rc, @@ -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]) -> Result { 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")?), diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 93f8afb3e6..9b6bd6017a 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -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); diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 62436ae9ab..f13677ca52 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -124,6 +124,9 @@ struct FnCompiler<'a> { struct Hoisted { vars: Vec, 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, } 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 { 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, own_name: Option, 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 = f.params.iter().chain(&f.rest).filter(|p| matches!(p, Binding::Pattern(_))).flat_map(|p| c.bound_keys(p)).collect(); let all_params: Vec = 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) } diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 397521b8a3..1a076c43c1 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -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::()); + 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::(); + 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 diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs index 3a542a6365..361af9a01f 100644 --- a/crates/js/src/generator.rs +++ b/crates/js/src/generator.rs @@ -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, }); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index c758610862..3698826ab0 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -301,6 +301,8 @@ pub(crate) enum Class { Promise(Box), /// The state that the functions a promise operation makes share; scripts never see it. PromiseRecord(Box), + /// An async function's frame waiting at `await`, until it is resumed; scripts never see it. + Activation(Option>), /// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added. Map(Box), /// 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::(); let tables = code.finally_tables.iter().map(|t| 24 + 4 * t.len()).sum::(); @@ -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, 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 diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 10bcc8b49c..0a308c91fd 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -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; +/// 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>; /// 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,10 +312,24 @@ 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::>()); - 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 { let o = self.object_mut(id)?; if let Class::Host(h) = &mut o.class && h.class != class @@ -314,7 +345,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 +489,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)>, - /// 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)>, + objects: Vec<(MadeKey, ObjId, u32, Option)>, } impl Undo { @@ -486,9 +523,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 +571,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)); + } } } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 194a199b19..d6afcca217 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -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); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 2b7915c9b9..0639d52d25 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -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; + pub(crate) struct Frame { pub(crate) code: Rc, 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, + /// 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, + /// 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, usize); +pub(crate) mod async_function; + /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -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, /// 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, ObjId)>, @@ -375,9 +395,9 @@ pub(crate) struct Interp { pub(crate) host_classes: Vec, /// 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> { + 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> { 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, 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, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + fn instantiate_pending(&mut self, code: &Rc, 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, 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, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + /// Also gives the names of [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not + /// declare. + fn instantiate_global(&mut self, code: &Rc, 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, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + fn instantiate_global_rooted(&mut self, code: &Rc, 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, 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, + (env, lex): (EnvId, EnvId), + var_env: EnvId, + configurable: u8, + ) -> JsResult { // 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, ): 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 { + 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` diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs new file mode 100644 index 0000000000..9bcf7f274c --- /dev/null +++ b/crates/js/src/interp/async_function.rs @@ -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, +//! ): [`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, + pc: usize, + env: EnvId, + var_env: EnvId, + env_depth: u32, + this: Value, + this_in_env: bool, + strict_class: bool, + callee: Option, + new_target: Option, + this_env: Option, + completion: Value, + /// The promise the async function's call returned. + pub(crate) promise: ObjId, + stack: Vec, + 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 { + 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 { + 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 { + 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 { + 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(()) + } +} diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index cf47fa9848..8fa4dfe23d 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -1029,6 +1029,7 @@ fn code(ops: Vec) -> 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) -> Code { own_name: None, method: false, generator: false, + is_async: false, supers: crate::parser::SuperRules::default(), } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 731ef1aed1..a720940b06 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -126,6 +126,10 @@ //! ECMAScript 2020 defines them (sections 26.1 and 26.2 and 9.5, //! ), 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, ). +//! 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)] diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 12c76f6b47..b733f90093 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -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, + /// 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, + /// The last identifier expression read from an `async` written without escapes. + async_ident: Option, } impl<'s> Parser<'s> { pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result { - 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 { @@ -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 { - 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 { - 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 { - 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 { 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 { 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 = 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 { + /// 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 { 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 = 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) -> Result { + 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 { 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 { + 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 { 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> { + 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, 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 { @@ -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 { 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 { - 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) }); } diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs index 5d186c9b11..850846abe1 100644 --- a/crates/js/src/parser/module.rs +++ b/crates/js/src/parser/module.rs @@ -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)) } diff --git a/crates/js/src/parser/pattern.rs b/crates/js/src/parser/pattern.rs index b25350549a..4bb126f8c2 100644 --- a/crates/js/src/parser/pattern.rs +++ b/crates/js/src/parser/pattern.rs @@ -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 { 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)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 1fbdb5c003..078175b562 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -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", diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index fe92e15269..34cab5c170 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -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(); diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index fa81397b00..9581ebc0ac 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -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], 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], 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();"])); diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 0cfb8ea805..64da7fb8d5 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -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); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 629113680c..c85f36bd7f 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -378,19 +378,25 @@ pub(super) fn bounds(nodes: &[Arc]) -> Option { 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> { + 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, w: u32, h: u32) -> Option> { 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, w: u32, h: u32) -> Option> { 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, w: u32, h: u32) -> Option> { 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 { diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 5fdafeb5fc..731f18ff06 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -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")); diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 7a1085a152..00516ffd34 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1299,16 +1299,24 @@ fn a_trace_off_the_ui_thread_is_adopted_when_it_lands() { } /// The object Trace acts on as the panel found it before [`find_target`]: every selected object put -/// in paint order, the first image or Image Trace object among them taken, else the first selected -/// object. +/// in paint order, the first image or Image Trace object among them taken (an Image Trace object's +/// source image is traced through that object, so it is skipped), else the first selected object +/// when it is neither. fn target_node_sorting_everything(app: &VectorcraftApp) -> Option { let st = app.session.active()?; - let traceable = |n: &&Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); + let traceable = |n: &Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); + let source = |id: NodeId| { + st.doc + .parent_of(id) + .and_then(|g| st.doc.node(g)) + .is_some_and(|g| is_trace(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id)) + }; st.selection .in_paint_order(&st.doc) .into_iter() - .find_map(|id| st.doc.node(id).filter(traceable).cloned()) - .or_else(|| first_selected(app).map(|n| (*n).clone())) + .filter(|id| !source(*id)) + .find_map(|id| st.doc.node(id).filter(|n| traceable(n)).cloned()) + .or_else(|| first_selected(app).filter(|n| !traceable(n)).map(|n| (*n).clone())) } /// [`Target`] from [`target_node_sorting_everything`] and a scan of the whole selection for Image @@ -1383,6 +1391,8 @@ fn lookup_fixture() -> (VectorcraftApp, std::collections::HashMap<&'static str, ids.insert("other", doc.insert(Some(second), usize::MAX, other).unwrap()); let other_trace = doc.reid(&trace); ids.insert("other trace", doc.insert(Some(second), 0, other_trace).unwrap()); + let added = doc.reid(&image); + ids.insert("trace added", doc.insert(Some(trace.id), usize::MAX, added).unwrap()); st.revision += 1; (app, ids) } @@ -1406,6 +1416,9 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { &["trace", "trace image"], &["trace image", "trace"], &["rect", "trace image"], + &["trace image"], + &["trace image", "rect"], + &["trace image", "front"], &["clip"], &["rect", "clipped"], &["outer"], @@ -1439,6 +1452,12 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { } assert!(objects.len() >= 8, "the cases reach many different objects: {objects:?}"); + // The source image with a second image of the same tracing: the panel targets the second image. + for sel in [[ids["trace image"], ids["trace added"]], [ids["trace added"], ids["trace image"]]] { + select_as_is(&mut app, &sel); + assert_eq!(target(&mut app).object.map(|o| o.1), Some(ids["trace added"]), "{sel:?}"); + } + // An edit and Undo. app.run("select.set", json!({"ids": [ids["rect"].0, ids["trace"].0]})).unwrap(); let before = target(&mut app); diff --git a/docs/gaps.md b/docs/gaps.md index 671283d648..f17b874b92 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -865,6 +865,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms. Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a document's `fullName`, `path` and `saved`, and close it with `Document.close`. + Scripts also have each document's linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` + and `RasterItem`), and trace them with `trace()`, which gives the Image Trace object as a `PluginItem` with its + `TracingObject` and `TracingOptions`; the tracing options VectorCraft has no setting for, rasterizing and capturing + images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and diff --git a/docs/mcp.md b/docs/mcp.md index dfae0a1c0f..7d104f840e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2746,8 +2746,8 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a File object's `length`, `hidden` or `readonly` counts too, on any object that may be a File object; only - `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out, and - nothing is left out in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a + `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out; a + document's `saveAs` or `exportFile` counts too, and nothing is left out in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a word or as a string literal in brackets, read, call or assign a property in brackets (a `[` after a value, not an array literal) when the brackets hold anything but one number or string literal (`o[k]`, `this['ev' + 'al'](s)`, `this[('eval')](s)`, `this[0, 'eval'](s)`, `o[a[0]]`, or a preprocessor line inside the brackets) or the `[` opens @@ -2951,10 +2951,14 @@ checks that read a target descriptor also throw `ReferenceError` for an uninitia The function returned as `Proxy.revocable(...).revoke` has an own empty-string `name` and a `length` of zero; both properties are nonwritable, nonenumerable and configurable. Its first call clears the revoker's reference to the proxy. Later calls return `undefined` without revoking another object. A -`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there +`.jsx` file and a `source` string run as scripts read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there `yield` is a name like any other. A `.js` file `.jsx` file and a `source` string read ES5.1 when run as scripts. With `module: true`, they run as modules and -accept the ECMAScript 2015 forms listed here. A `.js` file +accept the ECMAScript 2015 forms listed here. A +`.js` file also has `Promise` (described below), and so does a `.jsx` file or a `source` string run with +`module: true`; a `.jsx` file and a `source` string run as scripts do not, except that a named engine +(`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later run, as it keeps +its globals. A `.js` file also reads two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)`), which give `undefined` and skip the rest of the chain when the value before `?.` is `undefined` or `null`, and `??`, which evaluates its right side only when its left side is `undefined` or `null`. Mixing `??` with `&&` @@ -3118,7 +3122,8 @@ through `$`: 100), `blendingMode` (the object's own blend mode as a `BlendModes` value such as `"BlendModes.MULTIPLY"` (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds, widened to take in the direction points of every path in the object; in a document in the back, type + visible bounds with the anchors and Bézier handles of the object's paths, and of the shown paths in its groups and + compound paths; a clip group's come from its clipping path; in a document in the back, type not measured yet is measured first, as the switch to that document would measure it; a valid `position`, `left`, `top`, `width` or `height` equal to the value an object that holds no type, symbol instance or placed document already has is not applied, and its document stays in the back), `editable` (false for an @@ -3134,7 +3139,12 @@ through `$`: object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The one exception is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the - document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. An object of + document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. Moving a tracing's visible, + unlocked source image (`TracingObject.sourceArt`) out of its tracing throws `a tracing's source image cannot leave + its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating + an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before + the document changes, as renaming such a group does. `move`, `remove()` and `zOrder` throw the same error, with + nothing changed, when they would leave an image at the bottom of such a group. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or @@ -3156,9 +3166,9 @@ through `$`: as an empty group or that compound path, reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws - `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that - holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a - `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `BlendModes`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, + `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. When a placed image is embedded, an + object a script holds for it is stale, and the next read gives a new `RasterItem` object. The + enumerations `ElementPlacement`, `ZOrderMethod`, `BlendModes`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. `pageItems` lists the art topmost first, as the example on @@ -3244,7 +3254,7 @@ through `$`: and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/), with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to - 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and + 776.19; 100 writes one pixel per point whatever the raster effects resolution) for PNG24 and JPEG, `matteColor` (PNG24 and JPEG; only white, an `RGBColor` of 255, 255, 255, is accepted, and another color is an error), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with @@ -3307,6 +3317,74 @@ through `$`: show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that `saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name (`saveAs: …`). +- `Document.placedItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/) lists the document's linked + images and `Document.rasterItems` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/) its embedded ones, + topmost first as `pageItems` lists them, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()` + gives a `PlacedItem` with no file; assigning a `File` to its `file` runs `file.place` with `link: true`, and every + other member of it throws `PlacedItem.file is required` until then. A `PlacedItem` + (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/) has `file`, `relink(file)` (`links.relink`), `embed()` + (`links.embed`), `matrix` and `boundingBox`. A `RasterItem` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/) + has `bitsPerChannel`, `channels`, `imageColorSpace` and `transparent`, read from the header of its encoded pixels, + and `colorizedGrayscale`, `embedded`, `file`, `status`, `matrix` and `boundingBox`. The enumeration values are + strings such as `"ImageColorSpace.Grayscale"` and `"RasterLinkState.NODATA"` + (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). VectorCraft's own rules: `file` is assigned + once, on a `placedItems.add()` result, and is read-only after (`PlacedItem.file is read-only: use relink`). A file + to place or relink must be a `File` the script may read, checked as `app.open` checks its file, of at most + 256 MiB, holding an image; its size is read before its contents, and anything else throws an error with nothing + changed (`Script file access denied` names no path). Reading `file` of an image whose file the script may not read + throws `Script file access denied`. After `embed()` the object is stale and `rasterItems` has the image under the + same id; an image whose file is missing throws `Linked image is missing` and stays linked. `RasterItem.file` is + `null`, `embedded` is `true` and takes only `true`, and `status` is `RasterLinkState.NODATA`. `transparent` is true + for an image with an alpha channel or a transparent palette entry. `matrix` is a record of `mValueA` to `mValueTY` + that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning + `matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of + the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point + a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete + objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the + item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()` + result without a file throws `PlacedItem.file is required` whatever the value, and assigning `file` to one checks + the file and places the image. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a + file is dropped at the end of the run. `contentVariable` works as the variables paragraph below describes, and + `colorants`, `colorize` and `overprint` are not available yet. +- `PlacedItem.trace()` and `RasterItem.trace()` trace the image with `imageTrace.make` and the Default preset and + return the Image Trace object as a `PluginItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/), whose + `isTracing` is `true` and whose `tracing` is its `TracingObject` + (https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/). A `TracingObject` has `sourceArt` (the traced image), + `pathCount`, `anchorCount`, `usedColorCount`, `imageResolution`, `tracingOptions`, `parent`, `expandTracing()` + (`imageTrace.expand`, which returns the expanded group) and `releaseTracing()` (`imageTrace.release`, which returns + the image). `TracingOptions` (https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/) has `tracingMode`, + `threshold`, `maxColors`, `palette`, `fills`, `strokes`, `ignoreWhite`, `minArea`, `viewRaster`, `viewVector`, + `preset`, `parent`, `loadFromPreset(name)` and `storeToPreset(name)`, and the enumerations `TracingModeType`, + `ViewRasterType` and `ViewVectorType` hold strings such as `"TracingModeType.TRACINGMODECOLOR"`. VectorCraft's own + rules: `trace()` returns once the trace is made. It throws `The image is the source art of a tracing` on an image an + Image Trace object holds, and `Linked image is missing` on a linked image whose file is missing. `pathCount` does not + count the seam fills of an Abutting trace, `usedColorCount` counts the different fill and stroke paints, and + `imageResolution` is the image's pixels per inch as placed, an error for an image placed at different resolutions + across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the + source image and the view, and a value the tracing already has runs no command. Assigning `viewRaster` or + `viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject` + and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. Tracing again throws + `Cannot retrace a tracing containing 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 + `Cannot release a tracing containing added artwork` in the same case. When no object was added, both throw + `Cannot edit page item `, with nothing changed, when an object the trace made is locked. `imageTrace.make` records the objects it made in + the tracing's `trace` settings as `made`, ranges of ids `[[first, last], ...]`, and a copy of the tracing records + their copies. A tracing saved without `made` is checked only for objects added in the same run. `threshold` takes a whole + number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest + image the tracer reads; `fills` and `strokes` cannot both be `false`; `palette` is `""` (automatic), `"Limited"`, + `"Full Tone"` or `"Document Library"`; `viewRaster` and `viewVector` take only the pairs that match an Image Trace + view. A value of the wrong type throws a `TypeError`, a number out of range a `RangeError`, and nothing changes. + `expandTracing(true)` throws `TracingObject.expandTracing(true) is not implemented` with nothing changed. A preset + name is a string of at most 256 bytes without `/`, `\`, `:` or control characters. `storeToPreset` returns `false` + for a built-in preset name and `Custom`, and throws for any other name, since a script cannot run + `imageTrace.presets.save`. A tracing that was expanded, released, deleted, traced again by a command, or whose + source image was deleted throws `Stale page item`. A script gets the source image from `sourceArt`, and `pageItems`, + `placedItems` and `rasterItems` do not list it. Assigning a different `name` to a `PluginItem` throws + `The name of a tracing cannot be changed`, and assigning `Image Trace` as the `name` of a group whose first object + is an image throws `Only Image Trace can make a tracing`. `areaCount`, `cornerAngle`, `livePaintOutput`, + `maxStrokeWeight`, `minStrokeLength`, `outputToSwatches`, `pathFitting`, `preprocessBlur`, `resample` and + `resampleResolution` throw an error that says they are not implemented. With a script running, `imageTrace.make` + stops at the run's stop request and changes nothing. - `Document.print(options?)` runs `file.print` on the document, with the options a script assigned over the document's print settings, or over the preset's when `printPreset` is assigned. The document's print settings stay as they are, and `print` adds no undo step @@ -3731,6 +3809,19 @@ has them only when a `.js` script started it, and then a later `.jsx` run in it In such a `.jsx` run, `Object.prototype.toString` gives the ES5.1 result, `[object Object]` or another class name, and does not read `Symbol.toStringTag`. +A `.js` script, and a `.jsx` file or a `source` string run with `module: true`, also read async functions and `await` as ECMA-262 2017 section 25.5 defines them +(https://262.ecma-international.org/8.0/#sec-async-function-objects): `async function` declarations and expressions, +async arrow functions and async methods in object literals. A call returns a `Promise` that the function's `return` +resolves and an uncaught exception rejects. `await` suspends the function until its operand settles, and the function +goes on in a promise job with the value, or with the rejection thrown at the `await`, so `try`, `catch` and `finally` +work around it. Async functions cannot be called with `new` and have no `prototype` property. `AsyncFunction` is +reached through `Object.getPrototypeOf(async function () {}).constructor` and is not a global. In script code +outside an async function `await` is an ordinary name; module code does not accept `await` as a name. In a `.jsx` +file or a `source` string run as a script, `async` and `await` are ordinary names and an async function is a syntax +error. These are VectorCraft's own rules: each time a function resumes +counts as a job and takes 1 unit of fuel, and a function still waiting when no job is left stays suspended, and the +run ends. + Before any of the script runs, its preprocessor lines are read. The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/ describes `$.evalFile`, `$.fileName` diff --git a/docs/roadmap.md b/docs/roadmap.md index 8c4897174b..e3703999b1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -209,7 +209,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; the rest of the script document model (layers, artboards, text lines, gradient stops and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; the rest of the script document model (layers, artboards, text lines, gradient stops and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 543a6f8361..e9e87a2976 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1114,6 +1114,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. + - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, 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 raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, 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. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, its area and length are read-only, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked or is on a locked artboard. The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. @@ -1207,6 +1209,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - A realm made with `Options::es2015` also has `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18, https://262.ecma-international.org/6.0/#sec-object.setprototypeof), which returns `o` with `proto` as its prototype. `undefined` or `null` for `o`, a `proto` that is neither an object nor `null`, a non-extensible object given a different prototype, and a prototype whose chain leads back to the object are `TypeError`s; any other primitive `o` is returned unchanged. `Object.prototype` keeps its `null` prototype, as later editions give it (https://262.ecma-international.org/11.0/#sec-immutable-prototype-exotic-objects). For a proxy it calls the handler's `setPrototypeOf` trap, or sets the target's prototype when the handler has none, and a `false` result, a revoked proxy and a trap that breaks the invariant of section 9.5.2 are `TypeError`s. When the trap returns `true`, the call returns the proxy, and the proxy's prototype is whatever the trap left, which may be unchanged for an extensible target. It uses the same [[SetPrototypeOf]] as `Reflect.setPrototypeOf`, so the cycle check stops at a proxy in the chain and each prototype it passes takes fuel. A realm made without the option has no `Object.setPrototypeOf`. Tests: `crates/js/src/es2015_object_tests.rs`. - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,285 of 1,289 runs of 669 tests pass. The 4 others expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. In script code `await` is an identifier outside async functions, and module code rejects it as one; `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file and for any run with `module: true`; `.jsx` scripts and `source` strings run as scripts do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 009256ccd4..9bc4469ae4 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -426,6 +426,9 @@ pub fn describe(runs: &[Run]) -> String { /// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`]. pub fn check() -> Result, String> { + // The shared gate runs only the shards that test a crate a pull request reaches, by these + // lines, so a mismatch fails every shard instead of one test that selection may skip. + workflow_members(include_str!("../../.github/workflows/ci.yml"))?; let members = members(&crate::metadata()?)?; let shards = assign(GROUPS, &members)?; let workspace = tree_features(&tree(&["--workspace".to_owned()])?, &members); @@ -451,6 +454,39 @@ pub fn check() -> Result, String> { Ok(shards) } +/// The lines of the `shard-members: |` block in `workflow`, trimmed. +fn shard_members(workflow: &str) -> Vec<&str> { + let mut lines = workflow.lines().skip_while(|l| l.trim() != "shard-members: |"); + let Some(key) = lines.next() else { return Vec::new() }; + let indent = |l: &str| l.len() - l.trim_start().len(); + lines.take_while(|l| !l.trim().is_empty() && indent(l) > indent(key)).map(str::trim).collect() +} + +/// Checks that `workflow`'s `shard-members` block names each shard's crates as [`GROUPS`] does. +fn workflow_members(workflow: &str) -> Result<(), String> { + let expected: Vec = GROUPS + .iter() + .map(|g| match g { + Group::Part(split, _) => split.crates.join(" "), + // The selection names each crate on one line only, so a shard that runs a crate's + // integration tests leaves it off its line and relies on a crate there that + // depends on it (checked in the tests). + Group::Targets(lists) => { + lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::>().join(" ") + } + Group::Rest => "(rest)".to_owned(), + Group::Checks => "(always)".to_owned(), + }) + .collect(); + let found = shard_members(workflow); + if found != expected { + return Err(format!( + "shard-members in .github/workflows/ci.yml does not match xtask/src/shards.rs › GROUPS:\n found: {found:?}\n expected: {expected:?}" + )); + } + Ok(()) +} + /// `cargo xtask shards`: prints each shard's crates after [`check`], and returns the shards. pub fn run() -> Result, String> { let shards = check()?; @@ -834,32 +870,10 @@ geom v0.1.0 (/w/geom)| ); } - /// The lines of the `shard-members: |` block in `workflow`, trimmed. - fn shard_members(workflow: &str) -> Vec<&str> { - let mut lines = workflow.lines().skip_while(|l| l.trim() != "shard-members: |"); - let Some(key) = lines.next() else { return Vec::new() }; - let indent = |l: &str| l.len() - l.trim_start().len(); - lines.take_while(|l| !l.trim().is_empty() && indent(l) > indent(key)).map(str::trim).collect() - } - #[test] fn ci_names_the_crates_of_every_shard_for_test_selection() { - // The shared gate runs only the shards that test a crate a pull request reaches, by these lines. - let expected: Vec = GROUPS - .iter() - .map(|g| match g { - Group::Part(split, _) => split.crates.join(" "), - // The selection names each crate on one line only, so a shard that runs a crate's - // integration tests leaves it off its line and relies on a crate there that - // depends on it (checked below). - Group::Targets(lists) => { - lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::>().join(" ") - } - Group::Rest => "(rest)".to_owned(), - Group::Checks => "(always)".to_owned(), - }) - .collect(); - assert_eq!(shard_members(include_str!("../../.github/workflows/ci.yml")), expected, "shard-members in .github/workflows/ci.yml"); + assert_eq!(workflow_members(include_str!("../../.github/workflows/ci.yml")), Ok(())); + assert!(workflow_members(" shard-members: |\n a b\n (rest)\n next: 1\n").is_err()); let meta = crate::metadata().unwrap(); let deps: BTreeMap<&str, Vec<&str>> = meta["packages"] .as_array()