mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge main into feat/scripts-api-d8-placed-raster
This commit is contained in:
commit
b47eaf582c
65 files changed
+5095
-362
No files matched your search
+183
-49
@@ -102,6 +102,7 @@ mod print;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
mod tracing;
|
||||
mod variables;
|
||||
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
@@ -128,6 +129,10 @@ pub(crate) use paths::POINT_LOOKS;
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
/// The error for an object that was deleted, or that came from an earlier run.
|
||||
pub const STALE_ITEM: &str = "Stale page item";
|
||||
/// The error for a new name given to a `PluginItem`.
|
||||
const TRACING_NAME: &str = "The name of a tracing cannot be changed";
|
||||
/// The error for the tracing's name given to a group that holds an image first.
|
||||
const NOT_A_TRACING: &str = "Only Image Trace can make a tracing";
|
||||
/// The error for a document that was closed, or that came from an earlier run.
|
||||
pub const STALE_DOCUMENT: &str = "Stale document";
|
||||
/// The error of `index` and `getByName` when nothing matches.
|
||||
@@ -159,6 +164,7 @@ const ITEM_CLASSES: &[&str] = &[
|
||||
"RepeatItem",
|
||||
"PlacedDocumentItem",
|
||||
"IntertwineItem",
|
||||
"PluginItem",
|
||||
];
|
||||
|
||||
/// `app.coordinateSystem`.
|
||||
@@ -215,11 +221,13 @@ pub(super) struct State {
|
||||
printing: print::State,
|
||||
text: text::TextState,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
/// What the placed and raster items keep ([`images::State`]).
|
||||
images: images::State,
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
vars: variables::Handles,
|
||||
/// What the placed and raster items keep ([`images::State`]).
|
||||
images: images::State,
|
||||
/// What the tracings keep ([`tracing::State`]).
|
||||
tracing: tracing::State,
|
||||
tool: Cell<Option<&'static str>>,
|
||||
}
|
||||
|
||||
@@ -446,7 +454,7 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
|
||||
"Document" => {
|
||||
doc_of(&h, arg(&a, 0), "Document")?;
|
||||
}
|
||||
"PageItem" | "PathItem" | "PlacedItem" | "RasterItem" | "TextFrame" => {
|
||||
"PageItem" | "PathItem" | "TextFrame" | "PlacedItem" | "RasterItem" => {
|
||||
item_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
"PathPoint" => {
|
||||
@@ -594,12 +602,17 @@ fn item_of(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
};
|
||||
let (doc, id) = match handle.as_slice() {
|
||||
[_, _, _, _, _] => node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?,
|
||||
[run, uid, _, _, reverts, slot] => images::pending_item(h, *run, *uid, *reverts, *slot)?,
|
||||
&[run, uid, _, _, _, slot] => {
|
||||
let id = images::pending_id(h, run, uid, slot)?;
|
||||
(find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?, id)
|
||||
}
|
||||
_ => return Err(HostError::Type("this is not a page item".into())),
|
||||
};
|
||||
let original = id;
|
||||
let id = if class == "PluginItem" { tracing::follow(h, doc.uid, id) } else { id };
|
||||
let s = h.session.borrow();
|
||||
let st = &s.documents()[doc.index];
|
||||
if st.doc.node(id).is_none_or(|n| typename(n) != Some(class)) {
|
||||
if st.doc.node(id).is_none_or(|n| typename(n) != Some(class) || (class == "PluginItem" && !tracing::same_source(h, doc.uid, original, n))) {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
}
|
||||
Ok(Item { doc, id })
|
||||
@@ -610,6 +623,7 @@ fn typename(n: &crate::doc::Node) -> Option<&'static str> {
|
||||
Some(match &n.kind {
|
||||
NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None,
|
||||
NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem",
|
||||
NodeKind::Group { .. } if crate::cmd::is_trace_group(n) => "PluginItem",
|
||||
NodeKind::Group { .. } => "GroupItem",
|
||||
NodeKind::Path { .. } => "PathItem",
|
||||
NodeKind::Compound { .. } => "CompoundPathItem",
|
||||
@@ -633,6 +647,11 @@ fn doc_ref(h: &Host, uid: u64) -> Data {
|
||||
fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
match st.doc.node(id) {
|
||||
Some(n) => match typename(n) {
|
||||
Some("PlacedItem") => images::bound_ref(h, st, id).unwrap_or_else(|| host_ref("PlacedItem", &node_handle(h, st, id))),
|
||||
Some("PluginItem") => {
|
||||
tracing::remember_source(h, st.uid, n);
|
||||
host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id)))
|
||||
}
|
||||
Some(t) => host_ref(t, &node_handle(h, st, id)),
|
||||
None => host_ref("Layer", &node_handle(h, st, id)),
|
||||
},
|
||||
@@ -656,7 +675,10 @@ fn page_items(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, H
|
||||
_ => {
|
||||
out.push(n.id);
|
||||
if let Some(children) = n.children() {
|
||||
walk(children, out);
|
||||
// The source image an Image Trace object keeps hidden as its first child is
|
||||
// reached through that object's `tracing`.
|
||||
let source = usize::from(crate::cmd::is_trace_group(n));
|
||||
walk(children.get(source..).unwrap_or_default(), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -693,9 +715,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.
|
||||
@@ -2314,6 +2338,28 @@ fn item_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
// An Image Trace object is known by its name, so renaming one would end the tracing, and giving
|
||||
// an ordinary group that holds an image first the tracing's name would make it one.
|
||||
let item = this_item(h, a)?;
|
||||
let refused = with_doc(h, item.doc, |_, st| {
|
||||
st.doc.node(item.id).and_then(|n| {
|
||||
let tracing = crate::cmd::is_trace_group(n);
|
||||
let would_trace = !tracing
|
||||
&& name == crate::cmd::TRACE_NAME
|
||||
&& matches!(n.kind, crate::doc::NodeKind::Group { clip: false, .. })
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, crate::doc::NodeKind::Image(_))));
|
||||
if tracing && n.name.as_deref() != Some(&**name) {
|
||||
Some(TRACING_NAME)
|
||||
} else if would_trace {
|
||||
Some(NOT_A_TRACING)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
});
|
||||
if let Some(msg) = refused {
|
||||
return Err(HostError::Error(msg.into()));
|
||||
}
|
||||
set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name}))
|
||||
}
|
||||
|
||||
@@ -2509,24 +2555,26 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
|
||||
bounds(h, a, true)
|
||||
}
|
||||
|
||||
/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in
|
||||
/// the object.
|
||||
/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an
|
||||
/// object with nothing in it.
|
||||
fn item_control(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
// An object with nothing in it reads zeros, as its other bounds do.
|
||||
let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) };
|
||||
let r = with_doc(h, item.doc, |_, st| {
|
||||
let mut r = r;
|
||||
if let Some(n) = st.doc.node(item.id) {
|
||||
n.walk(&mut |c| {
|
||||
if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) {
|
||||
r = r.union(handles);
|
||||
}
|
||||
});
|
||||
}
|
||||
r
|
||||
});
|
||||
Ok(f.bounds(h.dom.coords.get(), r))
|
||||
let (r, f) = item_rect(h, item, true)?;
|
||||
let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds));
|
||||
match r.into_iter().chain(handles).reduce(|a, b| a.union(b)) {
|
||||
Some(r) => Ok(f.bounds(h.dom.coords.get(), r)),
|
||||
None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown
|
||||
/// paths in its children (a clip group's from its clipping path).
|
||||
fn handle_bounds(n: &crate::doc::Node) -> Option<Rect> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.control_bounds(),
|
||||
NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)),
|
||||
_ => n.children().and_then(|children| children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b))),
|
||||
}
|
||||
}
|
||||
|
||||
fn item_position(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -2695,6 +2743,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
// An image left first in an ordinary group named as a tracing would make that group one.
|
||||
if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
// A compound path whose last path this is stays, empty, as it does after `move`.
|
||||
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?;
|
||||
Ok(Data::Undefined)
|
||||
@@ -2748,21 +2800,18 @@ struct Destination {
|
||||
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
|
||||
let how = placement_of(how)?;
|
||||
let beside = matches!(how, Placement::Above | Placement::Below);
|
||||
let pending = images::pending_as_item(h, target)?.map(|p| p.to_vec());
|
||||
let is_pending = pending.is_some();
|
||||
let handle = pending.or_else(|| handle_of(target, "PageItem")).or_else(|| handle_of(target, "Layer"));
|
||||
let Some(handle) = handle.filter(|parts| parts.len() == 5) else {
|
||||
if handle_of(target, "Document").is_some() {
|
||||
return Err(HostError::Error("a document as the relative object is not available yet".into()));
|
||||
}
|
||||
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
|
||||
};
|
||||
let (doc, target) = if is_pending || handle_of(target, "PageItem").is_some() {
|
||||
// A page item, an `add()` result included, must still be of its class: an embedded
|
||||
// `PlacedItem`'s old object is stale.
|
||||
let it = item_of(h, target)?;
|
||||
(it.doc, it.id)
|
||||
// A page item is looked up as its class names it (a wrapper whose object changed class is
|
||||
// stale), a layer by its handle.
|
||||
let (doc, target) = if handle_of(target, "PageItem").is_some() {
|
||||
let t = item_of(h, target)?;
|
||||
(t.doc, t.id)
|
||||
} else {
|
||||
let Some(handle) = handle_of(target, "Layer").filter(|parts| parts.len() == 5) else {
|
||||
if handle_of(target, "Document").is_some() {
|
||||
return Err(HostError::Error("a document as the relative object is not available yet".into()));
|
||||
}
|
||||
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
|
||||
};
|
||||
node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?
|
||||
};
|
||||
if doc.uid != item.doc.uid {
|
||||
@@ -2804,17 +2853,64 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
|
||||
let name = d.node(item.id).and_then(typename).unwrap_or("page item");
|
||||
return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0)));
|
||||
}
|
||||
// Checked here as well as in `place`, so `duplicate` refuses before it makes the copy. A
|
||||
// tracing's source image moved out keeps the error `place` gives it.
|
||||
let image = d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)));
|
||||
if image && (copy || !crate::cmd::is_trace_source(d, item.id)) && named_as_tracing(d, parent) {
|
||||
// Where the image comes from: its index in `parent` when it is already there.
|
||||
let own = d.position(item.id).and_then(|(p, i, _)| (p == Some(parent)).then_some(i)).filter(|_| !copy);
|
||||
let count = d.children(Some(parent)).map_or(0, Vec::len);
|
||||
let first = match how {
|
||||
Placement::Bottom => true,
|
||||
Placement::Top => count == usize::from(own.is_some()),
|
||||
Placement::Below => beside.and_then(|b| d.position(b)).is_some_and(|(_, i, _)| i == 0 || (i == 1 && own == Some(0))),
|
||||
Placement::Above => false,
|
||||
};
|
||||
if first {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
}
|
||||
Ok(Destination { parent, beside, how })
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `id` is an ordinary group named as an Image Trace object that is not one: an image put
|
||||
/// first in it would make it a tracing.
|
||||
fn named_as_tracing(d: &Document, id: NodeId) -> bool {
|
||||
d.node(id).is_some_and(|p| {
|
||||
!crate::cmd::is_trace_group(p) && matches!(p.kind, NodeKind::Group { clip: false, .. }) && p.name.as_deref() == Some(crate::cmd::TRACE_NAME)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether taking the object `id` out of `parent` and, with `at`, putting it back at that index of
|
||||
/// what is left would make `parent`, an ordinary group named as a tracing, one: an image first in it.
|
||||
fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option<usize>) -> bool {
|
||||
if !named_as_tracing(d, parent) {
|
||||
return false;
|
||||
}
|
||||
let image = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Image(_));
|
||||
let rest = d.children(Some(parent)).map(|c| c.iter().filter(|n| n.id != id).collect::<Vec<_>>()).unwrap_or_default();
|
||||
match at {
|
||||
Some(0) => d.node(id).is_some_and(image),
|
||||
_ => rest.first().is_some_and(|n| image(n)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place.
|
||||
fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> {
|
||||
let index = with_doc(h, doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let from = d.position(id);
|
||||
let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent)));
|
||||
let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0;
|
||||
// A clip group's first child is its clipping path, and an Image Trace object's its source
|
||||
// image: both stay first, and the source image moved within its own tracing stays where it is.
|
||||
if crate::cmd::is_trace_source(d, id) {
|
||||
if d.parent_of(id) == Some(to.parent) {
|
||||
return Ok(0);
|
||||
}
|
||||
return Err(HostError::Error("a tracing's source image cannot leave its tracing".into()));
|
||||
}
|
||||
let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0;
|
||||
let at = match (to.how, to.beside) {
|
||||
(Placement::Top, _) => count,
|
||||
(Placement::Bottom, _) => 0,
|
||||
@@ -2830,7 +2926,14 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
|
||||
}
|
||||
(_, None) => count,
|
||||
};
|
||||
Ok::<_, HostError>(if clips { at.max(1) } else { at })
|
||||
let at = if clips { at.max(1) } else { at };
|
||||
// An image left or put first in an ordinary group named as a tracing would make that group
|
||||
// one, in the group it leaves as in the group it goes into.
|
||||
let left = from.and_then(|(p, ..)| p).filter(|p| *p != to.parent);
|
||||
if makes_tracing(d, to.parent, id, Some(at)) || left.is_some_and(|p| makes_tracing(d, p, id, None)) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
Ok::<_, HostError>(at)
|
||||
})?;
|
||||
let now = with_doc(h, doc, |_, st| st.doc.position(id));
|
||||
if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) {
|
||||
@@ -2925,22 +3028,50 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
// The Arrange commands keep a clipping path at the bottom of its parent and the art below the
|
||||
// parent's ruler guides, so the item's place is counted among the art above the clipping path.
|
||||
let (before, floor, art) = with_doc(h, item.doc, |_, st| {
|
||||
// The source image an Image Trace object keeps first stays first, and the other objects in it
|
||||
// stay above it.
|
||||
let (before, floor, art, parent, source, in_trace) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let at = d.position(item.id);
|
||||
let parent = at.and_then(|(p, ..)| p);
|
||||
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips));
|
||||
let in_trace = parent.and_then(|p| d.node(p)).is_some_and(crate::cmd::is_trace_group);
|
||||
let clips = parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips);
|
||||
let floor = usize::from(clips || in_trace);
|
||||
let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c));
|
||||
(at.map(|(_, i, _)| i), floor, art)
|
||||
(at.map(|(_, i, _)| i), floor, art, parent, crate::cmd::is_trace_source(d, item.id), in_trace)
|
||||
});
|
||||
let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) };
|
||||
if source {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let unchanged = i < floor
|
||||
|| match id {
|
||||
"object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art,
|
||||
_ => i <= floor,
|
||||
};
|
||||
if !unchanged {
|
||||
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
|
||||
if unchanged {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
// Where the Arrange command puts the item among its parent's art, worked out as
|
||||
// `object.arrange` works it out for one object. An image put first, or another object moved
|
||||
// from above an image that becomes first, in an ordinary group named as a tracing would make
|
||||
// that group one.
|
||||
let to = match id {
|
||||
"object.arrange.bringToFront" => art - 1,
|
||||
"object.arrange.bringForward" => i + 1,
|
||||
"object.arrange.sendBackward" => i - 1,
|
||||
_ => floor,
|
||||
};
|
||||
if parent.is_some_and(|p| with_doc(h, item.doc, |_, st| makes_tracing(&st.doc, p, item.id, Some(to)))) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
match parent {
|
||||
Some(p) if in_trace && id == "object.arrange.sendToBack" => {
|
||||
edit_item(h, item, "node.move", &json!({"id": item.id.0, "parent": p.0, "index": floor}))?;
|
||||
}
|
||||
_ => {
|
||||
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
|
||||
}
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -3045,7 +3176,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(images::ENUMS).chain(print::ENUMS) {
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
@@ -3166,8 +3297,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(images::document_members(l));
|
||||
document.extend(print::document_members(l));
|
||||
document.extend(images::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
@@ -3266,18 +3397,21 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
);
|
||||
page_item.extend(variables::page_item_members(l));
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame" && !images::CLASSES.contains(c)).map(|c| {
|
||||
let own = |c: &&&str| **c == "TextFrame" || images::CLASSES.contains(c) || tracing::CLASSES.contains(c);
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| {
|
||||
let mut members = variables::item_members(l, c);
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
}
|
||||
class(c, Some("PageItem"), members, None)
|
||||
}));
|
||||
classes.extend(images::classes(l));
|
||||
classes.extend(paths::classes(l));
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(images::classes(l));
|
||||
tracing::add_trace(&mut classes, l);
|
||||
classes.extend(tracing::classes(l));
|
||||
classes.extend(save_open::classes(l));
|
||||
classes.extend(print::classes(l));
|
||||
classes.push(class(
|
||||
|
||||
@@ -42,9 +42,9 @@ use vectorcraft_geom::{Affine, Point};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, file_ref, file_ref_path, host_ref, host_ref_parts};
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref,
|
||||
edit_item, editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, returns, text,
|
||||
typed, typename_of, whole, with_doc,
|
||||
Answer, Coords, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, command_value,
|
||||
doc_of, doc_ref, edit_item, editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property,
|
||||
returns, text, typed, typename_of, variables, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
|
||||
@@ -88,22 +88,29 @@ pub(super) struct State {
|
||||
lists: RefCell<Option<Lists>>,
|
||||
}
|
||||
|
||||
/// A `PlacedItems.add()` result: its document, and its image once `file` placed one.
|
||||
/// A `PlacedItems.add()` result: its document, how many times that document had been reverted then,
|
||||
/// and its image once `file` placed one.
|
||||
struct Pending {
|
||||
uid: u64,
|
||||
reverts: u64,
|
||||
bound: Option<NodeId>,
|
||||
}
|
||||
|
||||
/// The slot of a `PlacedItems.add()` result in this run, from its handle.
|
||||
pub(super) fn bound_ref(h: &Host, st: &DocState, id: NodeId) -> Option<Data> {
|
||||
let pending = h.dom.images.pending.borrow();
|
||||
let slot = pending.iter().position(|p| p.uid == st.uid && p.reverts == st.reverts && p.bound == Some(id))?;
|
||||
Some(host_ref("PlacedItem", &[float(h.run), float(st.uid), 0.0, 0.0, float(st.reverts), float(slot as u64)]))
|
||||
}
|
||||
|
||||
/// The slot of a `PlacedItems.add()` result in this run, from its handle. A result whose document
|
||||
/// was closed or reverted since is stale.
|
||||
fn slot_of(h: &Host, run: f64, uid: f64, slot: f64) -> Result<usize, HostError> {
|
||||
let stale = || HostError::Error(STALE_ITEM.into());
|
||||
if whole(run) != Some(h.run) {
|
||||
return Err(stale());
|
||||
}
|
||||
let doc = find_doc(h, run, uid).ok_or_else(stale)?;
|
||||
let reverts = h.session.borrow().documents().get(doc.index).map(|st| st.reverts);
|
||||
let k = whole(slot).and_then(|k| usize::try_from(k).ok()).ok_or_else(stale)?;
|
||||
let uid = whole(uid).ok_or_else(stale)?;
|
||||
match h.dom.images.pending.borrow().get(k) {
|
||||
Some(p) if p.uid == uid => Ok(k),
|
||||
Some(p) if p.uid == doc.uid && Some(p.reverts) == reverts => Ok(k),
|
||||
_ => Err(stale()),
|
||||
}
|
||||
}
|
||||
@@ -117,47 +124,20 @@ pub(super) fn pending_id(h: &Host, run: f64, uid: f64, slot: f64) -> Result<Node
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle's run, uid, the document's revert count and slot when `d` is a `PlacedItems.add()`
|
||||
/// result. Its handle has six numbers, where a page item's has five.
|
||||
fn pending_handle(d: &Data) -> Option<[f64; 4]> {
|
||||
/// The handle's run, uid and slot when `d` is a `PlacedItems.add()` result. Its handle has six
|
||||
/// numbers, where a page item's has five.
|
||||
fn pending_handle(d: &Data) -> Option<[f64; 3]> {
|
||||
match host_ref_parts(d) {
|
||||
Some(("PlacedItem", handle)) => match handle.as_slice() {
|
||||
[run, uid, _, _, reverts, slot] => Some([*run, *uid, *reverts, *slot]),
|
||||
[run, uid, _, _, _, slot] => Some([*run, *uid, *slot]),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The document and the id of the image a `PlacedItems.add()` result placed. The result is stale
|
||||
/// once its document is closed or reverted.
|
||||
pub(super) fn pending_item(h: &Host, run: f64, uid: f64, reverts: f64, slot: f64) -> Result<(Doc, NodeId), HostError> {
|
||||
let doc = pending_doc(h, run, uid, reverts)?;
|
||||
Ok((doc, pending_id(h, run, uid, slot)?))
|
||||
}
|
||||
|
||||
/// The document of a `PlacedItems.add()` result, which is stale once the document is closed or
|
||||
/// reverted.
|
||||
fn pending_doc(h: &Host, run: f64, uid: f64, reverts: f64) -> Result<Doc, HostError> {
|
||||
let stale = || HostError::Error(STALE_ITEM.into());
|
||||
let doc = find_doc(h, run, uid).ok_or_else(stale)?;
|
||||
if h.session.borrow().documents().get(doc.index).is_none_or(|st| whole(reverts) != Some(st.reverts)) {
|
||||
return Err(stale());
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// The page item handle (run, uid, the two halves of the id and the document's revert count) of
|
||||
/// the image a `PlacedItems.add()` result `d` placed, or `None` when `d` is not such a result.
|
||||
pub(super) fn pending_as_item(h: &Host, d: &Data) -> Result<Option<[f64; 5]>, HostError> {
|
||||
let Some([run, uid, reverts, slot]) = pending_handle(d) else { return Ok(None) };
|
||||
let (_, id) = pending_item(h, run, uid, reverts, slot)?;
|
||||
let [high, low] = super::id_parts(id);
|
||||
Ok(Some([run, uid, high, low, reverts]))
|
||||
}
|
||||
|
||||
/// The ids of a document's linked (`placed`) or embedded images, topmost first, in the order of
|
||||
/// `pageItems`.
|
||||
/// The ids of a document's linked (`placed`) or embedded images, topmost first as [`page_items`]
|
||||
/// lists them.
|
||||
fn images(h: &Host, st: &DocState, placed: bool) -> Result<Rc<Vec<NodeId>>, HostError> {
|
||||
let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() };
|
||||
if let Some(l) = &*h.dom.images.lists.borrow()
|
||||
@@ -187,14 +167,6 @@ fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> {
|
||||
}
|
||||
}
|
||||
|
||||
fn id_value(d: Option<&Data>) -> Option<NodeId> {
|
||||
match d {
|
||||
Some(Data::Number(n)) => whole(*n).map(NodeId),
|
||||
Some(Data::Array(a)) => id_value(a.first()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- PlacedItems and RasterItems ----
|
||||
|
||||
fn collection(placed: bool) -> &'static str {
|
||||
@@ -270,12 +242,12 @@ fn list_remove_all(h: &Host, a: &[Data], placed: bool) -> Answer {
|
||||
/// `PlacedItems.add()`: a placed item with no file yet, which assigning `file` places.
|
||||
fn placed_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = list_doc(h, a, true)?;
|
||||
let reverts = h.session.borrow().documents().get(doc.index).map_or(0, |st| st.reverts);
|
||||
let mut pending = h.dom.images.pending.borrow_mut();
|
||||
if pending.len() >= MAX_PENDING {
|
||||
return Err(HostError::Range(format!("a run makes at most {MAX_PENDING} placed items with PlacedItems.add")));
|
||||
}
|
||||
let reverts = h.session.borrow().documents().get(doc.index).map_or(0, |st| st.reverts);
|
||||
pending.push(Pending { uid: doc.uid, bound: None });
|
||||
pending.push(Pending { uid: doc.uid, reverts, bound: None });
|
||||
Ok(host_ref("PlacedItem", &[float(h.run), float(doc.uid), 0.0, 0.0, float(reverts), float(pending.len() as u64 - 1)]))
|
||||
}
|
||||
|
||||
@@ -381,14 +353,22 @@ fn read_image(h: &Host, a: &[Data], cls: &str, f: impl FnOnce(&DocState, &crate:
|
||||
}
|
||||
|
||||
fn placed_file(h: &Host, a: &[Data]) -> Answer {
|
||||
if let Some([run, uid, reverts, slot]) = pending_handle(arg(a, 0)) {
|
||||
pending_doc(h, run, uid, reverts)?;
|
||||
if let Some([run, uid, slot]) = pending_handle(arg(a, 0)) {
|
||||
let k = slot_of(h, run, uid, slot)?;
|
||||
if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_none()) {
|
||||
// Null while its document is open; stale once that document is closed.
|
||||
find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
return Ok(Data::Null);
|
||||
}
|
||||
}
|
||||
let path = read_image(h, a, "PlacedItem", |_, _, im| Ok(text(im.link.as_ref().map(|l| l.path.clone()).unwrap_or_default())))?;
|
||||
let path = read_image(h, a, "PlacedItem", |st, _, im| {
|
||||
let path = im.link.as_ref().and_then(|link| {
|
||||
let base = crate::cmd::links::LinkBase::of(st);
|
||||
crate::cmd::links::located_path(link, base).or_else(|| crate::cmd::fileio::document_path(&link.path, base.doc).ok())
|
||||
});
|
||||
let path = path.ok_or_else(|| HostError::Error(super::super::files::ACCESS_DENIED.into()))?;
|
||||
Ok(text(path))
|
||||
})?;
|
||||
let Data::String(path) = path else { return Ok(Data::Null) };
|
||||
if !may_read(h, &path) {
|
||||
return Err(HostError::Error(super::super::files::ACCESS_DENIED.into()));
|
||||
@@ -398,7 +378,7 @@ fn placed_file(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// `file = File`: places the file, linked, for a `PlacedItems.add()` result that has none.
|
||||
fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some([run, uid, reverts, slot]) = pending_handle(arg(a, 0)) else {
|
||||
let Some([run, uid, slot]) = pending_handle(arg(a, 0)) else {
|
||||
if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PlacedItem") {
|
||||
this_of(h, a, "PlacedItem")?;
|
||||
return Err(HostError::Error(FILE_READ_ONLY.into()));
|
||||
@@ -410,29 +390,24 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
|
||||
this_of(h, a, "PlacedItem")?;
|
||||
return Err(HostError::Error(FILE_READ_ONLY.into()));
|
||||
}
|
||||
let doc = pending_doc(h, run, uid, reverts)?;
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let path = image_path(h, arg(a, 1), "PlacedItem.file")?;
|
||||
let placed = on_doc(h, doc.uid, true, |h| command(h, "file.place", &json!({"path": path, "link": true})))?;
|
||||
let ids: Vec<u64> = match field(&placed, "ids") {
|
||||
Some(Data::Array(ids)) => ids.iter().filter_map(|d| id_value(Some(d))).map(|i| i.0).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let id = id_value(field(&placed, "image")).or_else(|| id_value(field(&placed, "ids")));
|
||||
let linked = |id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some()));
|
||||
match id.filter(|id| linked(*id)) {
|
||||
Some(id) => {
|
||||
if let Some(p) = h.dom.images.pending.borrow_mut().get_mut(k) {
|
||||
p.bound = Some(id);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
None => {
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids})))?;
|
||||
}
|
||||
Err(HostError::Error(NOT_AN_IMAGE.into()))
|
||||
}
|
||||
// The ids are read from the command's own result, where every id is exact (a script number
|
||||
// holds integers exactly only up to 2^53).
|
||||
// The placement and its check run under one savepoint, so an error after the place leaves
|
||||
// no linked image behind.
|
||||
let id = super::atomically(h, |h| {
|
||||
let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?;
|
||||
let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64));
|
||||
let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId);
|
||||
let linked =
|
||||
|id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some()));
|
||||
id.filter(|id| linked(*id)).ok_or_else(|| HostError::Error(NOT_AN_IMAGE.into()))
|
||||
})?;
|
||||
if let Some(p) = h.dom.images.pending.borrow_mut().get_mut(k) {
|
||||
p.bound = Some(id);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `relink(file)`: `links.relink` of the item to the image in `file`.
|
||||
@@ -450,11 +425,8 @@ fn placed_embed(h: &Host, a: &[Data]) -> Answer {
|
||||
if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") {
|
||||
return Err(HostError::Error(MISSING_LINK.into()));
|
||||
}
|
||||
let r = edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?;
|
||||
let embedded = match field(&r, "embedded") {
|
||||
Some(Data::Array(ids)) => ids.iter().any(|d| id_value(Some(d)) == Some(item.id)),
|
||||
_ => false,
|
||||
};
|
||||
edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?;
|
||||
let embedded = with_doc(h, item.doc, |_, st| matches!(st.doc.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()));
|
||||
if !embedded {
|
||||
return Err(HostError::Error(MISSING_LINK.into()));
|
||||
}
|
||||
@@ -723,8 +695,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("matrix", property(l, placed_matrix, placed_set_matrix), typed("Matrix")),
|
||||
("boundingBox", get(l, placed_box), typed("Array")),
|
||||
]);
|
||||
placed.extend(super::variables::item_members(l, "PlacedItem"));
|
||||
placed.push(later(l, "PlacedItem", "trace"));
|
||||
placed.extend(variables::item_members(l, "PlacedItem"));
|
||||
let mut raster = named(vec![
|
||||
("bitsPerChannel", get(l, raster_bits), typed("number")),
|
||||
("channels", get(l, raster_channels), typed("number")),
|
||||
@@ -737,8 +708,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("transparent", get(l, raster_transparent), typed("boolean")),
|
||||
("boundingBox", get(l, raster_box), typed("Array")),
|
||||
]);
|
||||
raster.extend(super::variables::item_members(l, "RasterItem"));
|
||||
raster.extend(["colorants", "colorize", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m)));
|
||||
raster.extend(variables::item_members(l, "RasterItem"));
|
||||
raster.extend(["colorants", "colorize", "overprint"].into_iter().map(|m| later(l, "RasterItem", m)));
|
||||
vec![
|
||||
class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))),
|
||||
class("RasterItems", None, raster_list, Some(super::function(l, raster_at))),
|
||||
|
||||
@@ -196,6 +196,8 @@ enum Default {
|
||||
Member(&'static str, &'static str),
|
||||
/// The help page gives no default: any value throws.
|
||||
Unset,
|
||||
/// White as an `RGBColor`: red, green and blue each 255.
|
||||
White,
|
||||
}
|
||||
|
||||
impl Default {
|
||||
@@ -205,6 +207,11 @@ impl Default {
|
||||
(Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9,
|
||||
(Default::Text(a), Data::String(b)) => a == b,
|
||||
(Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m),
|
||||
(Default::White, Data::Object(items)) => {
|
||||
let get = |k: &str| items.iter().find(|(name, _)| name == k).map(|(_, v)| v);
|
||||
matches!(get("typename"), Some(Data::String(t)) if t == "RGBColor")
|
||||
&& ["red", "green", "blue"].iter().all(|k| matches!(get(k), Some(Data::Number(n)) if *n == 255.0))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -560,7 +567,7 @@ fn png24_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::R
|
||||
raster_map("ExportOptionsPNG24", name, d, p)
|
||||
}
|
||||
|
||||
const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))];
|
||||
const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))];
|
||||
|
||||
fn png24_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
@@ -588,7 +595,7 @@ fn jpeg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Re
|
||||
}
|
||||
|
||||
const JPEG_KEPT: &[(&str, Default)] =
|
||||
&[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))];
|
||||
&[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))];
|
||||
|
||||
fn jpeg_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
@@ -733,7 +740,7 @@ pub(super) fn refused(message: &str, path: &str) -> HostError {
|
||||
|
||||
/// Runs `f` with the commands' reads and writes held to the script's own grants
|
||||
/// ([`super::super::files::Disk::exact`]).
|
||||
pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
|
||||
pub(super) fn exactly<T>(h: &Host, f: impl FnOnce() -> Result<T, HostError>) -> Result<T, HostError> {
|
||||
h.disk.borrow_mut().exact = true;
|
||||
let r = f();
|
||||
h.disk.borrow_mut().exact = false;
|
||||
|
||||
@@ -0,0 +1,928 @@
|
||||
//! Tracing in the script object model: `PlacedItem.trace()` and `RasterItem.trace()`, the
|
||||
//! `PluginItem` an Image Trace object is, its `TracingObject` and its `TracingOptions`, as the help
|
||||
//! pages <https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/> describe them.
|
||||
//!
|
||||
//! An Image Trace object is a group that holds its source image, hidden, as its first object.
|
||||
//! Tracing runs `imageTrace.make`, expanding `imageTrace.expand`, releasing `imageTrace.release`
|
||||
//! and a change of view `imageTrace.setView`, so each joins the run's transaction and its work
|
||||
//! counts against the run's limits.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `trace()` returns once the trace is made, so the counts can be read at once. It traces with
|
||||
//! the Default preset.
|
||||
//! - The traced image stays the same object: `sourceArt` gives it, and `releaseTracing()` gives it
|
||||
//! back. `trace()` on an image that is the source of a tracing throws [`ALREADY_TRACED`], and on
|
||||
//! a linked image whose file is missing throws `Linked image is missing`.
|
||||
//! - `pathCount` counts the traced paths, without the seam fills an Abutting trace adds,
|
||||
//! `anchorCount` their anchor points and `usedColorCount` the different paints they are filled
|
||||
//! and stroked with, as the tracing is when they are read. `areaCount` throws. `imageResolution`
|
||||
//! is the source image's pixels per inch as it is placed; an image placed at a different
|
||||
//! resolution across and down has none.
|
||||
//! - Assigning an option, or `loadFromPreset(name)`, traces again unless the options are already
|
||||
//! so. Tracing again makes a new object: the `PluginItem`, its `TracingObject` and its
|
||||
//! `TracingOptions` follow it. A tracing that another command traced again, expanded or
|
||||
//! released, or whose source image was deleted, is stale.
|
||||
//! - Tracing again throws [`ADDED_ARTWORK`], with nothing changed, when the tracing holds an object
|
||||
//! its trace did not make, whether this run, an earlier run or a command added it, and
|
||||
//! `releaseTracing()` throws [`ADDED_ARTWORK_RELEASE`] in the same case. The tracing records the
|
||||
//! objects its trace made ([`crate::doc::TraceMade`]), and a copy of it records their copies. A
|
||||
//! tracing saved without that record is checked only for objects added in this run.
|
||||
//! - `palette` is `""` for the automatic palette, or `"Limited"`, `"Full Tone"` or
|
||||
//! `"Document Library"`. `minArea` is the Noise setting in pixels: an area smaller than it is not
|
||||
//! traced. `tracingMode` has no value for the Flat Logo mode. The options with no VectorCraft
|
||||
//! setting throw [`not_implemented`].
|
||||
//! - `viewRaster` and `viewVector` take only the pairs of the Image Trace views
|
||||
//! ([`VIEWS`]); the Split view has neither.
|
||||
//! - `storeToPreset(name)` gives `false` for a built-in preset and `Custom`; a script cannot change
|
||||
//! the saved presets, so any other name throws. A preset name has at most [`MAX_PRESET_NAME`]
|
||||
//! bytes and none of `/`, `\`, `:` or control characters.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostMember, MemberInfo, host_ref, host_ref_parts};
|
||||
|
||||
use super::{
|
||||
Answer, Described, Host, Item, Link, STALE_ITEM, arg, boolean, class, command, command_value, edit_item, float, get, item_of, item_ref, method,
|
||||
named, node_of, num, number, on_doc, property, returns, text, typed, typename_of, whole, with_doc,
|
||||
};
|
||||
use crate::doc::{Node, TraceView};
|
||||
use crate::{NodeId, NodeKind};
|
||||
|
||||
/// The error of `trace()` on an image that is the source of a tracing.
|
||||
pub const ALREADY_TRACED: &str = "The image is the source art of a tracing";
|
||||
/// The error of tracing again a tracing that holds an object its trace did not make.
|
||||
pub const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork";
|
||||
/// The error of releasing a tracing that holds an object its trace did not make.
|
||||
pub const ADDED_ARTWORK_RELEASE: &str = "Cannot release a tracing containing added artwork";
|
||||
/// The error of options that trace with neither fills nor strokes.
|
||||
pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes";
|
||||
/// The error of `expandTracing(true)`.
|
||||
pub const VIEWED_EXPAND: &str = "TracingObject.expandTracing(true) is not implemented";
|
||||
/// The longest preset name `loadFromPreset` and `storeToPreset` take, in bytes.
|
||||
pub const MAX_PRESET_NAME: usize = 256;
|
||||
/// The most times one run traces a tracing again through its options.
|
||||
pub const MAX_RETRACES: usize = 10_000;
|
||||
/// The largest `minArea`: the most pixels the tracer traces ([`vectorcraft_trace::MAX_PIXELS`]).
|
||||
pub const MAX_MIN_AREA: u64 = vectorcraft_trace::MAX_PIXELS;
|
||||
|
||||
/// The enumerations the members here give values of, as the help page
|
||||
/// <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/> lists them.
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("TracingModeType", &["TRACINGMODEBLACKANDWHITE", "TRACINGMODECOLOR", "TRACINGMODEGRAY"]),
|
||||
(
|
||||
"ViewRasterType",
|
||||
&["TRACINGVIEWRASTERADJUSTEDIMAGE", "TRACINGVIEWRASTERNOIMAGE", "TRACINGVIEWRASTERORIGINALIMAGE", "TRACINGVIEWRASTERTRANSPARENTIMAGE"],
|
||||
),
|
||||
(
|
||||
"ViewVectorType",
|
||||
&["TRACINGVIEWVECTORNOTRACINGRESULT", "TRACINGVIEWVECTOROUTLINES", "TRACINGVIEWVECTOROUTLINESWITHTRACING", "TRACINGVIEWVECTORTRACINGRESULT"],
|
||||
),
|
||||
];
|
||||
|
||||
/// The classes this module defines.
|
||||
pub(super) const CLASSES: &[&str] = &["PluginItem"];
|
||||
|
||||
/// Each Image Trace view with the `viewRaster` and `viewVector` that give it.
|
||||
const VIEWS: &[(TraceView, &str, &str)] = &[
|
||||
(TraceView::Result, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"),
|
||||
(TraceView::ResultWithOutlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINESWITHTRACING"),
|
||||
(TraceView::Outlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"),
|
||||
(TraceView::OutlinesWithSource, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"),
|
||||
(TraceView::Source, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTORNOTRACINGRESULT"),
|
||||
];
|
||||
|
||||
/// Each `tracingMode` with its Image Trace mode.
|
||||
const MODES: &[(&str, &str)] = &[
|
||||
("TracingModeType.TRACINGMODEBLACKANDWHITE", "blackAndWhite"),
|
||||
("TracingModeType.TRACINGMODEGRAY", "grayscale"),
|
||||
("TracingModeType.TRACINGMODECOLOR", "color"),
|
||||
];
|
||||
|
||||
/// Each `palette` name with its Image Trace palette.
|
||||
const PALETTES: &[(&str, &str)] = &[("", "automatic"), ("Limited", "limited"), ("Full Tone", "fullTone"), ("Document Library", "documentLibrary")];
|
||||
|
||||
/// The options with no VectorCraft setting.
|
||||
const NOT_IMPLEMENTED: &[&str] = &[
|
||||
"cornerAngle",
|
||||
"livePaintOutput",
|
||||
"maxStrokeWeight",
|
||||
"minStrokeLength",
|
||||
"outputToSwatches",
|
||||
"pathFitting",
|
||||
"preprocessBlur",
|
||||
"resample",
|
||||
"resampleResolution",
|
||||
];
|
||||
|
||||
/// What a run keeps for tracings: for each document uid and Image Trace object a script traced
|
||||
/// again through its options, the id of the object that replaced it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
next: RefCell<HashMap<(u64, u64), u64>>,
|
||||
/// `next` the other way round: for each replacing object, the object it replaced.
|
||||
prev: RefCell<HashMap<(u64, u64), u64>>,
|
||||
sources: RefCell<HashMap<(u64, u64), NodeId>>,
|
||||
descendants: RefCell<HashMap<(u64, u64), HashSet<NodeId>>>,
|
||||
retraces: Cell<usize>,
|
||||
}
|
||||
|
||||
/// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put
|
||||
/// it back put back the same object), else the first object the document holds among those that
|
||||
/// replaced it, one after the other, when this run traced it again (an Undo can put back one of
|
||||
/// them), else the last of them, else `id`.
|
||||
pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId {
|
||||
let s = h.session.borrow();
|
||||
let doc = s.documents().iter().find(|d| d.uid == uid);
|
||||
let held = |id: NodeId| doc.is_some_and(|d| d.doc.node(id).is_some());
|
||||
let next = h.dom.tracing.next.borrow();
|
||||
let mut id = id;
|
||||
// Each object is replaced by one made later, so the steps end; the bound holds them anyway.
|
||||
for _ in 0..=next.len() {
|
||||
if held(id) {
|
||||
return id;
|
||||
}
|
||||
match next.get(&(uid, id.0)) {
|
||||
Some(n) => id = NodeId(*n),
|
||||
None => return id,
|
||||
}
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// The first object of the run's chain of replacements that leads to `id` in the document `uid`,
|
||||
/// so every handle to a tracing traced again names the same object; `id` when no earlier object
|
||||
/// in the chain resolves to it.
|
||||
pub(super) fn origin(h: &Host, uid: u64, id: NodeId) -> NodeId {
|
||||
let first = {
|
||||
let prev = h.dom.tracing.prev.borrow();
|
||||
let mut first = id;
|
||||
// Each object replaces one made before it, so the steps end; the bound holds them anyway.
|
||||
for _ in 0..prev.len() {
|
||||
match prev.get(&(uid, first.0)) {
|
||||
Some(old) => first = NodeId(*old),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
first
|
||||
};
|
||||
if first != id && follow(h, uid, first) == id { first } else { id }
|
||||
}
|
||||
|
||||
/// Records that `new` replaced `old` in the document `uid`.
|
||||
fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) {
|
||||
let mut prev = h.dom.tracing.prev.borrow_mut();
|
||||
// A second replacement of `old` takes the place of the first in both directions.
|
||||
if let Some(earlier) = h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0)
|
||||
&& prev.get(&(uid, earlier)) == Some(&old.0)
|
||||
{
|
||||
prev.remove(&(uid, earlier));
|
||||
}
|
||||
prev.insert((uid, new.0), old.0);
|
||||
}
|
||||
|
||||
pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) {
|
||||
let mut first = true;
|
||||
if let Some(source) = group.children().and_then(|c| c.first()) {
|
||||
let mut sources = h.dom.tracing.sources.borrow_mut();
|
||||
first = !sources.contains_key(&(uid, group.id.0));
|
||||
sources.entry((uid, group.id.0)).or_insert(source.id);
|
||||
}
|
||||
// Only a tracing saved without the record of the objects its trace made needs the snapshot,
|
||||
// taken the first time this run sees it.
|
||||
if !first || group.trace_made().is_some() {
|
||||
return;
|
||||
}
|
||||
h.dom.tracing.descendants.borrow_mut().entry((uid, group.id.0)).or_insert_with(|| {
|
||||
let mut ids = HashSet::new();
|
||||
group.walk(&mut |n| {
|
||||
if n.id != group.id {
|
||||
ids.insert(n.id);
|
||||
}
|
||||
});
|
||||
ids
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool {
|
||||
let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied();
|
||||
source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source))
|
||||
}
|
||||
|
||||
/// The error of a member with no VectorCraft setting.
|
||||
pub fn not_implemented(class: &str, name: &str) -> String {
|
||||
format!("{class}.{name} is not implemented")
|
||||
}
|
||||
|
||||
fn out_of_range(name: &str, range: &str) -> HostError {
|
||||
HostError::Range(format!("TracingOptions.{name} is out of range: {range}"))
|
||||
}
|
||||
|
||||
fn invalid(name: &str) -> HostError {
|
||||
HostError::Error(format!("TracingOptions.{name} has an invalid value"))
|
||||
}
|
||||
|
||||
fn stale() -> HostError {
|
||||
HostError::Error(STALE_ITEM.into())
|
||||
}
|
||||
|
||||
fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> {
|
||||
match d {
|
||||
Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first id of a command's result `key`: a number or a list of them, read exactly.
|
||||
fn result_id(v: &Value, key: &str) -> Option<NodeId> {
|
||||
match &v[key] {
|
||||
Value::Array(a) => a.first().and_then(Value::as_u64).map(NodeId),
|
||||
n => n.as_u64().map(NodeId),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Image Trace object, its document and the id its handle holds, of the `cls` (`TracingObject`
|
||||
/// or `TracingOptions`) `d` names. It must still be an Image Trace object of its document.
|
||||
fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 5]), HostError> {
|
||||
let Some((c, handle)) = host_ref_parts(d).filter(|(c, _)| *c == cls) else {
|
||||
return Err(HostError::Type(format!("this is not a {cls}")));
|
||||
};
|
||||
let &[run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) };
|
||||
let (doc, original) = node_of(h, &handle).ok_or_else(stale)?;
|
||||
let id = follow(h, doc.uid, original);
|
||||
let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|g| crate::cmd::is_trace_group(g) && same_source(h, doc.uid, original, g)));
|
||||
if !live {
|
||||
return Err(stale());
|
||||
}
|
||||
Ok((Item { doc, id }, [run, uid, high, low, reverts]))
|
||||
}
|
||||
|
||||
/// The `PluginItem` `this` names, with the handle numbers its `tracing` keeps.
|
||||
fn plugin_of(h: &Host, a: &[Data]) -> Result<(Item, [f64; 5]), HostError> {
|
||||
match host_ref_parts(arg(a, 0)) {
|
||||
Some(("PluginItem", handle)) => {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
match handle.as_slice() {
|
||||
&[run, uid, high, low, reverts] => Ok((item, [run, uid, high, low, reverts])),
|
||||
_ => Err(HostError::Type("this is not a PluginItem".into())),
|
||||
}
|
||||
}
|
||||
_ => Err(HostError::Type("this is not a PluginItem".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the Image Trace object of `item` with `f`.
|
||||
fn read_group<T>(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) -> Result<T, HostError>) -> Result<T, HostError> {
|
||||
with_doc(h, item.doc, |_, st| match st.doc.node(item.id) {
|
||||
Some(n) => f(st, n),
|
||||
None => Err(stale()),
|
||||
})
|
||||
}
|
||||
|
||||
fn refuse_uneditable(h: &Host, item: Item) -> Result<(), HostError> {
|
||||
let editable = with_doc(h, item.doc, |_, st| super::editable(&st.doc, item.id) && !super::on_locked_artboard(h, st, item.id));
|
||||
if !editable {
|
||||
return Err(HostError::Error(format!("Cannot edit page item {}", item.id.0)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs command `id` with `params` on `item`'s document → the object its result names under `key`.
|
||||
/// The selection stays as it was, with that object in place of `item`.
|
||||
fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result<NodeId, HostError> {
|
||||
refuse_uneditable(h, item)?;
|
||||
let mut before = with_doc(h, item.doc, |_, st| st.selection.clone());
|
||||
on_doc(h, item.doc.uid, false, |h| {
|
||||
let (_, r) = command_value(h, id, params)?;
|
||||
for w in r.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
super::super::each_line(&format!("{id}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
|
||||
}
|
||||
let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?;
|
||||
let remap = |i: NodeId| if i == item.id { new } else { i };
|
||||
before.objects = before.objects.into_iter().map(remap).collect();
|
||||
let mut seen = HashSet::new();
|
||||
before.objects.retain(|i| seen.insert(*i));
|
||||
before.key = before.key.map(remap);
|
||||
before.target = before.target.map(remap);
|
||||
before.on_path_member = before.on_path_member.map(remap);
|
||||
let restore = {
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
(st.selection != before).then(|| st.doc.clone())
|
||||
};
|
||||
if let Some(doc) = restore {
|
||||
super::restore_selection(h, &doc, &before)?;
|
||||
}
|
||||
Ok(new)
|
||||
})
|
||||
}
|
||||
|
||||
/// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make,
|
||||
/// and "Cannot edit page item" when it holds a locked object other than its source image, which
|
||||
/// the replacement would discard. The objects looked at are charged to the run either way.
|
||||
fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
|
||||
let (visited, result) = read_group(h, item, |_, group| {
|
||||
remember_source(h, item.doc.uid, group);
|
||||
// The objects the trace made, as the tracing records them; a tracing saved without that
|
||||
// record is checked against the objects it held when this run first saw it.
|
||||
let made = group.trace_made();
|
||||
let descendants = h.dom.tracing.descendants.borrow();
|
||||
let ids = match made {
|
||||
Some(_) => None,
|
||||
None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?),
|
||||
};
|
||||
let source = group.children().and_then(|c| c.first()).map(|n| n.id);
|
||||
let mut visited = 0u64;
|
||||
let mut locked = None;
|
||||
let mut todo: Vec<&Arc<Node>> = group.children().map(|c| c.iter().collect()).unwrap_or_default();
|
||||
while let Some(n) = todo.pop() {
|
||||
visited += 1;
|
||||
let added = match (&made, ids) {
|
||||
(Some(m), _) => !m.contains(n.id),
|
||||
(None, Some(ids)) => !ids.contains(&n.id),
|
||||
(None, None) => false,
|
||||
};
|
||||
// Added artwork is reported before a locked object, whichever comes first.
|
||||
if added {
|
||||
return Ok((visited, Err(HostError::Error(refusal.into()))));
|
||||
}
|
||||
if n.locked && Some(n.id) != source && locked.is_none() {
|
||||
locked = Some(n.id);
|
||||
}
|
||||
todo.extend(n.children().into_iter().flatten());
|
||||
}
|
||||
Ok((visited, locked.map_or(Ok(()), |id| Err(HostError::Error(format!("Cannot edit page item {}", id.0))))))
|
||||
})?;
|
||||
h.charge_call(visited)?;
|
||||
result
|
||||
}
|
||||
|
||||
/// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its
|
||||
/// script objects follow the new one.
|
||||
fn retrace(h: &Host, item: Item, mut params: Map<String, Value>) -> Result<(), HostError> {
|
||||
if h.dom.tracing.retraces.get() >= MAX_RETRACES {
|
||||
return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times")));
|
||||
}
|
||||
refuse_added(h, item, ADDED_ARTWORK)?;
|
||||
params.insert("id".into(), json!(item.id.0));
|
||||
// One savepoint covers the trace and the selection's restore, so a failed restore undoes the trace.
|
||||
let new = super::atomically(h, |h| replace(h, item, "imageTrace.make", &Value::Object(params), "id"))?;
|
||||
read_group(h, Item { id: new, ..item }, |_, group| {
|
||||
remember_source(h, item.doc.uid, group);
|
||||
Ok(())
|
||||
})?;
|
||||
h.dom.tracing.retraces.set(h.dom.tracing.retraces.get() + 1);
|
||||
replaced(h, item.doc.uid, item.id, new);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- PlacedItem and RasterItem ----
|
||||
|
||||
/// `trace()`: `imageTrace.make` of the image with the Default preset → its `PluginItem`.
|
||||
fn image_trace(h: &Host, a: &[Data], cls: &str) -> Answer {
|
||||
let item = match host_ref_parts(arg(a, 0)) {
|
||||
Some((c, _)) if c == cls => item_of(h, arg(a, 0))?,
|
||||
_ => return Err(HostError::Type(format!("this is not a {cls}"))),
|
||||
};
|
||||
let (source, linked) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let source = crate::cmd::is_trace_source(d, item.id);
|
||||
let linked = matches!(d.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some());
|
||||
(source, linked)
|
||||
});
|
||||
if source {
|
||||
return Err(HostError::Error(ALREADY_TRACED.into()));
|
||||
}
|
||||
if linked {
|
||||
let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?;
|
||||
if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") {
|
||||
return Err(HostError::Error(super::images::MISSING_LINK.into()));
|
||||
}
|
||||
}
|
||||
let id = replace(h, item, "imageTrace.make", &json!({"id": item.id.0}), "id")?;
|
||||
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
|
||||
}
|
||||
|
||||
fn placed_trace(h: &Host, a: &[Data]) -> Answer {
|
||||
image_trace(h, a, "PlacedItem")
|
||||
}
|
||||
|
||||
fn raster_trace(h: &Host, a: &[Data]) -> Answer {
|
||||
image_trace(h, a, "RasterItem")
|
||||
}
|
||||
|
||||
// ---- PluginItem ----
|
||||
|
||||
fn plugin_is_tracing(h: &Host, a: &[Data]) -> Answer {
|
||||
plugin_of(h, a)?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
fn plugin_tracing(h: &Host, a: &[Data]) -> Answer {
|
||||
let (item, handle) = plugin_of(h, a)?;
|
||||
let source = read_group(h, item, |_, g| g.children().and_then(|c| c.first()).map(|n| n.id).ok_or_else(stale))?;
|
||||
let (_, original) = node_of(h, &handle).ok_or_else(stale)?;
|
||||
h.dom.tracing.sources.borrow_mut().entry((item.doc.uid, original.0)).or_insert(source);
|
||||
Ok(host_ref("TracingObject", &handle))
|
||||
}
|
||||
|
||||
// ---- TracingObject ----
|
||||
|
||||
/// What a tracing's counts are made of.
|
||||
#[derive(Default)]
|
||||
struct Counts {
|
||||
paths: u64,
|
||||
anchors: u64,
|
||||
colors: u64,
|
||||
/// The objects looked at.
|
||||
visited: u64,
|
||||
}
|
||||
|
||||
/// Which of a tracing's counts a read needs; the others are not worked out.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Metric {
|
||||
Paths,
|
||||
Anchors,
|
||||
Colors,
|
||||
}
|
||||
|
||||
/// The anchor points of `n` and every path in it, adding each object looked at below `n` to
|
||||
/// `visited`.
|
||||
fn anchors_of(n: &Node, visited: &mut u64) -> u64 {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.anchor_count() as u64,
|
||||
_ => n.children().map_or(0, |c| {
|
||||
c.iter()
|
||||
.map(|m| {
|
||||
*visited += 1;
|
||||
anchors_of(m, visited)
|
||||
})
|
||||
.sum()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The traced paths of the Image Trace object `g`, their anchor points and paints: every path
|
||||
/// and compound path in it but its source image, the seam fills and clipping paths. The seam fills
|
||||
/// are a clip group directly in the tracing that [`crate::cmd::is_seam_fills`] accepts, or, for a
|
||||
/// trace made before seam fills were clipped, the lowest item above the source image when it
|
||||
/// accepts that. A group nested deeper, or an unclipped group higher up, is counted. An Image
|
||||
/// Trace object inside `g` leaves out its own seam fills the same way. Only the count `metric`
|
||||
/// names is worked out; a compound path counts as one path, and the paths inside it are looked at
|
||||
/// (and counted in `visited`) only for its anchor points.
|
||||
fn counts(g: &Node, metric: Metric) -> Counts {
|
||||
let mut c = Counts::default();
|
||||
let mut paints = HashSet::new();
|
||||
let mut todo: Vec<&Arc<Node>> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default();
|
||||
let mut seams = seam_fills_of(g);
|
||||
while let Some(n) = todo.pop() {
|
||||
c.visited += 1;
|
||||
if seams.contains(&n.id) {
|
||||
continue;
|
||||
}
|
||||
if crate::cmd::is_trace_group(n) {
|
||||
seams.extend(seam_fills_of(n));
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { clipping: true, .. } => {}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
c.paths += 1;
|
||||
match metric {
|
||||
Metric::Paths => {}
|
||||
Metric::Anchors => c.anchors += anchors_of(n, &mut c.visited),
|
||||
Metric::Colors => {
|
||||
for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] {
|
||||
if paint != vectorcraft_color::Paint::None
|
||||
&& let Ok(key) = serde_json::to_string(&paint)
|
||||
{
|
||||
paints.insert(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => todo.extend(n.children().into_iter().flatten()),
|
||||
}
|
||||
}
|
||||
c.colors = paints.len() as u64;
|
||||
c
|
||||
}
|
||||
|
||||
/// The seam fills of the Image Trace object `g` ([`counts`]).
|
||||
fn seam_fills_of(g: &Node) -> HashSet<NodeId> {
|
||||
g.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.skip(1)
|
||||
.enumerate()
|
||||
.filter(|(i, n)| (*i == 0 || matches!(n.kind, NodeKind::Group { clip: true, .. })) && crate::cmd::is_seam_fills(n))
|
||||
.map(|(_, n)| n.id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reads the counts of the tracing `this` names with `f`.
|
||||
fn count(h: &Host, a: &[Data], metric: Metric) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
let c = read_group(h, item, |_, g| Ok(counts(g, metric)))?;
|
||||
h.charge_call(c.visited)?;
|
||||
Ok(num(float(match metric {
|
||||
Metric::Paths => c.paths,
|
||||
Metric::Anchors => c.anchors,
|
||||
Metric::Colors => c.colors,
|
||||
})))
|
||||
}
|
||||
|
||||
fn tracing_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, Metric::Paths)
|
||||
}
|
||||
|
||||
fn tracing_anchors(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, Metric::Anchors)
|
||||
}
|
||||
|
||||
fn tracing_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, Metric::Colors)
|
||||
}
|
||||
|
||||
fn tracing_areas(h: &Host, a: &[Data]) -> Answer {
|
||||
tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
Err(HostError::Error(not_implemented("TracingObject", "areaCount")))
|
||||
}
|
||||
|
||||
/// `imageResolution`: the source image's pixels per inch, 72 over the size of a pixel in points.
|
||||
fn tracing_resolution(h: &Host, a: &[Data]) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
read_group(h, item, |_, g| {
|
||||
let source = g.children().and_then(|c| c.first()).ok_or_else(stale)?;
|
||||
let NodeKind::Image(im) = &source.kind else { return Err(stale()) };
|
||||
let none = || HostError::Error("the source image has no single resolution".into());
|
||||
if source.is_distorted_image() {
|
||||
return Err(none());
|
||||
}
|
||||
let [xa, xb, ya, yb, ..] = im.xf.as_coeffs();
|
||||
let (across, down) = (xa.hypot(xb), ya.hypot(yb));
|
||||
if across <= 1e-12 || down <= 1e-12 || (across - down).abs() > 1e-9 * across.max(down) {
|
||||
return Err(none());
|
||||
}
|
||||
Ok(num(72.0 / across))
|
||||
})
|
||||
}
|
||||
|
||||
fn tracing_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
Ok(host_ref("PluginItem", &handle))
|
||||
}
|
||||
|
||||
fn tracing_source(h: &Host, a: &[Data]) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
read_group(h, item, |st, g| g.children().and_then(|c| c.first()).map(|s| item_ref(h, st, s.id)).ok_or_else(stale))
|
||||
}
|
||||
|
||||
fn tracing_options(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
Ok(host_ref("TracingOptions", &handle))
|
||||
}
|
||||
|
||||
/// `expandTracing(viewed?)`: `imageTrace.expand` → the `GroupItem` that takes the tracing's place.
|
||||
fn tracing_expand(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::Undefined | Data::Bool(false) => {}
|
||||
Data::Bool(true) => {
|
||||
tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
return Err(HostError::Error(VIEWED_EXPAND.into()));
|
||||
}
|
||||
_ => return Err(HostError::Type("viewed must be true or false".into())),
|
||||
}
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
let id = replace(h, item, "imageTrace.expand", &json!({"ids": [item.id.0]}), "ids")?;
|
||||
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
|
||||
}
|
||||
|
||||
/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. A
|
||||
/// tracing that holds an object its trace did not make throws [`ADDED_ARTWORK_RELEASE`], since the
|
||||
/// release keeps only the source image.
|
||||
fn tracing_release(h: &Host, a: &[Data]) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
refuse_added(h, item, ADDED_ARTWORK_RELEASE)?;
|
||||
let id = replace(h, item, "imageTrace.release", &json!({"ids": [item.id.0]}), "ids")?;
|
||||
Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id)))
|
||||
}
|
||||
|
||||
// ---- TracingOptions ----
|
||||
|
||||
/// The tracing `this` names, the settings it was traced with, its view and its preset's name.
|
||||
fn options_of(h: &Host, a: &[Data]) -> Result<(Item, Map<String, Value>, TraceView, String), HostError> {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingOptions")?;
|
||||
read_group(h, item, |_, g| {
|
||||
let trace = g.extras().trace.as_deref();
|
||||
let params = trace.and_then(|t| t.get("params")).and_then(Value::as_object).cloned();
|
||||
let params = params.ok_or_else(|| HostError::Error("the tracing has no recorded options".into()))?;
|
||||
let preset = trace.and_then(|t| t.get("preset")).and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
Ok((item, params, g.trace_view(), preset))
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the setting `key` of the tracing `this` names with `f`.
|
||||
fn read_option(h: &Host, a: &[Data], key: &str, f: impl FnOnce(&Value) -> Answer) -> Answer {
|
||||
let (_, params, ..) = options_of(h, a)?;
|
||||
f(params.get(key).unwrap_or(&Value::Null))
|
||||
}
|
||||
|
||||
/// Traces again with the setting `key` at `value`, unless it is at that value already.
|
||||
fn write_option(h: &Host, a: &[Data], key: &str, value: Value) -> Answer {
|
||||
let (item, mut params, ..) = options_of(h, a)?;
|
||||
if params.get(key) == Some(&value) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
params.insert(key.into(), value);
|
||||
let on = |k: &str| params.get(k).and_then(Value::as_bool) == Some(true);
|
||||
if !on("fills") && !on("strokes") {
|
||||
return Err(HostError::Error(NEEDS_FILLS_OR_STROKES.into()));
|
||||
}
|
||||
let mut p = Map::new();
|
||||
p.insert("params".into(), Value::Object(params));
|
||||
retrace(h, item, p)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// A whole number from `lo` to `hi` for the option `name`.
|
||||
fn whole_in(d: &Data, name: &str, lo: u64, hi: u64) -> Result<u64, HostError> {
|
||||
let n = number(d, &format!("TracingOptions.{name}"))?;
|
||||
if n.fract() != 0.0 || n < float(lo) || n > float(hi) {
|
||||
return Err(out_of_range(name, &format!("a whole number from {lo} to {hi}")));
|
||||
}
|
||||
whole(n).ok_or_else(|| out_of_range(name, &format!("a whole number from {lo} to {hi}")))
|
||||
}
|
||||
|
||||
fn as_number(v: &Value) -> Answer {
|
||||
v.as_f64().map(num).ok_or_else(|| HostError::Error("the tracing's options are damaged".into()))
|
||||
}
|
||||
|
||||
fn as_bool(v: &Value) -> Answer {
|
||||
v.as_bool().map(Data::Bool).ok_or_else(|| HostError::Error("the tracing's options are damaged".into()))
|
||||
}
|
||||
|
||||
fn options_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "mode", |v| {
|
||||
let mode = v.as_str().unwrap_or_default();
|
||||
match MODES.iter().find(|(_, m)| *m == mode) {
|
||||
Some((name, _)) => Ok(text(*name)),
|
||||
None => Err(HostError::Error("TracingOptions.tracingMode has no value for this tracing's mode".into())),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn options_set_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let mode = match arg(a, 1) {
|
||||
Data::String(s) => MODES.iter().find(|(n, _)| n == s).map(|(_, m)| *m),
|
||||
_ => None,
|
||||
};
|
||||
let mode = mode.ok_or_else(|| HostError::Type("TracingOptions.tracingMode must be a TracingModeType value".into()))?;
|
||||
write_option(h, a, "mode", json!(mode))
|
||||
}
|
||||
|
||||
fn options_threshold(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "threshold", as_number)
|
||||
}
|
||||
|
||||
fn options_set_threshold(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = whole_in(arg(a, 1), "threshold", 0, 255)?;
|
||||
write_option(h, a, "threshold", json!(v))
|
||||
}
|
||||
|
||||
fn options_max_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "colors", as_number)
|
||||
}
|
||||
|
||||
fn options_set_max_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = whole_in(arg(a, 1), "maxColors", 2, 256)?;
|
||||
write_option(h, a, "colors", json!(v))
|
||||
}
|
||||
|
||||
fn options_min_area(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "noise", as_number)
|
||||
}
|
||||
|
||||
fn options_set_min_area(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = whole_in(arg(a, 1), "minArea", 0, MAX_MIN_AREA)?;
|
||||
write_option(h, a, "noise", json!(v))
|
||||
}
|
||||
|
||||
fn options_fills(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "fills", as_bool)
|
||||
}
|
||||
|
||||
fn options_set_fills(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = boolean(arg(a, 1), "TracingOptions.fills")?;
|
||||
write_option(h, a, "fills", json!(v))
|
||||
}
|
||||
|
||||
fn options_strokes(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "strokes", as_bool)
|
||||
}
|
||||
|
||||
fn options_set_strokes(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = boolean(arg(a, 1), "TracingOptions.strokes")?;
|
||||
write_option(h, a, "strokes", json!(v))
|
||||
}
|
||||
|
||||
fn options_ignore_white(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "ignoreWhite", as_bool)
|
||||
}
|
||||
|
||||
fn options_set_ignore_white(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = boolean(arg(a, 1), "TracingOptions.ignoreWhite")?;
|
||||
write_option(h, a, "ignoreWhite", json!(v))
|
||||
}
|
||||
|
||||
fn options_palette(h: &Host, a: &[Data]) -> Answer {
|
||||
read_option(h, a, "palette", |v| {
|
||||
let palette = v.as_str().unwrap_or_default();
|
||||
match PALETTES.iter().find(|(_, p)| *p == palette) {
|
||||
Some((name, _)) => Ok(text(*name)),
|
||||
None => Err(HostError::Error("the tracing's options are damaged".into())),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn options_set_palette(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("TracingOptions.palette must be a string".into())) };
|
||||
let palette = PALETTES.iter().find(|(n, _)| n == name).map(|(_, p)| *p).ok_or_else(|| invalid("palette"))?;
|
||||
write_option(h, a, "palette", json!(palette))
|
||||
}
|
||||
|
||||
/// The view's `viewRaster` (`raster`) or `viewVector`.
|
||||
fn view_part(view: TraceView, raster: bool) -> Answer {
|
||||
let name = if raster { "viewRaster" } else { "viewVector" };
|
||||
VIEWS
|
||||
.iter()
|
||||
.find(|(v, ..)| *v == view)
|
||||
.map(|(_, r, v)| text(if raster { *r } else { *v }))
|
||||
.ok_or_else(|| HostError::Error(format!("TracingOptions.{name} has no value for the Split view")))
|
||||
}
|
||||
|
||||
fn options_view(h: &Host, a: &[Data], raster: bool) -> Answer {
|
||||
let (_, _, view, _) = options_of(h, a)?;
|
||||
view_part(view, raster)
|
||||
}
|
||||
|
||||
/// Shows the view `viewRaster` (`raster`) or `viewVector` makes with the other one as it is.
|
||||
fn options_set_view(h: &Host, a: &[Data], raster: bool) -> Answer {
|
||||
let (name, kind) = if raster { ("viewRaster", "ViewRasterType") } else { ("viewVector", "ViewVectorType") };
|
||||
let given = match arg(a, 1) {
|
||||
Data::String(s) if ENUMS.iter().any(|(e, members)| *e == kind && members.iter().any(|m| *s == format!("{kind}.{m}"))) => s.clone(),
|
||||
_ => return Err(HostError::Type(format!("TracingOptions.{name} must be a {kind} value"))),
|
||||
};
|
||||
let (item, _, view, _) = options_of(h, a)?;
|
||||
let Data::String(other) = view_part(view, !raster)? else { return Err(invalid(name)) };
|
||||
let pair = |r: &str, v: &str| if raster { given == r && other == v } else { other == r && given == v };
|
||||
let (to, ..) = VIEWS.iter().find(|(_, r, v)| pair(r, v)).ok_or_else(|| invalid(name))?;
|
||||
if *to != view {
|
||||
refuse_uneditable(h, item)?;
|
||||
edit_item(h, item, "imageTrace.setView", &json!({"ids": [item.id.0], "view": to.id()}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn options_view_raster(h: &Host, a: &[Data]) -> Answer {
|
||||
options_view(h, a, true)
|
||||
}
|
||||
|
||||
fn options_set_view_raster(h: &Host, a: &[Data]) -> Answer {
|
||||
options_set_view(h, a, true)
|
||||
}
|
||||
|
||||
fn options_view_vector(h: &Host, a: &[Data]) -> Answer {
|
||||
options_view(h, a, false)
|
||||
}
|
||||
|
||||
fn options_set_view_vector(h: &Host, a: &[Data]) -> Answer {
|
||||
options_set_view(h, a, false)
|
||||
}
|
||||
|
||||
fn options_preset(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, _, preset) = options_of(h, a)?;
|
||||
Ok(text(preset))
|
||||
}
|
||||
|
||||
fn options_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, handle) = tracing_of(h, arg(a, 0), "TracingOptions")?;
|
||||
Ok(host_ref("TracingObject", &handle))
|
||||
}
|
||||
|
||||
/// A preset name given to `method`: a string of at most [`MAX_PRESET_NAME`] bytes without `/`,
|
||||
/// `\`, `:` or control characters, trimmed.
|
||||
fn preset_name<'a>(d: &'a Data, method: &str) -> Result<&'a str, HostError> {
|
||||
let Data::String(name) = d else { return Err(HostError::Type(format!("TracingOptions.{method} needs a preset name, as a string"))) };
|
||||
if name.len() > MAX_PRESET_NAME {
|
||||
return Err(HostError::Range(format!("TracingOptions.{method}: a preset name has at most {MAX_PRESET_NAME} bytes")));
|
||||
}
|
||||
if name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) {
|
||||
return Err(HostError::Error(format!("TracingOptions.{method}: a preset name cannot hold / \\ : or control characters")));
|
||||
}
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err(HostError::Error(format!("TracingOptions.{method}: the preset name is empty")));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// `loadFromPreset(name)`: traces again with the built-in or saved preset `name` → `true`.
|
||||
fn options_load(h: &Host, a: &[Data]) -> Answer {
|
||||
let name = preset_name(arg(a, 1), "loadFromPreset")?;
|
||||
let (item, params, _, preset) = options_of(h, a)?;
|
||||
let wanted = vectorcraft_trace::preset(name).or_else(|| h.session.borrow().trace_preset(name).map(|q| q.params.clone()));
|
||||
let wanted = wanted.ok_or_else(|| HostError::Error("TracingOptions.loadFromPreset: no built-in or saved preset has that name".into()))?;
|
||||
let same = serde_json::to_value(&wanted).ok().as_ref().and_then(Value::as_object) == Some(¶ms);
|
||||
if !(same && preset.eq_ignore_ascii_case(name)) {
|
||||
let mut p = Map::new();
|
||||
p.insert("preset".into(), json!(name));
|
||||
retrace(h, item, p)?;
|
||||
}
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `storeToPreset(name)`: `false` for a built-in preset or `Custom`; any other name runs
|
||||
/// `imageTrace.presets.save`, which a script cannot run.
|
||||
fn options_store(h: &Host, a: &[Data]) -> Answer {
|
||||
let name = preset_name(arg(a, 1), "storeToPreset")?;
|
||||
let (_, params, ..) = options_of(h, a)?;
|
||||
if vectorcraft_trace::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") {
|
||||
return Ok(Data::Bool(false));
|
||||
}
|
||||
command(h, "imageTrace.presets.save", &json!({"name": name, "params": params}))?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// A member of `TracingOptions` with no VectorCraft setting: reading and assigning it both throw,
|
||||
/// after the check that the tracing `this` names is still there, and `reflect` and
|
||||
/// `hasOwnProperty` leave it out.
|
||||
fn missing(link: &Link, name: &'static str) -> Described {
|
||||
let message = not_implemented("TracingOptions", name);
|
||||
let l = link.clone();
|
||||
let f: vectorcraft_js::HostFunction = std::rc::Rc::new(move |a: Vec<Data>| {
|
||||
let h = super::current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
tracing_of(&h, arg(&a, 0), "TracingOptions")?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`.
|
||||
pub(super) fn add_trace(classes: &mut [HostClass], l: &Link) {
|
||||
for c in classes.iter_mut() {
|
||||
let f: super::Member = match c.name.as_str() {
|
||||
"PlacedItem" => placed_trace,
|
||||
"RasterItem" => raster_trace,
|
||||
_ => continue,
|
||||
};
|
||||
c.members.push(("trace".into(), method(l, f)));
|
||||
c.info.push(("trace".into(), returns("PluginItem", &[])));
|
||||
}
|
||||
}
|
||||
|
||||
/// `PluginItem`, after `PageItem`, `TracingObject` and `TracingOptions`.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let plugin = named(vec![("isTracing", get(l, plugin_is_tracing), typed("boolean")), ("tracing", get(l, plugin_tracing), typed("TracingObject"))]);
|
||||
let tracing = named(vec![
|
||||
("typename", typename_of("TracingObject"), typed("string")),
|
||||
("anchorCount", get(l, tracing_anchors), typed("number")),
|
||||
("areaCount", HostMember::Unavailable(super::function(l, tracing_areas)), MemberInfo { unavailable: true, ..MemberInfo::default() }),
|
||||
("imageResolution", get(l, tracing_resolution), typed("number")),
|
||||
("parent", get(l, tracing_parent), typed("PluginItem")),
|
||||
("pathCount", get(l, tracing_paths), typed("number")),
|
||||
("sourceArt", get(l, tracing_source), typed("PageItem")),
|
||||
("tracingOptions", get(l, tracing_options), typed("TracingOptions")),
|
||||
("usedColorCount", get(l, tracing_colors), typed("number")),
|
||||
("expandTracing", method(l, tracing_expand), returns("GroupItem", &[("viewed", "boolean")])),
|
||||
("releaseTracing", method(l, tracing_release), returns("PageItem", &[])),
|
||||
]);
|
||||
let mut options = named(vec![
|
||||
("typename", typename_of("TracingOptions"), typed("string")),
|
||||
("parent", get(l, options_parent), typed("TracingObject")),
|
||||
("preset", get(l, options_preset), typed("string")),
|
||||
("tracingMode", property(l, options_mode, options_set_mode), typed("TracingModeType")),
|
||||
("threshold", property(l, options_threshold, options_set_threshold), MemberInfo { min: Some(0.0), max: Some(255.0), ..typed("number") }),
|
||||
("fills", property(l, options_fills, options_set_fills), typed("boolean")),
|
||||
("strokes", property(l, options_strokes, options_set_strokes), typed("boolean")),
|
||||
("maxColors", property(l, options_max_colors, options_set_max_colors), MemberInfo { min: Some(2.0), max: Some(256.0), ..typed("number") }),
|
||||
("palette", property(l, options_palette, options_set_palette), typed("string")),
|
||||
("ignoreWhite", property(l, options_ignore_white, options_set_ignore_white), typed("boolean")),
|
||||
("minArea", property(l, options_min_area, options_set_min_area), typed("number")),
|
||||
("viewRaster", property(l, options_view_raster, options_set_view_raster), typed("ViewRasterType")),
|
||||
("viewVector", property(l, options_view_vector, options_set_view_vector), typed("ViewVectorType")),
|
||||
("loadFromPreset", method(l, options_load), returns("boolean", &[("presetName", "string")])),
|
||||
("storeToPreset", method(l, options_store), returns("boolean", &[("presetName", "string")])),
|
||||
]);
|
||||
options.extend(NOT_IMPLEMENTED.iter().map(|m| missing(l, m)));
|
||||
vec![
|
||||
class("PluginItem", Some("PageItem"), plugin, None),
|
||||
class("TracingObject", None, tracing, None),
|
||||
class("TracingOptions", None, options, None),
|
||||
]
|
||||
}
|
||||
@@ -238,9 +238,10 @@ pub(crate) struct Files {
|
||||
entry_key: Option<String>,
|
||||
}
|
||||
|
||||
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
|
||||
/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text
|
||||
/// run as ECMAScript 5.1 with the ExtendScript extensions.
|
||||
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] and
|
||||
/// [`vectorcraft_js::Options::es2017`] when its file name ends in `.js` or `.mjs` (in any letter
|
||||
/// case); a `.jsx` script, any other file and a script given as text run as ECMAScript 5.1 with
|
||||
/// the ExtendScript extensions.
|
||||
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs"))
|
||||
}
|
||||
@@ -496,7 +497,7 @@ impl Files {
|
||||
|
||||
/// The options a file of this run is parsed with, preprocessor lines aside.
|
||||
pub(crate) fn options(&self) -> Options {
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, es2017: self.es2015, e4x: true, ..Options::default() }
|
||||
}
|
||||
|
||||
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
|
||||
|
||||
@@ -2299,13 +2299,16 @@ impl Session {
|
||||
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
|
||||
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
|
||||
let es2015 = request.module || include::es2015_script(request.file.as_deref());
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
|
||||
// It also reads async functions and `await` (ECMAScript 2017).
|
||||
let options =
|
||||
Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, es2017: es2015, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
// A kept engine reads each run's code the way that run's script does.
|
||||
let mut realm = match realm {
|
||||
Some(mut realm) => {
|
||||
realm.set_limits(limits);
|
||||
realm.set_es2015(es2015);
|
||||
realm.set_es2017(es2015);
|
||||
if es2015 {
|
||||
realm.add_es2015();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user