Files
vectorcraft/crates/engine/src/script/dom/tracing.rs
T
dotCooCoo eb5e4c5eb7 Scripts: retrace and release refuse a tracing with locked traced artwork
Retracing and releasing a tracing discard the objects its trace made, so
both now throw "Cannot edit page item <id>" when one of them is locked,
with nothing changed. Added artwork is still reported first. The scan
stops at the first added object and charges the objects it looked at to
the run on both the success and refusal paths.
2026-12-02 08:32:22 -08:00

929 lines
41 KiB
Rust

//! Tracing in the script object model: `PlacedItem.trace()` and `RasterItem.trace()`, the
//! `PluginItem` an Image Trace object is, its `TracingObject` and its `TracingOptions`, as the help
//! pages <https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/> describe them.
//!
//! An Image Trace object is a group that holds its source image, hidden, as its first object.
//! Tracing runs `imageTrace.make`, expanding `imageTrace.expand`, releasing `imageTrace.release`
//! and a change of view `imageTrace.setView`, so each joins the run's transaction and its work
//! counts against the run's limits.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - `trace()` returns once the trace is made, so the counts can be read at once. It traces with
//! the Default preset.
//! - The traced image stays the same object: `sourceArt` gives it, and `releaseTracing()` gives it
//! back. `trace()` on an image that is the source of a tracing throws [`ALREADY_TRACED`], and on
//! a linked image whose file is missing throws `Linked image is missing`.
//! - `pathCount` counts the traced paths, without the seam fills an Abutting trace adds,
//! `anchorCount` their anchor points and `usedColorCount` the different paints they are filled
//! and stroked with, as the tracing is when they are read. `areaCount` throws. `imageResolution`
//! is the source image's pixels per inch as it is placed; an image placed at a different
//! resolution across and down has none.
//! - Assigning an option, or `loadFromPreset(name)`, traces again unless the options are already
//! so. Tracing again makes a new object: the `PluginItem`, its `TracingObject` and its
//! `TracingOptions` follow it. A tracing that another command traced again, expanded or
//! released, or whose source image was deleted, is stale.
//! - Tracing again throws [`ADDED_ARTWORK`], with nothing changed, when the tracing holds an object
//! its trace did not make, whether this run, an earlier run or a command added it, and
//! `releaseTracing()` throws [`ADDED_ARTWORK_RELEASE`] in the same case. The tracing records the
//! objects its trace made ([`crate::doc::TraceMade`]), and a copy of it records their copies. A
//! tracing saved without that record is checked only for objects added in this run.
//! - `palette` is `""` for the automatic palette, or `"Limited"`, `"Full Tone"` or
//! `"Document Library"`. `minArea` is the Noise setting in pixels: an area smaller than it is not
//! traced. `tracingMode` has no value for the Flat Logo mode. The options with no VectorCraft
//! setting throw [`not_implemented`].
//! - `viewRaster` and `viewVector` take only the pairs of the Image Trace views
//! ([`VIEWS`]); the Split view has neither.
//! - `storeToPreset(name)` gives `false` for a built-in preset and `Custom`; a script cannot change
//! the saved presets, so any other name throws. A preset name has at most [`MAX_PRESET_NAME`]
//! bytes and none of `/`, `\`, `:` or control characters.
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{Data, HostClass, HostError, HostMember, MemberInfo, host_ref, host_ref_parts};
use super::{
Answer, Described, Host, Item, Link, STALE_ITEM, arg, boolean, class, command, command_value, edit_item, float, get, item_of, item_ref, method,
named, node_of, num, number, on_doc, property, returns, text, typed, typename_of, whole, with_doc,
};
use crate::doc::{Node, TraceView};
use crate::{NodeId, NodeKind};
/// The error of `trace()` on an image that is the source of a tracing.
pub const ALREADY_TRACED: &str = "The image is the source art of a tracing";
/// The error of tracing again a tracing that holds an object its trace did not make.
pub const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork";
/// The error of releasing a tracing that holds an object its trace did not make.
pub const ADDED_ARTWORK_RELEASE: &str = "Cannot release a tracing containing added artwork";
/// The error of options that trace with neither fills nor strokes.
pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes";
/// The error of `expandTracing(true)`.
pub const VIEWED_EXPAND: &str = "TracingObject.expandTracing(true) is not implemented";
/// The longest preset name `loadFromPreset` and `storeToPreset` take, in bytes.
pub const MAX_PRESET_NAME: usize = 256;
/// The most times one run traces a tracing again through its options.
pub const MAX_RETRACES: usize = 10_000;
/// The largest `minArea`: the most pixels the tracer traces ([`vectorcraft_trace::MAX_PIXELS`]).
pub const MAX_MIN_AREA: u64 = vectorcraft_trace::MAX_PIXELS;
/// The enumerations the members here give values of, as the help page
/// <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/> lists them.
pub(super) const ENUMS: &[(&str, &[&str])] = &[
("TracingModeType", &["TRACINGMODEBLACKANDWHITE", "TRACINGMODECOLOR", "TRACINGMODEGRAY"]),
(
"ViewRasterType",
&["TRACINGVIEWRASTERADJUSTEDIMAGE", "TRACINGVIEWRASTERNOIMAGE", "TRACINGVIEWRASTERORIGINALIMAGE", "TRACINGVIEWRASTERTRANSPARENTIMAGE"],
),
(
"ViewVectorType",
&["TRACINGVIEWVECTORNOTRACINGRESULT", "TRACINGVIEWVECTOROUTLINES", "TRACINGVIEWVECTOROUTLINESWITHTRACING", "TRACINGVIEWVECTORTRACINGRESULT"],
),
];
/// The classes this module defines.
pub(super) const CLASSES: &[&str] = &["PluginItem"];
/// Each Image Trace view with the `viewRaster` and `viewVector` that give it.
const VIEWS: &[(TraceView, &str, &str)] = &[
(TraceView::Result, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"),
(TraceView::ResultWithOutlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINESWITHTRACING"),
(TraceView::Outlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"),
(TraceView::OutlinesWithSource, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"),
(TraceView::Source, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTORNOTRACINGRESULT"),
];
/// Each `tracingMode` with its Image Trace mode.
const MODES: &[(&str, &str)] = &[
("TracingModeType.TRACINGMODEBLACKANDWHITE", "blackAndWhite"),
("TracingModeType.TRACINGMODEGRAY", "grayscale"),
("TracingModeType.TRACINGMODECOLOR", "color"),
];
/// Each `palette` name with its Image Trace palette.
const PALETTES: &[(&str, &str)] = &[("", "automatic"), ("Limited", "limited"), ("Full Tone", "fullTone"), ("Document Library", "documentLibrary")];
/// The options with no VectorCraft setting.
const NOT_IMPLEMENTED: &[&str] = &[
"cornerAngle",
"livePaintOutput",
"maxStrokeWeight",
"minStrokeLength",
"outputToSwatches",
"pathFitting",
"preprocessBlur",
"resample",
"resampleResolution",
];
/// What a run keeps for tracings: for each document uid and Image Trace object a script traced
/// again through its options, the id of the object that replaced it.
#[derive(Default)]
pub(super) struct State {
next: RefCell<HashMap<(u64, u64), u64>>,
/// `next` the other way round: for each replacing object, the object it replaced.
prev: RefCell<HashMap<(u64, u64), u64>>,
sources: RefCell<HashMap<(u64, u64), NodeId>>,
descendants: RefCell<HashMap<(u64, u64), HashSet<NodeId>>>,
retraces: Cell<usize>,
}
/// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put
/// it back put back the same object), else the first object the document holds among those that
/// replaced it, one after the other, when this run traced it again (an Undo can put back one of
/// them), else the last of them, else `id`.
pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId {
let s = h.session.borrow();
let doc = s.documents().iter().find(|d| d.uid == uid);
let held = |id: NodeId| doc.is_some_and(|d| d.doc.node(id).is_some());
let next = h.dom.tracing.next.borrow();
let mut id = id;
// Each object is replaced by one made later, so the steps end; the bound holds them anyway.
for _ in 0..=next.len() {
if held(id) {
return id;
}
match next.get(&(uid, id.0)) {
Some(n) => id = NodeId(*n),
None => return id,
}
}
id
}
/// The first object of the run's chain of replacements that leads to `id` in the document `uid`,
/// so every handle to a tracing traced again names the same object; `id` when no earlier object
/// in the chain resolves to it.
pub(super) fn origin(h: &Host, uid: u64, id: NodeId) -> NodeId {
let first = {
let prev = h.dom.tracing.prev.borrow();
let mut first = id;
// Each object replaces one made before it, so the steps end; the bound holds them anyway.
for _ in 0..prev.len() {
match prev.get(&(uid, first.0)) {
Some(old) => first = NodeId(*old),
None => break,
}
}
first
};
if first != id && follow(h, uid, first) == id { first } else { id }
}
/// Records that `new` replaced `old` in the document `uid`.
fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) {
let mut prev = h.dom.tracing.prev.borrow_mut();
// A second replacement of `old` takes the place of the first in both directions.
if let Some(earlier) = h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0)
&& prev.get(&(uid, earlier)) == Some(&old.0)
{
prev.remove(&(uid, earlier));
}
prev.insert((uid, new.0), old.0);
}
pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) {
let mut first = true;
if let Some(source) = group.children().and_then(|c| c.first()) {
let mut sources = h.dom.tracing.sources.borrow_mut();
first = !sources.contains_key(&(uid, group.id.0));
sources.entry((uid, group.id.0)).or_insert(source.id);
}
// Only a tracing saved without the record of the objects its trace made needs the snapshot,
// taken the first time this run sees it.
if !first || group.trace_made().is_some() {
return;
}
h.dom.tracing.descendants.borrow_mut().entry((uid, group.id.0)).or_insert_with(|| {
let mut ids = HashSet::new();
group.walk(&mut |n| {
if n.id != group.id {
ids.insert(n.id);
}
});
ids
});
}
pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool {
let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied();
source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source))
}
/// The error of a member with no VectorCraft setting.
pub fn not_implemented(class: &str, name: &str) -> String {
format!("{class}.{name} is not implemented")
}
fn out_of_range(name: &str, range: &str) -> HostError {
HostError::Range(format!("TracingOptions.{name} is out of range: {range}"))
}
fn invalid(name: &str) -> HostError {
HostError::Error(format!("TracingOptions.{name} has an invalid value"))
}
fn stale() -> HostError {
HostError::Error(STALE_ITEM.into())
}
fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> {
match d {
Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v),
_ => None,
}
}
/// The first id of a command's result `key`: a number or a list of them, read exactly.
fn result_id(v: &Value, key: &str) -> Option<NodeId> {
match &v[key] {
Value::Array(a) => a.first().and_then(Value::as_u64).map(NodeId),
n => n.as_u64().map(NodeId),
}
}
/// The Image Trace object, its document and the id its handle holds, of the `cls` (`TracingObject`
/// or `TracingOptions`) `d` names. It must still be an Image Trace object of its document.
fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 5]), HostError> {
let Some((c, handle)) = host_ref_parts(d).filter(|(c, _)| *c == cls) else {
return Err(HostError::Type(format!("this is not a {cls}")));
};
let &[run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) };
let (doc, original) = node_of(h, &handle).ok_or_else(stale)?;
let id = follow(h, doc.uid, original);
let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|g| crate::cmd::is_trace_group(g) && same_source(h, doc.uid, original, g)));
if !live {
return Err(stale());
}
Ok((Item { doc, id }, [run, uid, high, low, reverts]))
}
/// The `PluginItem` `this` names, with the handle numbers its `tracing` keeps.
fn plugin_of(h: &Host, a: &[Data]) -> Result<(Item, [f64; 5]), HostError> {
match host_ref_parts(arg(a, 0)) {
Some(("PluginItem", handle)) => {
let item = item_of(h, arg(a, 0))?;
match handle.as_slice() {
&[run, uid, high, low, reverts] => Ok((item, [run, uid, high, low, reverts])),
_ => Err(HostError::Type("this is not a PluginItem".into())),
}
}
_ => Err(HostError::Type("this is not a PluginItem".into())),
}
}
/// Reads the Image Trace object of `item` with `f`.
fn read_group<T>(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) -> Result<T, HostError>) -> Result<T, HostError> {
with_doc(h, item.doc, |_, st| match st.doc.node(item.id) {
Some(n) => f(st, n),
None => Err(stale()),
})
}
fn refuse_uneditable(h: &Host, item: Item) -> Result<(), HostError> {
let editable = with_doc(h, item.doc, |_, st| super::editable(&st.doc, item.id) && !super::on_locked_artboard(h, st, item.id));
if !editable {
return Err(HostError::Error(format!("Cannot edit page item {}", item.id.0)));
}
Ok(())
}
/// Runs command `id` with `params` on `item`'s document → the object its result names under `key`.
/// The selection stays as it was, with that object in place of `item`.
fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result<NodeId, HostError> {
refuse_uneditable(h, item)?;
let mut before = with_doc(h, item.doc, |_, st| st.selection.clone());
on_doc(h, item.doc.uid, false, |h| {
let (_, r) = command_value(h, id, params)?;
for w in r.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
super::super::each_line(&format!("{id}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
}
let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?;
let remap = |i: NodeId| if i == item.id { new } else { i };
before.objects = before.objects.into_iter().map(remap).collect();
let mut seen = HashSet::new();
before.objects.retain(|i| seen.insert(*i));
before.key = before.key.map(remap);
before.target = before.target.map(remap);
before.on_path_member = before.on_path_member.map(remap);
let restore = {
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
(st.selection != before).then(|| st.doc.clone())
};
if let Some(doc) = restore {
super::restore_selection(h, &doc, &before)?;
}
Ok(new)
})
}
/// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make,
/// and "Cannot edit page item" when it holds a locked object other than its source image, which
/// the replacement would discard. The objects looked at are charged to the run either way.
fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
let (visited, result) = read_group(h, item, |_, group| {
remember_source(h, item.doc.uid, group);
// The objects the trace made, as the tracing records them; a tracing saved without that
// record is checked against the objects it held when this run first saw it.
let made = group.trace_made();
let descendants = h.dom.tracing.descendants.borrow();
let ids = match made {
Some(_) => None,
None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?),
};
let source = group.children().and_then(|c| c.first()).map(|n| n.id);
let mut visited = 0u64;
let mut locked = None;
let mut todo: Vec<&Arc<Node>> = group.children().map(|c| c.iter().collect()).unwrap_or_default();
while let Some(n) = todo.pop() {
visited += 1;
let added = match (&made, ids) {
(Some(m), _) => !m.contains(n.id),
(None, Some(ids)) => !ids.contains(&n.id),
(None, None) => false,
};
// Added artwork is reported before a locked object, whichever comes first.
if added {
return Ok((visited, Err(HostError::Error(refusal.into()))));
}
if n.locked && Some(n.id) != source && locked.is_none() {
locked = Some(n.id);
}
todo.extend(n.children().into_iter().flatten());
}
Ok((visited, locked.map_or(Ok(()), |id| Err(HostError::Error(format!("Cannot edit page item {}", id.0))))))
})?;
h.charge_call(visited)?;
result
}
/// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its
/// script objects follow the new one.
fn retrace(h: &Host, item: Item, mut params: Map<String, Value>) -> Result<(), HostError> {
if h.dom.tracing.retraces.get() >= MAX_RETRACES {
return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times")));
}
refuse_added(h, item, ADDED_ARTWORK)?;
params.insert("id".into(), json!(item.id.0));
// One savepoint covers the trace and the selection's restore, so a failed restore undoes the trace.
let new = super::atomically(h, |h| replace(h, item, "imageTrace.make", &Value::Object(params), "id"))?;
read_group(h, Item { id: new, ..item }, |_, group| {
remember_source(h, item.doc.uid, group);
Ok(())
})?;
h.dom.tracing.retraces.set(h.dom.tracing.retraces.get() + 1);
replaced(h, item.doc.uid, item.id, new);
Ok(())
}
// ---- PlacedItem and RasterItem ----
/// `trace()`: `imageTrace.make` of the image with the Default preset → its `PluginItem`.
fn image_trace(h: &Host, a: &[Data], cls: &str) -> Answer {
let item = match host_ref_parts(arg(a, 0)) {
Some((c, _)) if c == cls => item_of(h, arg(a, 0))?,
_ => return Err(HostError::Type(format!("this is not a {cls}"))),
};
let (source, linked) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let source = crate::cmd::is_trace_source(d, item.id);
let linked = matches!(d.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some());
(source, linked)
});
if source {
return Err(HostError::Error(ALREADY_TRACED.into()));
}
if linked {
let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?;
if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") {
return Err(HostError::Error(super::images::MISSING_LINK.into()));
}
}
let id = replace(h, item, "imageTrace.make", &json!({"id": item.id.0}), "id")?;
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
}
fn placed_trace(h: &Host, a: &[Data]) -> Answer {
image_trace(h, a, "PlacedItem")
}
fn raster_trace(h: &Host, a: &[Data]) -> Answer {
image_trace(h, a, "RasterItem")
}
// ---- PluginItem ----
fn plugin_is_tracing(h: &Host, a: &[Data]) -> Answer {
plugin_of(h, a)?;
Ok(Data::Bool(true))
}
fn plugin_tracing(h: &Host, a: &[Data]) -> Answer {
let (item, handle) = plugin_of(h, a)?;
let source = read_group(h, item, |_, g| g.children().and_then(|c| c.first()).map(|n| n.id).ok_or_else(stale))?;
let (_, original) = node_of(h, &handle).ok_or_else(stale)?;
h.dom.tracing.sources.borrow_mut().entry((item.doc.uid, original.0)).or_insert(source);
Ok(host_ref("TracingObject", &handle))
}
// ---- TracingObject ----
/// What a tracing's counts are made of.
#[derive(Default)]
struct Counts {
paths: u64,
anchors: u64,
colors: u64,
/// The objects looked at.
visited: u64,
}
/// Which of a tracing's counts a read needs; the others are not worked out.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Metric {
Paths,
Anchors,
Colors,
}
/// The anchor points of `n` and every path in it, adding each object looked at below `n` to
/// `visited`.
fn anchors_of(n: &Node, visited: &mut u64) -> u64 {
match &n.kind {
NodeKind::Path { path, .. } => path.anchor_count() as u64,
_ => n.children().map_or(0, |c| {
c.iter()
.map(|m| {
*visited += 1;
anchors_of(m, visited)
})
.sum()
}),
}
}
/// The traced paths of the Image Trace object `g`, their anchor points and paints: every path
/// and compound path in it but its source image, the seam fills and clipping paths. The seam fills
/// are a clip group directly in the tracing that [`crate::cmd::is_seam_fills`] accepts, or, for a
/// trace made before seam fills were clipped, the lowest item above the source image when it
/// accepts that. A group nested deeper, or an unclipped group higher up, is counted. An Image
/// Trace object inside `g` leaves out its own seam fills the same way. Only the count `metric`
/// names is worked out; a compound path counts as one path, and the paths inside it are looked at
/// (and counted in `visited`) only for its anchor points.
fn counts(g: &Node, metric: Metric) -> Counts {
let mut c = Counts::default();
let mut paints = HashSet::new();
let mut todo: Vec<&Arc<Node>> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default();
let mut seams = seam_fills_of(g);
while let Some(n) = todo.pop() {
c.visited += 1;
if seams.contains(&n.id) {
continue;
}
if crate::cmd::is_trace_group(n) {
seams.extend(seam_fills_of(n));
}
match &n.kind {
NodeKind::Path { clipping: true, .. } => {}
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
c.paths += 1;
match metric {
Metric::Paths => {}
Metric::Anchors => c.anchors += anchors_of(n, &mut c.visited),
Metric::Colors => {
for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] {
if paint != vectorcraft_color::Paint::None
&& let Ok(key) = serde_json::to_string(&paint)
{
paints.insert(key);
}
}
}
}
}
_ => todo.extend(n.children().into_iter().flatten()),
}
}
c.colors = paints.len() as u64;
c
}
/// The seam fills of the Image Trace object `g` ([`counts`]).
fn seam_fills_of(g: &Node) -> HashSet<NodeId> {
g.children()
.into_iter()
.flatten()
.skip(1)
.enumerate()
.filter(|(i, n)| (*i == 0 || matches!(n.kind, NodeKind::Group { clip: true, .. })) && crate::cmd::is_seam_fills(n))
.map(|(_, n)| n.id)
.collect()
}
/// Reads the counts of the tracing `this` names with `f`.
fn count(h: &Host, a: &[Data], metric: Metric) -> Answer {
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
let c = read_group(h, item, |_, g| Ok(counts(g, metric)))?;
h.charge_call(c.visited)?;
Ok(num(float(match metric {
Metric::Paths => c.paths,
Metric::Anchors => c.anchors,
Metric::Colors => c.colors,
})))
}
fn tracing_paths(h: &Host, a: &[Data]) -> Answer {
count(h, a, Metric::Paths)
}
fn tracing_anchors(h: &Host, a: &[Data]) -> Answer {
count(h, a, Metric::Anchors)
}
fn tracing_colors(h: &Host, a: &[Data]) -> Answer {
count(h, a, Metric::Colors)
}
fn tracing_areas(h: &Host, a: &[Data]) -> Answer {
tracing_of(h, arg(a, 0), "TracingObject")?;
Err(HostError::Error(not_implemented("TracingObject", "areaCount")))
}
/// `imageResolution`: the source image's pixels per inch, 72 over the size of a pixel in points.
fn tracing_resolution(h: &Host, a: &[Data]) -> Answer {
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
read_group(h, item, |_, g| {
let source = g.children().and_then(|c| c.first()).ok_or_else(stale)?;
let NodeKind::Image(im) = &source.kind else { return Err(stale()) };
let none = || HostError::Error("the source image has no single resolution".into());
if source.is_distorted_image() {
return Err(none());
}
let [xa, xb, ya, yb, ..] = im.xf.as_coeffs();
let (across, down) = (xa.hypot(xb), ya.hypot(yb));
if across <= 1e-12 || down <= 1e-12 || (across - down).abs() > 1e-9 * across.max(down) {
return Err(none());
}
Ok(num(72.0 / across))
})
}
fn tracing_parent(h: &Host, a: &[Data]) -> Answer {
let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?;
Ok(host_ref("PluginItem", &handle))
}
fn tracing_source(h: &Host, a: &[Data]) -> Answer {
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
read_group(h, item, |st, g| g.children().and_then(|c| c.first()).map(|s| item_ref(h, st, s.id)).ok_or_else(stale))
}
fn tracing_options(h: &Host, a: &[Data]) -> Answer {
let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?;
Ok(host_ref("TracingOptions", &handle))
}
/// `expandTracing(viewed?)`: `imageTrace.expand` → the `GroupItem` that takes the tracing's place.
fn tracing_expand(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::Undefined | Data::Bool(false) => {}
Data::Bool(true) => {
tracing_of(h, arg(a, 0), "TracingObject")?;
return Err(HostError::Error(VIEWED_EXPAND.into()));
}
_ => return Err(HostError::Type("viewed must be true or false".into())),
}
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
let id = replace(h, item, "imageTrace.expand", &json!({"ids": [item.id.0]}), "ids")?;
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
}
/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. A
/// tracing that holds an object its trace did not make throws [`ADDED_ARTWORK_RELEASE`], since the
/// release keeps only the source image.
fn tracing_release(h: &Host, a: &[Data]) -> Answer {
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
refuse_added(h, item, ADDED_ARTWORK_RELEASE)?;
let id = replace(h, item, "imageTrace.release", &json!({"ids": [item.id.0]}), "ids")?;
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
}
// ---- TracingOptions ----
/// The tracing `this` names, the settings it was traced with, its view and its preset's name.
fn options_of(h: &Host, a: &[Data]) -> Result<(Item, Map<String, Value>, TraceView, String), HostError> {
let (item, _) = tracing_of(h, arg(a, 0), "TracingOptions")?;
read_group(h, item, |_, g| {
let trace = g.extras().trace.as_deref();
let params = trace.and_then(|t| t.get("params")).and_then(Value::as_object).cloned();
let params = params.ok_or_else(|| HostError::Error("the tracing has no recorded options".into()))?;
let preset = trace.and_then(|t| t.get("preset")).and_then(Value::as_str).unwrap_or_default().to_string();
Ok((item, params, g.trace_view(), preset))
})
}
/// Reads the setting `key` of the tracing `this` names with `f`.
fn read_option(h: &Host, a: &[Data], key: &str, f: impl FnOnce(&Value) -> Answer) -> Answer {
let (_, params, ..) = options_of(h, a)?;
f(params.get(key).unwrap_or(&Value::Null))
}
/// Traces again with the setting `key` at `value`, unless it is at that value already.
fn write_option(h: &Host, a: &[Data], key: &str, value: Value) -> Answer {
let (item, mut params, ..) = options_of(h, a)?;
if params.get(key) == Some(&value) {
return Ok(Data::Undefined);
}
params.insert(key.into(), value);
let on = |k: &str| params.get(k).and_then(Value::as_bool) == Some(true);
if !on("fills") && !on("strokes") {
return Err(HostError::Error(NEEDS_FILLS_OR_STROKES.into()));
}
let mut p = Map::new();
p.insert("params".into(), Value::Object(params));
retrace(h, item, p)?;
Ok(Data::Undefined)
}
/// A whole number from `lo` to `hi` for the option `name`.
fn whole_in(d: &Data, name: &str, lo: u64, hi: u64) -> Result<u64, HostError> {
let n = number(d, &format!("TracingOptions.{name}"))?;
if n.fract() != 0.0 || n < float(lo) || n > float(hi) {
return Err(out_of_range(name, &format!("a whole number from {lo} to {hi}")));
}
whole(n).ok_or_else(|| out_of_range(name, &format!("a whole number from {lo} to {hi}")))
}
fn as_number(v: &Value) -> Answer {
v.as_f64().map(num).ok_or_else(|| HostError::Error("the tracing's options are damaged".into()))
}
fn as_bool(v: &Value) -> Answer {
v.as_bool().map(Data::Bool).ok_or_else(|| HostError::Error("the tracing's options are damaged".into()))
}
fn options_mode(h: &Host, a: &[Data]) -> Answer {
read_option(h, a, "mode", |v| {
let mode = v.as_str().unwrap_or_default();
match MODES.iter().find(|(_, m)| *m == mode) {
Some((name, _)) => Ok(text(*name)),
None => Err(HostError::Error("TracingOptions.tracingMode has no value for this tracing's mode".into())),
}
})
}
fn options_set_mode(h: &Host, a: &[Data]) -> Answer {
let mode = match arg(a, 1) {
Data::String(s) => MODES.iter().find(|(n, _)| n == s).map(|(_, m)| *m),
_ => None,
};
let mode = mode.ok_or_else(|| HostError::Type("TracingOptions.tracingMode must be a TracingModeType value".into()))?;
write_option(h, a, "mode", json!(mode))
}
fn options_threshold(h: &Host, a: &[Data]) -> Answer {
read_option(h, a, "threshold", as_number)
}
fn options_set_threshold(h: &Host, a: &[Data]) -> Answer {
let v = whole_in(arg(a, 1), "threshold", 0, 255)?;
write_option(h, a, "threshold", json!(v))
}
fn options_max_colors(h: &Host, a: &[Data]) -> Answer {
read_option(h, a, "colors", as_number)
}
fn options_set_max_colors(h: &Host, a: &[Data]) -> Answer {
let v = whole_in(arg(a, 1), "maxColors", 2, 256)?;
write_option(h, a, "colors", json!(v))
}
fn options_min_area(h: &Host, a: &[Data]) -> Answer {
read_option(h, a, "noise", as_number)
}
fn options_set_min_area(h: &Host, a: &[Data]) -> Answer {
let v = whole_in(arg(a, 1), "minArea", 0, MAX_MIN_AREA)?;
write_option(h, a, "noise", json!(v))
}
fn options_fills(h: &Host, a: &[Data]) -> Answer {
read_option(h, a, "fills", as_bool)
}
fn options_set_fills(h: &Host, a: &[Data]) -> Answer {
let v = boolean(arg(a, 1), "TracingOptions.fills")?;
write_option(h, a, "fills", json!(v))
}
fn options_strokes(h: &Host, a: &[Data]) -> Answer {
read_option(h, a, "strokes", as_bool)
}
fn options_set_strokes(h: &Host, a: &[Data]) -> Answer {
let v = boolean(arg(a, 1), "TracingOptions.strokes")?;
write_option(h, a, "strokes", json!(v))
}
fn options_ignore_white(h: &Host, a: &[Data]) -> Answer {
read_option(h, a, "ignoreWhite", as_bool)
}
fn options_set_ignore_white(h: &Host, a: &[Data]) -> Answer {
let v = boolean(arg(a, 1), "TracingOptions.ignoreWhite")?;
write_option(h, a, "ignoreWhite", json!(v))
}
fn options_palette(h: &Host, a: &[Data]) -> Answer {
read_option(h, a, "palette", |v| {
let palette = v.as_str().unwrap_or_default();
match PALETTES.iter().find(|(_, p)| *p == palette) {
Some((name, _)) => Ok(text(*name)),
None => Err(HostError::Error("the tracing's options are damaged".into())),
}
})
}
fn options_set_palette(h: &Host, a: &[Data]) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("TracingOptions.palette must be a string".into())) };
let palette = PALETTES.iter().find(|(n, _)| n == name).map(|(_, p)| *p).ok_or_else(|| invalid("palette"))?;
write_option(h, a, "palette", json!(palette))
}
/// The view's `viewRaster` (`raster`) or `viewVector`.
fn view_part(view: TraceView, raster: bool) -> Answer {
let name = if raster { "viewRaster" } else { "viewVector" };
VIEWS
.iter()
.find(|(v, ..)| *v == view)
.map(|(_, r, v)| text(if raster { *r } else { *v }))
.ok_or_else(|| HostError::Error(format!("TracingOptions.{name} has no value for the Split view")))
}
fn options_view(h: &Host, a: &[Data], raster: bool) -> Answer {
let (_, _, view, _) = options_of(h, a)?;
view_part(view, raster)
}
/// Shows the view `viewRaster` (`raster`) or `viewVector` makes with the other one as it is.
fn options_set_view(h: &Host, a: &[Data], raster: bool) -> Answer {
let (name, kind) = if raster { ("viewRaster", "ViewRasterType") } else { ("viewVector", "ViewVectorType") };
let given = match arg(a, 1) {
Data::String(s) if ENUMS.iter().any(|(e, members)| *e == kind && members.iter().any(|m| *s == format!("{kind}.{m}"))) => s.clone(),
_ => return Err(HostError::Type(format!("TracingOptions.{name} must be a {kind} value"))),
};
let (item, _, view, _) = options_of(h, a)?;
let Data::String(other) = view_part(view, !raster)? else { return Err(invalid(name)) };
let pair = |r: &str, v: &str| if raster { given == r && other == v } else { other == r && given == v };
let (to, ..) = VIEWS.iter().find(|(_, r, v)| pair(r, v)).ok_or_else(|| invalid(name))?;
if *to != view {
refuse_uneditable(h, item)?;
edit_item(h, item, "imageTrace.setView", &json!({"ids": [item.id.0], "view": to.id()}))?;
}
Ok(Data::Undefined)
}
fn options_view_raster(h: &Host, a: &[Data]) -> Answer {
options_view(h, a, true)
}
fn options_set_view_raster(h: &Host, a: &[Data]) -> Answer {
options_set_view(h, a, true)
}
fn options_view_vector(h: &Host, a: &[Data]) -> Answer {
options_view(h, a, false)
}
fn options_set_view_vector(h: &Host, a: &[Data]) -> Answer {
options_set_view(h, a, false)
}
fn options_preset(h: &Host, a: &[Data]) -> Answer {
let (_, _, _, preset) = options_of(h, a)?;
Ok(text(preset))
}
fn options_parent(h: &Host, a: &[Data]) -> Answer {
let (_, handle) = tracing_of(h, arg(a, 0), "TracingOptions")?;
Ok(host_ref("TracingObject", &handle))
}
/// A preset name given to `method`: a string of at most [`MAX_PRESET_NAME`] bytes without `/`,
/// `\`, `:` or control characters, trimmed.
fn preset_name<'a>(d: &'a Data, method: &str) -> Result<&'a str, HostError> {
let Data::String(name) = d else { return Err(HostError::Type(format!("TracingOptions.{method} needs a preset name, as a string"))) };
if name.len() > MAX_PRESET_NAME {
return Err(HostError::Range(format!("TracingOptions.{method}: a preset name has at most {MAX_PRESET_NAME} bytes")));
}
if name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) {
return Err(HostError::Error(format!("TracingOptions.{method}: a preset name cannot hold / \\ : or control characters")));
}
let name = name.trim();
if name.is_empty() {
return Err(HostError::Error(format!("TracingOptions.{method}: the preset name is empty")));
}
Ok(name)
}
/// `loadFromPreset(name)`: traces again with the built-in or saved preset `name` → `true`.
fn options_load(h: &Host, a: &[Data]) -> Answer {
let name = preset_name(arg(a, 1), "loadFromPreset")?;
let (item, params, _, preset) = options_of(h, a)?;
let wanted = vectorcraft_trace::preset(name).or_else(|| h.session.borrow().trace_preset(name).map(|q| q.params.clone()));
let wanted = wanted.ok_or_else(|| HostError::Error("TracingOptions.loadFromPreset: no built-in or saved preset has that name".into()))?;
let same = serde_json::to_value(&wanted).ok().as_ref().and_then(Value::as_object) == Some(&params);
if !(same && preset.eq_ignore_ascii_case(name)) {
let mut p = Map::new();
p.insert("preset".into(), json!(name));
retrace(h, item, p)?;
}
Ok(Data::Bool(true))
}
/// `storeToPreset(name)`: `false` for a built-in preset or `Custom`; any other name runs
/// `imageTrace.presets.save`, which a script cannot run.
fn options_store(h: &Host, a: &[Data]) -> Answer {
let name = preset_name(arg(a, 1), "storeToPreset")?;
let (_, params, ..) = options_of(h, a)?;
if vectorcraft_trace::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") {
return Ok(Data::Bool(false));
}
command(h, "imageTrace.presets.save", &json!({"name": name, "params": params}))?;
Ok(Data::Bool(true))
}
/// A member of `TracingOptions` with no VectorCraft setting: reading and assigning it both throw,
/// after the check that the tracing `this` names is still there, and `reflect` and
/// `hasOwnProperty` leave it out.
fn missing(link: &Link, name: &'static str) -> Described {
let message = not_implemented("TracingOptions", name);
let l = link.clone();
let f: vectorcraft_js::HostFunction = std::rc::Rc::new(move |a: Vec<Data>| {
let h = super::current(&l)?;
h.charge_call(16)?;
tracing_of(&h, arg(&a, 0), "TracingOptions")?;
Err(HostError::Error(message.clone()))
});
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
}
/// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`.
pub(super) fn add_trace(classes: &mut [HostClass], l: &Link) {
for c in classes.iter_mut() {
let f: super::Member = match c.name.as_str() {
"PlacedItem" => placed_trace,
"RasterItem" => raster_trace,
_ => continue,
};
c.members.push(("trace".into(), method(l, f)));
c.info.push(("trace".into(), returns("PluginItem", &[])));
}
}
/// `PluginItem`, after `PageItem`, `TracingObject` and `TracingOptions`.
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
let plugin = named(vec![("isTracing", get(l, plugin_is_tracing), typed("boolean")), ("tracing", get(l, plugin_tracing), typed("TracingObject"))]);
let tracing = named(vec![
("typename", typename_of("TracingObject"), typed("string")),
("anchorCount", get(l, tracing_anchors), typed("number")),
("areaCount", HostMember::Unavailable(super::function(l, tracing_areas)), MemberInfo { unavailable: true, ..MemberInfo::default() }),
("imageResolution", get(l, tracing_resolution), typed("number")),
("parent", get(l, tracing_parent), typed("PluginItem")),
("pathCount", get(l, tracing_paths), typed("number")),
("sourceArt", get(l, tracing_source), typed("PageItem")),
("tracingOptions", get(l, tracing_options), typed("TracingOptions")),
("usedColorCount", get(l, tracing_colors), typed("number")),
("expandTracing", method(l, tracing_expand), returns("GroupItem", &[("viewed", "boolean")])),
("releaseTracing", method(l, tracing_release), returns("PageItem", &[])),
]);
let mut options = named(vec![
("typename", typename_of("TracingOptions"), typed("string")),
("parent", get(l, options_parent), typed("TracingObject")),
("preset", get(l, options_preset), typed("string")),
("tracingMode", property(l, options_mode, options_set_mode), typed("TracingModeType")),
("threshold", property(l, options_threshold, options_set_threshold), MemberInfo { min: Some(0.0), max: Some(255.0), ..typed("number") }),
("fills", property(l, options_fills, options_set_fills), typed("boolean")),
("strokes", property(l, options_strokes, options_set_strokes), typed("boolean")),
("maxColors", property(l, options_max_colors, options_set_max_colors), MemberInfo { min: Some(2.0), max: Some(256.0), ..typed("number") }),
("palette", property(l, options_palette, options_set_palette), typed("string")),
("ignoreWhite", property(l, options_ignore_white, options_set_ignore_white), typed("boolean")),
("minArea", property(l, options_min_area, options_set_min_area), typed("number")),
("viewRaster", property(l, options_view_raster, options_set_view_raster), typed("ViewRasterType")),
("viewVector", property(l, options_view_vector, options_set_view_vector), typed("ViewVectorType")),
("loadFromPreset", method(l, options_load), returns("boolean", &[("presetName", "string")])),
("storeToPreset", method(l, options_store), returns("boolean", &[("presetName", "string")])),
]);
options.extend(NOT_IMPLEMENTED.iter().map(|m| missing(l, m)));
vec![
class("PluginItem", Some("PageItem"), plugin, None),
class("TracingObject", None, tracing, None),
class("TracingOptions", None, options, None),
]
}