mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 20:43:18 -05:00
Scripts: PlacedItem.trace and RasterItem.trace make an Image Trace object with its tracing options
`PlacedItem.trace()` and `RasterItem.trace()` run `imageTrace.make` with the Default preset and return the Image Trace object as a `PluginItem`. Its `tracing` is a `TracingObject` with the source image, the path, anchor and color counts, the image's resolution, `expandTracing()`, `releaseTracing()` and a `TracingOptions` object. Assigning an option or loading a preset traces the image again, keeping its source image and view; a value the tracing already has runs no command. Option values are checked for type and range before any trace, and nothing changes when one is refused. Options with no VectorCraft setting and `expandTracing(true)` throw. `storeToPreset` returns `false` for a built-in preset name or `Custom` and throws for any other name. A tracing that was expanded, released, deleted or traced again by a command is stale. The source image is reached through `sourceArt` and is not listed in `pageItems`, `placedItems` or `rasterItems`, and the name of a tracing cannot be changed from a script. With a script running, `imageTrace.make` stops at the run's stop request. Setting `File.hidden` stores the new path with `set_path`, since the path is held in the object's class on this branch. Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
1 parent
f80f582fc8
commit
022d0ce7e8
13 files changed
+1404
-21
No files matched your search
@@ -921,6 +921,10 @@ pub use buildcmds::{TraceRun, Traced, image_trace_target};
|
||||
/// 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::{is_seam_fills, is_trace_group, is_trace_source};
|
||||
|
||||
/// The shapes a group selected alone gives the Pathfinder panel.
|
||||
pub use pathops::shape_count;
|
||||
|
||||
|
||||
@@ -41,10 +41,10 @@ pub use live_paint::live_paint_gaps;
|
||||
pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation};
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_copy_region, sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
pub use trace::{
|
||||
TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target,
|
||||
};
|
||||
pub(crate) use trace::{TracePresetChanges, is_seam_fills, is_trace_group, is_trace_source};
|
||||
use trace::{
|
||||
trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view,
|
||||
};
|
||||
|
||||
@@ -17,12 +17,17 @@ thread_local! {
|
||||
|
||||
// ---------- Image Trace ----------
|
||||
|
||||
fn is_trace_group(n: &Node) -> bool {
|
||||
pub(crate) fn is_trace_group(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& n.name.as_deref() == Some(TRACE_NAME)
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// Whether object `id` of `d` is the source image an Image Trace object keeps as its first child.
|
||||
pub(crate) fn is_trace_source(d: &Document, id: NodeId) -> bool {
|
||||
d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id))
|
||||
}
|
||||
|
||||
/// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]).
|
||||
const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
|
||||
@@ -32,7 +37,7 @@ const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
/// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made
|
||||
/// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one
|
||||
/// of stroked paths without fills. (Auto Grouping groups hold filled paths.)
|
||||
fn is_seam_fills(n: &Node) -> bool {
|
||||
pub(crate) fn is_seam_fills(n: &Node) -> bool {
|
||||
let path = |m: &Arc<Node>| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
let stroke_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None;
|
||||
let fill_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None;
|
||||
@@ -774,8 +779,12 @@ pub fn image_trace_target(s: &Session, p: &Value) -> Result<NodeId> {
|
||||
fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObject>)> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// The source image an Image Trace object keeps is traced through that object, so it is never
|
||||
// the object traced, and naming only such images is an error.
|
||||
let source = |r: &NodeId| is_trace_source(d, *r);
|
||||
roots
|
||||
.iter()
|
||||
.filter(|r| !source(r))
|
||||
.find_map(|r| {
|
||||
let n = d.node(*r)?;
|
||||
match &n.kind {
|
||||
@@ -787,7 +796,10 @@ fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObj
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))
|
||||
.ok_or_else(|| match roots.iter().find(|r| source(r)) {
|
||||
Some(r) => bad(c, format!("object {} is the source image of an Image Trace object: trace that object", r.0)),
|
||||
None => bad(c, "select an image (or an Image Trace group)"),
|
||||
})
|
||||
}
|
||||
|
||||
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
|
||||
@@ -1076,10 +1088,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let recorded = serde_json::to_value(&q.params).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
s.note_journal("savedPreset", recorded);
|
||||
}
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now. A script's trace
|
||||
// stops when the script is asked to stop.
|
||||
let stop = s.script_in_run.then(|| s.script_interrupt());
|
||||
let Traced { raster, res, seams: seam_fills, .. } = match s.trace_hand_off.take() {
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| true)?,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| stop.as_ref().is_none_or(|i| !i.is_set()))?,
|
||||
};
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let mut warnings = keep_warnings(&trace, &res);
|
||||
|
||||
@@ -40,11 +40,14 @@ use crate::{DocState, Document, NodeId, NodeKind, Session};
|
||||
|
||||
mod images;
|
||||
mod save_open;
|
||||
mod tracing;
|
||||
|
||||
/// The error for a member read or called with no document open.
|
||||
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 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.
|
||||
@@ -74,6 +77,7 @@ const ITEM_CLASSES: &[&str] = &[
|
||||
"RepeatItem",
|
||||
"PlacedDocumentItem",
|
||||
"IntertwineItem",
|
||||
"PluginItem",
|
||||
];
|
||||
|
||||
/// `app.coordinateSystem`.
|
||||
@@ -100,6 +104,8 @@ pub(super) struct State {
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
/// What the placed and raster items keep ([`images::State`]).
|
||||
images: images::State,
|
||||
/// What the tracings keep ([`tracing::State`]).
|
||||
tracing: tracing::State,
|
||||
}
|
||||
|
||||
impl State {
|
||||
@@ -303,6 +309,7 @@ fn item_of(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
};
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = id.ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
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) != Some(class)) {
|
||||
@@ -316,6 +323,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",
|
||||
@@ -361,7 +369,10 @@ fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
NodeKind::RulerGuide { .. } => {}
|
||||
NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
out.push(n.id);
|
||||
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);
|
||||
}
|
||||
_ => out.push(n.id),
|
||||
}
|
||||
@@ -391,9 +402,11 @@ fn top_items(d: &Document) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `n` and every object inside it are shown and unlocked.
|
||||
/// Whether `n` and every object inside it are shown and unlocked. The source image an Image Trace
|
||||
/// object keeps hidden as its first child is part of that object and is not counted.
|
||||
fn all_editable(n: &crate::doc::Node) -> bool {
|
||||
n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c)))
|
||||
let source = usize::from(crate::cmd::is_trace_group(n));
|
||||
n.visible && !n.locked && n.children().is_none_or(|c| c.iter().skip(source).all(|c| all_editable(c)))
|
||||
}
|
||||
|
||||
/// Whether the object and every layer and group it is in are shown and unlocked.
|
||||
@@ -1336,6 +1349,13 @@ 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.
|
||||
let item = this_item(h, a)?;
|
||||
let tracing =
|
||||
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| crate::cmd::is_trace_group(n) && n.name.as_deref() != Some(&**name)));
|
||||
if tracing {
|
||||
return Err(HostError::Error(TRACING_NAME.into()));
|
||||
}
|
||||
set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name}))
|
||||
}
|
||||
|
||||
@@ -1818,7 +1838,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link`
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(images::ENUMS) {
|
||||
for (name, members) in ENUMS.iter().chain(save_open::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)?;
|
||||
}
|
||||
@@ -1945,8 +1965,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
.map(|m| later(l, "PageItem", m)),
|
||||
);
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !images::CLASSES.contains(c)).map(|c| class(c, Some("PageItem"), Vec::new(), None)));
|
||||
let own = |c: &&&str| images::CLASSES.contains(c) || tracing::CLASSES.contains(c);
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| class(c, Some("PageItem"), Vec::new(), None)));
|
||||
classes.extend(images::classes(l));
|
||||
tracing::add_trace(&mut classes, l);
|
||||
classes.extend(tracing::classes(l));
|
||||
classes.extend(save_open::classes(l));
|
||||
classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None));
|
||||
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])
|
||||
|
||||
@@ -649,7 +649,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("matrix", property(l, placed_matrix, placed_set_matrix)),
|
||||
("boundingBox", get(l, placed_box)),
|
||||
]);
|
||||
placed.extend(["contentVariable", "trace"].into_iter().map(|m| later(l, "PlacedItem", m)));
|
||||
placed.push(later(l, "PlacedItem", "contentVariable"));
|
||||
let mut raster = named(vec![
|
||||
("bitsPerChannel", get(l, raster_bits)),
|
||||
("channels", get(l, raster_channels)),
|
||||
@@ -662,7 +662,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("transparent", get(l, raster_transparent)),
|
||||
("boundingBox", get(l, raster_box)),
|
||||
]);
|
||||
raster.extend(["colorants", "colorize", "contentVariable", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m)));
|
||||
raster.extend(["colorants", "colorize", "contentVariable", "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))),
|
||||
|
||||
@@ -0,0 +1,741 @@
|
||||
//! Tracing in the script object model: `PlacedItem.trace()` and `RasterItem.trace()`, the
|
||||
//! `PluginItem` an Image Trace object is, its `TracingObject` and its `TracingOptions`, as the help
|
||||
//! pages <https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/> describe them.
|
||||
//!
|
||||
//! An Image Trace object is a group that holds its source image, hidden, as its first object.
|
||||
//! Tracing runs `imageTrace.make`, expanding `imageTrace.expand`, releasing `imageTrace.release`
|
||||
//! and a change of view `imageTrace.setView`, so each joins the run's transaction and its work
|
||||
//! counts against the run's limits.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `trace()` returns once the trace is made, so the counts can be read at once. It traces with
|
||||
//! the Default preset.
|
||||
//! - The traced image stays the same object: `sourceArt` gives it, and `releaseTracing()` gives it
|
||||
//! back. `trace()` on an image that is the source of a tracing throws [`ALREADY_TRACED`], and on
|
||||
//! a linked image whose file is missing throws `Linked image is missing`.
|
||||
//! - `pathCount` counts the traced paths, without the seam fills an Abutting trace adds,
|
||||
//! `anchorCount` their anchor points and `usedColorCount` the different paints they are filled
|
||||
//! and stroked with, as the tracing is when they are read. `areaCount` throws. `imageResolution`
|
||||
//! is the source image's pixels per inch as it is placed; an image placed at a different
|
||||
//! resolution across and down has none.
|
||||
//! - Assigning an option, or `loadFromPreset(name)`, traces again unless the options are already
|
||||
//! so. Tracing again makes a new object: the `PluginItem`, its `TracingObject` and its
|
||||
//! `TracingOptions` follow it. A tracing that another command traced again, expanded or
|
||||
//! released, or whose source image was deleted, is stale.
|
||||
//! - `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::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts};
|
||||
|
||||
use super::{
|
||||
Answer, Host, Item, Link, STALE_ITEM, arg, boolean, class, command, command_value, edit_item, find_doc, float, get, id_of, item_of, item_ref,
|
||||
method, named, num, number, on_doc, property, text, 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 options that trace with neither fills nor strokes.
|
||||
pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes";
|
||||
/// The error of `expandTracing(true)`.
|
||||
pub const VIEWED_EXPAND: &str = "TracingObject.expandTracing(true) is not implemented";
|
||||
/// The longest preset name `loadFromPreset` and `storeToPreset` take, in bytes.
|
||||
pub const MAX_PRESET_NAME: usize = 256;
|
||||
/// The most times one run traces a tracing again through its options.
|
||||
pub const MAX_RETRACES: usize = 10_000;
|
||||
/// The largest `minArea`: the most pixels the tracer traces ([`vectorcraft_trace::MAX_PIXELS`]).
|
||||
pub const MAX_MIN_AREA: u64 = vectorcraft_trace::MAX_PIXELS;
|
||||
|
||||
/// The enumerations the members here give values of, as the help page
|
||||
/// <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/> lists them.
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("TracingModeType", &["TRACINGMODEBLACKANDWHITE", "TRACINGMODECOLOR", "TRACINGMODEGRAY"]),
|
||||
(
|
||||
"ViewRasterType",
|
||||
&["TRACINGVIEWRASTERADJUSTEDIMAGE", "TRACINGVIEWRASTERNOIMAGE", "TRACINGVIEWRASTERORIGINALIMAGE", "TRACINGVIEWRASTERTRANSPARENTIMAGE"],
|
||||
),
|
||||
(
|
||||
"ViewVectorType",
|
||||
&["TRACINGVIEWVECTORNOTRACINGRESULT", "TRACINGVIEWVECTOROUTLINES", "TRACINGVIEWVECTOROUTLINESWITHTRACING", "TRACINGVIEWVECTORTRACINGRESULT"],
|
||||
),
|
||||
];
|
||||
|
||||
/// The classes this module defines.
|
||||
pub(super) const CLASSES: &[&str] = &["PluginItem"];
|
||||
|
||||
/// Each Image Trace view with the `viewRaster` and `viewVector` that give it.
|
||||
const VIEWS: &[(TraceView, &str, &str)] = &[
|
||||
(TraceView::Result, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"),
|
||||
(TraceView::ResultWithOutlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINESWITHTRACING"),
|
||||
(TraceView::Outlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"),
|
||||
(TraceView::OutlinesWithSource, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"),
|
||||
(TraceView::Source, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTORNOTRACINGRESULT"),
|
||||
];
|
||||
|
||||
/// Each `tracingMode` with its Image Trace mode.
|
||||
const MODES: &[(&str, &str)] = &[
|
||||
("TracingModeType.TRACINGMODEBLACKANDWHITE", "blackAndWhite"),
|
||||
("TracingModeType.TRACINGMODEGRAY", "grayscale"),
|
||||
("TracingModeType.TRACINGMODECOLOR", "color"),
|
||||
];
|
||||
|
||||
/// Each `palette` name with its Image Trace palette.
|
||||
const PALETTES: &[(&str, &str)] = &[("", "automatic"), ("Limited", "limited"), ("Full Tone", "fullTone"), ("Document Library", "documentLibrary")];
|
||||
|
||||
/// The options with no VectorCraft setting.
|
||||
const NOT_IMPLEMENTED: &[&str] = &[
|
||||
"cornerAngle",
|
||||
"livePaintOutput",
|
||||
"maxStrokeWeight",
|
||||
"minStrokeLength",
|
||||
"outputToSwatches",
|
||||
"pathFitting",
|
||||
"preprocessBlur",
|
||||
"resample",
|
||||
"resampleResolution",
|
||||
];
|
||||
|
||||
/// What a run keeps for tracings: for each document uid and Image Trace object a script traced
|
||||
/// again through its options, the id of the object that replaced it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
next: RefCell<HashMap<(u64, u64), u64>>,
|
||||
}
|
||||
|
||||
/// `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 Image Trace object that replaced it when this run
|
||||
/// traced it again, else `id`.
|
||||
pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId {
|
||||
let held = h.session.borrow().documents().iter().find(|d| d.uid == uid).is_some_and(|d| d.doc.node(id).is_some());
|
||||
if held {
|
||||
return id;
|
||||
}
|
||||
h.dom.tracing.next.borrow().get(&(uid, id.0)).map_or(id, |n| NodeId(*n))
|
||||
}
|
||||
|
||||
/// Records that `new` replaced `old` in the document `uid`: every object that led to `old` leads to
|
||||
/// `new` now.
|
||||
fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) {
|
||||
let mut next = h.dom.tracing.next.borrow_mut();
|
||||
for ((u, _), to) in next.iter_mut() {
|
||||
if *u == uid && *to == old.0 {
|
||||
*to = new.0;
|
||||
}
|
||||
}
|
||||
next.insert((uid, old.0), new.0);
|
||||
}
|
||||
|
||||
/// The error of a member with no VectorCraft setting.
|
||||
pub fn not_implemented(class: &str, name: &str) -> String {
|
||||
format!("{class}.{name} is not implemented")
|
||||
}
|
||||
|
||||
fn out_of_range(name: &str, range: &str) -> HostError {
|
||||
HostError::Range(format!("TracingOptions.{name} is out of range: {range}"))
|
||||
}
|
||||
|
||||
fn invalid(name: &str) -> HostError {
|
||||
HostError::Error(format!("TracingOptions.{name} has an invalid value"))
|
||||
}
|
||||
|
||||
fn stale() -> HostError {
|
||||
HostError::Error(STALE_ITEM.into())
|
||||
}
|
||||
|
||||
fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> {
|
||||
match d {
|
||||
Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first id of a command's result `key`: a number or a list of them, read exactly.
|
||||
fn result_id(v: &Value, key: &str) -> Option<NodeId> {
|
||||
match &v[key] {
|
||||
Value::Array(a) => a.first().and_then(Value::as_u64).map(NodeId),
|
||||
n => n.as_u64().map(NodeId),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Image Trace object, its document and the id its handle holds, of the `cls` (`TracingObject`
|
||||
/// or `TracingOptions`) `d` names. It must still be an Image Trace object of its document.
|
||||
fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 4]), 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] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) };
|
||||
let doc = find_doc(h, run, uid).ok_or_else(stale)?;
|
||||
let id = follow(h, doc.uid, id_of(high, low).ok_or_else(stale)?);
|
||||
let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::cmd::is_trace_group));
|
||||
if !live {
|
||||
return Err(stale());
|
||||
}
|
||||
Ok((Item { doc, id }, [run, uid, high, low]))
|
||||
}
|
||||
|
||||
/// The `PluginItem` `this` names, with the handle numbers its `tracing` keeps.
|
||||
fn plugin_of(h: &Host, a: &[Data]) -> Result<(Item, [f64; 4]), 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] => Ok((item, [run, uid, high, low])),
|
||||
_ => Err(HostError::Type("this is not a PluginItem".into())),
|
||||
}
|
||||
}
|
||||
_ => Err(HostError::Type("this is not a PluginItem".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the Image Trace object of `item` with `f`.
|
||||
fn read_group<T>(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) -> Result<T, HostError>) -> Result<T, HostError> {
|
||||
with_doc(h, item.doc, |_, st| match st.doc.node(item.id) {
|
||||
Some(n) => f(st, n),
|
||||
None => Err(stale()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs command `id` with `params` on `item`'s document → the object its result names under `key`.
|
||||
/// The selection stays as it was, with that object in place of `item`.
|
||||
fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result<NodeId, HostError> {
|
||||
let before = with_doc(h, item.doc, |_, st| st.selection.objects.clone());
|
||||
on_doc(h, item.doc.uid, false, |h| {
|
||||
let (_, r) = command_value(h, id, params)?;
|
||||
let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?;
|
||||
let (want, now) = {
|
||||
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()))?;
|
||||
let mut want: Vec<NodeId> = Vec::new();
|
||||
for i in before.iter().map(|i| if *i == item.id { new } else { *i }) {
|
||||
if st.doc.node(i).is_some() && !want.contains(&i) {
|
||||
want.push(i);
|
||||
}
|
||||
}
|
||||
(want, st.selection.objects.clone())
|
||||
};
|
||||
if now != want {
|
||||
if want.is_empty() {
|
||||
command(h, "select.none", &json!({}))?;
|
||||
} else {
|
||||
command(h, "select.set", &json!({"ids": want.iter().map(|i| i.0).collect::<Vec<_>>()}))?;
|
||||
}
|
||||
}
|
||||
Ok(new)
|
||||
})
|
||||
}
|
||||
|
||||
/// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its
|
||||
/// script objects follow the new one.
|
||||
fn retrace(h: &Host, item: Item, mut params: Map<String, Value>) -> Result<(), HostError> {
|
||||
if h.dom.tracing.next.borrow().len() >= MAX_RETRACES {
|
||||
return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times")));
|
||||
}
|
||||
params.insert("id".into(), json!(item.id.0));
|
||||
let new = replace(h, item, "imageTrace.make", &Value::Object(params), "id")?;
|
||||
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 (_, handle) = plugin_of(h, a)?;
|
||||
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,
|
||||
}
|
||||
|
||||
fn anchors_of(n: &Node) -> u64 {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.anchor_count() as u64,
|
||||
_ => n.children().map_or(0, |c| c.iter().map(|m| anchors_of(m)).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.
|
||||
fn counts(g: &Node) -> Counts {
|
||||
let mut c = Counts::default();
|
||||
let mut paints = HashSet::new();
|
||||
let mut todo: Vec<&Arc<Node>> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default();
|
||||
while let Some(n) = todo.pop() {
|
||||
c.visited += 1;
|
||||
if crate::cmd::is_seam_fills(n) {
|
||||
continue;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { clipping: true, .. } => {}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
c.paths += 1;
|
||||
c.anchors += anchors_of(n);
|
||||
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
|
||||
}
|
||||
|
||||
/// Reads the counts of the tracing `this` names with `f`.
|
||||
fn count(h: &Host, a: &[Data], f: fn(&Counts) -> u64) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
let c = read_group(h, item, |_, g| Ok(counts(g)))?;
|
||||
h.charge_call(c.visited)?;
|
||||
Ok(num(float(f(&c))))
|
||||
}
|
||||
|
||||
fn tracing_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, |c| c.paths)
|
||||
}
|
||||
|
||||
fn tracing_anchors(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, |c| c.anchors)
|
||||
}
|
||||
|
||||
fn tracing_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, |c| c.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 (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id)))
|
||||
}
|
||||
|
||||
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.
|
||||
fn tracing_release(h: &Host, a: &[Data]) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
let id = replace(h, item, "imageTrace.release", &json!({"ids": [item.id.0]}), "ids")?;
|
||||
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
|
||||
}
|
||||
|
||||
// ---- TracingOptions ----
|
||||
|
||||
/// The tracing `this` names, the settings it was traced with, its view and its preset's name.
|
||||
fn options_of(h: &Host, a: &[Data]) -> Result<(Item, Map<String, Value>, TraceView, String), HostError> {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingOptions")?;
|
||||
read_group(h, item, |_, g| {
|
||||
let trace = g.extras().trace.as_deref();
|
||||
let params = trace.and_then(|t| t.get("params")).and_then(Value::as_object).cloned();
|
||||
let params = params.ok_or_else(|| HostError::Error("the tracing has no recorded options".into()))?;
|
||||
let preset = trace.and_then(|t| t.get("preset")).and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
Ok((item, params, g.trace_view(), preset))
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the setting `key` of the tracing `this` names with `f`.
|
||||
fn read_option(h: &Host, a: &[Data], key: &str, f: impl FnOnce(&Value) -> Answer) -> Answer {
|
||||
let (_, params, ..) = options_of(h, a)?;
|
||||
f(params.get(key).unwrap_or(&Value::Null))
|
||||
}
|
||||
|
||||
/// Traces again with the setting `key` at `value`, unless it is at that value already.
|
||||
fn write_option(h: &Host, a: &[Data], key: &str, value: Value) -> Answer {
|
||||
let (item, mut params, ..) = options_of(h, a)?;
|
||||
if params.get(key) == Some(&value) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
params.insert(key.into(), value);
|
||||
let on = |k: &str| params.get(k).and_then(Value::as_bool) == Some(true);
|
||||
if !on("fills") && !on("strokes") {
|
||||
return Err(HostError::Error(NEEDS_FILLS_OR_STROKES.into()));
|
||||
}
|
||||
let mut p = Map::new();
|
||||
p.insert("params".into(), Value::Object(params));
|
||||
retrace(h, item, p)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// A whole number from `lo` to `hi` for the option `name`.
|
||||
fn whole_in(d: &Data, name: &str, lo: u64, hi: u64) -> Result<u64, HostError> {
|
||||
let n = number(d, &format!("TracingOptions.{name}"))?;
|
||||
if n.fract() != 0.0 || n < float(lo) || n > float(hi) {
|
||||
return Err(out_of_range(name, &format!("a whole number from {lo} to {hi}")));
|
||||
}
|
||||
whole(n).ok_or_else(|| out_of_range(name, &format!("a whole number from {lo} to {hi}")))
|
||||
}
|
||||
|
||||
fn as_number(v: &Value) -> Answer {
|
||||
v.as_f64().map(num).ok_or_else(|| HostError::Error("the tracing's options are damaged".into()))
|
||||
}
|
||||
|
||||
fn as_bool(v: &Value) -> Answer {
|
||||
v.as_bool().map(Data::Bool).ok_or_else(|| HostError::Error("the tracing's options are damaged".into()))
|
||||
}
|
||||
|
||||
fn options_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "mode", |v| {
|
||||
let mode = v.as_str().unwrap_or_default();
|
||||
match MODES.iter().find(|(_, m)| *m == mode) {
|
||||
Some((name, _)) => Ok(text(*name)),
|
||||
None => Err(HostError::Error("TracingOptions.tracingMode has no value for this tracing's mode".into())),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn options_set_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let mode = match arg(a, 1) {
|
||||
Data::String(s) => MODES.iter().find(|(n, _)| n == s).map(|(_, m)| *m),
|
||||
_ => None,
|
||||
};
|
||||
let mode = mode.ok_or_else(|| HostError::Type("TracingOptions.tracingMode must be a TracingModeType value".into()))?;
|
||||
write_option(h, a, "mode", json!(mode))
|
||||
}
|
||||
|
||||
fn options_threshold(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "threshold", as_number)
|
||||
}
|
||||
|
||||
fn options_set_threshold(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = whole_in(arg(a, 1), "threshold", 0, 255)?;
|
||||
write_option(h, a, "threshold", json!(v))
|
||||
}
|
||||
|
||||
fn options_max_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "colors", as_number)
|
||||
}
|
||||
|
||||
fn options_set_max_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = whole_in(arg(a, 1), "maxColors", 2, 256)?;
|
||||
write_option(h, a, "colors", json!(v))
|
||||
}
|
||||
|
||||
fn options_min_area(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "noise", as_number)
|
||||
}
|
||||
|
||||
fn options_set_min_area(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = whole_in(arg(a, 1), "minArea", 0, MAX_MIN_AREA)?;
|
||||
write_option(h, a, "noise", json!(v))
|
||||
}
|
||||
|
||||
fn options_fills(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "fills", as_bool)
|
||||
}
|
||||
|
||||
fn options_set_fills(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = boolean(arg(a, 1), "TracingOptions.fills")?;
|
||||
write_option(h, a, "fills", json!(v))
|
||||
}
|
||||
|
||||
fn options_strokes(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "strokes", as_bool)
|
||||
}
|
||||
|
||||
fn options_set_strokes(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = boolean(arg(a, 1), "TracingOptions.strokes")?;
|
||||
write_option(h, a, "strokes", json!(v))
|
||||
}
|
||||
|
||||
fn options_ignore_white(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "ignoreWhite", as_bool)
|
||||
}
|
||||
|
||||
fn options_set_ignore_white(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = boolean(arg(a, 1), "TracingOptions.ignoreWhite")?;
|
||||
write_option(h, a, "ignoreWhite", json!(v))
|
||||
}
|
||||
|
||||
fn options_palette(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "palette", |v| {
|
||||
let palette = v.as_str().unwrap_or_default();
|
||||
match PALETTES.iter().find(|(_, p)| *p == palette) {
|
||||
Some((name, _)) => Ok(text(*name)),
|
||||
None => Err(HostError::Error("the tracing's options are damaged".into())),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn options_set_palette(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("TracingOptions.palette must be a string".into())) };
|
||||
let palette = PALETTES.iter().find(|(n, _)| n == name).map(|(_, p)| *p).ok_or_else(|| invalid("palette"))?;
|
||||
write_option(h, a, "palette", json!(palette))
|
||||
}
|
||||
|
||||
/// The view's `viewRaster` (`raster`) or `viewVector`.
|
||||
fn view_part(view: TraceView, raster: bool) -> Answer {
|
||||
let name = if raster { "viewRaster" } else { "viewVector" };
|
||||
VIEWS
|
||||
.iter()
|
||||
.find(|(v, ..)| *v == view)
|
||||
.map(|(_, r, v)| text(if raster { *r } else { *v }))
|
||||
.ok_or_else(|| HostError::Error(format!("TracingOptions.{name} has no value for the Split view")))
|
||||
}
|
||||
|
||||
fn options_view(h: &Host, a: &[Data], raster: bool) -> Answer {
|
||||
let (_, _, view, _) = options_of(h, a)?;
|
||||
view_part(view, raster)
|
||||
}
|
||||
|
||||
/// Shows the view `viewRaster` (`raster`) or `viewVector` makes with the other one as it is.
|
||||
fn options_set_view(h: &Host, a: &[Data], raster: bool) -> Answer {
|
||||
let (name, kind) = if raster { ("viewRaster", "ViewRasterType") } else { ("viewVector", "ViewVectorType") };
|
||||
let given = match arg(a, 1) {
|
||||
Data::String(s) if ENUMS.iter().any(|(e, members)| *e == kind && members.iter().any(|m| *s == format!("{kind}.{m}"))) => s.clone(),
|
||||
_ => return Err(HostError::Type(format!("TracingOptions.{name} must be a {kind} value"))),
|
||||
};
|
||||
let (item, _, view, _) = options_of(h, a)?;
|
||||
let Data::String(other) = view_part(view, !raster)? else { return Err(invalid(name)) };
|
||||
let pair = |r: &str, v: &str| if raster { given == r && other == v } else { other == r && given == v };
|
||||
let (to, ..) = VIEWS.iter().find(|(_, r, v)| pair(r, v)).ok_or_else(|| invalid(name))?;
|
||||
if *to != view {
|
||||
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.
|
||||
fn missing(link: &Link, name: &'static str) -> (String, HostMember) {
|
||||
let message = not_implemented("TracingOptions", name);
|
||||
let l = link.clone();
|
||||
let f: vectorcraft_js::HostFunction = std::rc::Rc::new(move |a: Vec<Data>| {
|
||||
let h = super::current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
tracing_of(&h, arg(&a, 0), "TracingOptions")?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Property { get: f.clone(), set: f })
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
match c.name.as_str() {
|
||||
"PlacedItem" => c.members.push(("trace".into(), method(l, placed_trace))),
|
||||
"RasterItem" => c.members.push(("trace".into(), method(l, raster_trace))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `PluginItem`, after `PageItem`, `TracingObject` and `TracingOptions`.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let plugin = named(vec![("isTracing", get(l, plugin_is_tracing)), ("tracing", get(l, plugin_tracing))]);
|
||||
let tracing = named(vec![
|
||||
("typename", typename_of("TracingObject")),
|
||||
("anchorCount", get(l, tracing_anchors)),
|
||||
("areaCount", get(l, tracing_areas)),
|
||||
("imageResolution", get(l, tracing_resolution)),
|
||||
("parent", get(l, tracing_parent)),
|
||||
("pathCount", get(l, tracing_paths)),
|
||||
("sourceArt", get(l, tracing_source)),
|
||||
("tracingOptions", get(l, tracing_options)),
|
||||
("usedColorCount", get(l, tracing_colors)),
|
||||
("expandTracing", method(l, tracing_expand)),
|
||||
("releaseTracing", method(l, tracing_release)),
|
||||
]);
|
||||
let mut options = named(vec![
|
||||
("typename", typename_of("TracingOptions")),
|
||||
("parent", get(l, options_parent)),
|
||||
("preset", get(l, options_preset)),
|
||||
("tracingMode", property(l, options_mode, options_set_mode)),
|
||||
("threshold", property(l, options_threshold, options_set_threshold)),
|
||||
("fills", property(l, options_fills, options_set_fills)),
|
||||
("strokes", property(l, options_strokes, options_set_strokes)),
|
||||
("maxColors", property(l, options_max_colors, options_set_max_colors)),
|
||||
("palette", property(l, options_palette, options_set_palette)),
|
||||
("ignoreWhite", property(l, options_ignore_white, options_set_ignore_white)),
|
||||
("minArea", property(l, options_min_area, options_set_min_area)),
|
||||
("viewRaster", property(l, options_view_raster, options_set_view_raster)),
|
||||
("viewVector", property(l, options_view_vector, options_set_view_vector)),
|
||||
("loadFromPreset", method(l, options_load)),
|
||||
("storeToPreset", method(l, options_store)),
|
||||
]);
|
||||
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),
|
||||
]
|
||||
}
|
||||
@@ -174,6 +174,7 @@ mod script_dialogs;
|
||||
mod script_dollar;
|
||||
mod script_dom;
|
||||
mod script_dom_images;
|
||||
mod script_dom_tracing;
|
||||
mod script_engines;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
|
||||
@@ -457,8 +457,8 @@ fn members_not_available_yet_check_the_image_first() {
|
||||
&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 { 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);",
|
||||
|
||||
@@ -0,0 +1,541 @@
|
||||
//! 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<u8> {
|
||||
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<Value> {
|
||||
let main = base.join("main/main.jsx");
|
||||
std::fs::write(&main, text).unwrap();
|
||||
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
|
||||
}
|
||||
|
||||
fn log(s: &mut Session, base: &Path, text: &str) -> Vec<Value> {
|
||||
let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The Image Trace objects of the active document.
|
||||
fn traces(s: &Session) -> Vec<NodeId> {
|
||||
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<NodeId> {
|
||||
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);
|
||||
}
|
||||
|
||||
#[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 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 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]));
|
||||
if !m.contains(message) || out[1] != before.2["params"]["threshold"] || now != before {
|
||||
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);
|
||||
}
|
||||
|
||||
#[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 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);",
|
||||
);
|
||||
assert_eq!(out, [json!("PluginItem"), 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);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
@@ -78,7 +78,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"",
|
||||
"app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||||
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \
|
||||
PageItems PlacedItem PlacedItems RasterItem RasterItems RulerUnits ZOrderMethod",
|
||||
PageItems PlacedItem PlacedItems PluginItem RasterItem RasterItems RulerUnits TracingObject TracingOptions ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
@@ -121,7 +121,9 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("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 trace="),
|
||||
("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"),
|
||||
@@ -129,7 +131,23 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"RasterItem.prototype.",
|
||||
"bitsPerChannel boundingBox channels colorants colorants= colorize colorize= colorizedGrayscale constructor \
|
||||
contentVariable contentVariable= embedded embedded= file imageColorSpace matrix matrix= overprint overprint= status \
|
||||
trace trace= transparent",
|
||||
trace transparent",
|
||||
),
|
||||
("TracingObject.", "prototype"),
|
||||
(
|
||||
"TracingObject.prototype.",
|
||||
"anchorCount 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=",
|
||||
),
|
||||
("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"),
|
||||
("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"),
|
||||
@@ -163,6 +181,15 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("", "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 classes the host adds with nothing but a prototype and its constructor: the page item types
|
||||
|
||||
@@ -518,7 +518,7 @@ fn set_hidden(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<
|
||||
if outcome(i, o, &r)? {
|
||||
let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?;
|
||||
if matches!(fs, Value::String(_)) {
|
||||
set_slot(i, o, PATH, fs)?;
|
||||
set_path(i, o, fs)?;
|
||||
}
|
||||
}
|
||||
Ok(Value::Undefined)
|
||||
|
||||
+32
-1
@@ -2756,7 +2756,38 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
`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. 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`, `trace`, `colorants`, `colorize` and `overprint` are not available yet.
|
||||
end of the run. `contentVariable`, `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. The `PluginItem`, `TracingObject`
|
||||
and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. `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`. `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.
|
||||
- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and
|
||||
`$.writeln(...values)` does the same and ends the line. Each call counts as a host call.
|
||||
- `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global
|
||||
|
||||
@@ -1029,7 +1029,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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. Tracing, rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.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, 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. `crates/engine/src/tests/script_dom_tracing.rs`.
|
||||
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
|
||||
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
|
||||
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.
|
||||
|
||||
Reference in new issue
Block a user