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 d2dc185222..1ad17361af 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -964,6 +964,10 @@ pub use retype::{RetypeFound, RetypeRun, RetypeSearch}; /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; +/// Whether an object is an Image Trace object, the source image of one, or the seam fills group in +/// one. +pub(crate) use buildcmds::{TRACE_NAME, is_seam_fills, is_trace_group, is_trace_source}; + /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; 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 3c2bbe8d29..4e50da3b48 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -97,10 +97,12 @@ use vectorcraft_js::{ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; +mod images; mod print; mod save_open; mod tags; mod text; +mod tracing; mod variables; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; @@ -127,6 +129,10 @@ pub(crate) use paths::POINT_LOOKS; pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. pub const STALE_ITEM: &str = "Stale page item"; +/// The error for a new name given to a `PluginItem`. +const TRACING_NAME: &str = "The name of a tracing cannot be changed"; +/// The error for the tracing's name given to a group that holds an image first. +const NOT_A_TRACING: &str = "Only Image Trace can make a tracing"; /// The error for a document that was closed, or that came from an earlier run. pub const STALE_DOCUMENT: &str = "Stale document"; /// The error of `index` and `getByName` when nothing matches. @@ -158,6 +164,7 @@ const ITEM_CLASSES: &[&str] = &[ "RepeatItem", "PlacedDocumentItem", "IntertwineItem", + "PluginItem", ]; /// `app.coordinateSystem`. @@ -217,6 +224,10 @@ pub(super) struct State { preset_bytes: Cell, 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>, } @@ -443,7 +454,7 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" | "PathItem" | "TextFrame" => { + "PageItem" | "PathItem" | "TextFrame" | "PlacedItem" | "RasterItem" => { item_of(&h, arg(&a, 0))?; } "PathPoint" => { @@ -583,16 +594,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 }) @@ -603,6 +623,7 @@ fn typename(n: &crate::doc::Node) -> Option<&'static str> { Some(match &n.kind { NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None, NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem", + NodeKind::Group { .. } if crate::cmd::is_trace_group(n) => "PluginItem", NodeKind::Group { .. } => "GroupItem", NodeKind::Path { .. } => "PathItem", NodeKind::Compound { .. } => "CompoundPathItem", @@ -626,6 +647,11 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { + Some("PlacedItem") => images::bound_ref(h, st, id).unwrap_or_else(|| host_ref("PlacedItem", &node_handle(h, st, id))), + Some("PluginItem") => { + tracing::remember_source(h, st.uid, n); + host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id))) + } Some(t) => host_ref(t, &node_handle(h, st, id)), None => host_ref("Layer", &node_handle(h, st, id)), }, @@ -649,7 +675,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); } } } @@ -686,9 +715,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. @@ -2307,6 +2338,28 @@ fn item_set_name(h: &Host, a: &[Data]) -> Answer { if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } + // An Image Trace object is known by its name, so renaming one would end the tracing, and giving + // an ordinary group that holds an image first the tracing's name would make it one. + let item = this_item(h, a)?; + let refused = with_doc(h, item.doc, |_, st| { + st.doc.node(item.id).and_then(|n| { + let tracing = crate::cmd::is_trace_group(n); + let would_trace = !tracing + && name == crate::cmd::TRACE_NAME + && matches!(n.kind, crate::doc::NodeKind::Group { clip: false, .. }) + && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, crate::doc::NodeKind::Image(_)))); + if tracing && n.name.as_deref() != Some(&**name) { + Some(TRACING_NAME) + } else if would_trace { + Some(NOT_A_TRACING) + } else { + None + } + }) + }); + if let Some(msg) = refused { + return Err(HostError::Error(msg.into())); + } set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name})) } @@ -2502,24 +2555,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 { @@ -2688,6 +2743,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } + // An image left first in an ordinary group named as a tracing would make that group one. + if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } // A compound path whose last path this is stays, empty, as it does after `move`. edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; Ok(Data::Undefined) @@ -2741,14 +2800,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())); } @@ -2788,17 +2853,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, @@ -2814,7 +2926,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) { @@ -2909,22 +3028,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) } @@ -3029,7 +3176,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { text::install_enums(realm)?; - for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -3151,6 +3298,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( @@ -3249,7 +3397,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)); @@ -3260,6 +3409,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/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 151dd11e25..60d38330a9 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(); @@ -1434,7 +1474,7 @@ fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() { } #[test] -fn a_held_image_stays_the_same_object_when_it_is_embedded() { +fn a_held_image_is_stale_when_it_is_embedded() { let dir = super::links::Folder::new("dom-embed"); let photo = dir.file("photo.png"); super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0])); @@ -1444,11 +1484,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_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 6b8965dd7f..2bf79b10c0 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. ( "", @@ -455,11 +500,11 @@ const INSIDE: &[(&str, &str)] = &[ ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types -/// other than `PathItem`, the color classes, and the save and export option classes. +/// other than `PathItem`, `PlacedItem` and `RasterItem`, the color classes and the save and export +/// option classes. const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \ - IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \ - SymbolItem cmykColor EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \ - PDFSaveOptions"; + IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem \ + cmykColor EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. 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 07017ba921..0639d52d25 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -395,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. 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 2c0be5123c..cebfe4b189 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 @@ -3122,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 @@ -3138,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 @@ -3160,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 @@ -3248,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 @@ -3311,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 diff --git a/docs/roadmap.md b/docs/roadmap.md index f669559fd2..f2e6058229 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, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines 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`), and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines 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 1403634d48..144759bf00 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, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path 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`.