Merge main into fix/doc-pathitems-removeall-clipping

This commit is contained in:
dotCooCoo committed 2026-12-03 07:44:01 -08:00
commit 199b92bd5c
222 files changed
+15993 -848

No files matched your search

+124 -26
View File
@@ -54,7 +54,7 @@
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
//! error. A run that fails leaves the tool as it was.
//! - `controlBounds` is the visible bounds, widened to take in the anchors and direction points of
//! the paths in the object; a clipping group counts its clipping path only.
//! the shown paths in the object; a clip group or clipping layer takes in only its clipping path's.
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
//! in view-number order, and none without one. View objects keep their window's identity when
//! windows are renumbered. The screen mode is the app's:
@@ -107,6 +107,9 @@ mod matrix;
mod paths;
pub mod preferences;
mod print;
mod raster_capture;
#[cfg(test)]
pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT;
mod save_open;
mod tags;
mod text;
@@ -457,7 +460,7 @@ fn point_method(link: &Link, f: Member) -> HostMember {
pub(super) type Described = (String, HostMember, MemberInfo);
/// A property's or a method's result's type for `reflect`.
fn typed(data_type: &str) -> MemberInfo {
pub(super) fn typed(data_type: &str) -> MemberInfo {
MemberInfo { data_type: data_type.into(), ..MemberInfo::default() }
}
@@ -468,7 +471,8 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo
}
/// A member the help pages list that is not available yet: reading or assigning it throws, after
/// the check that a document, layer, page item, path point or text range `this` is still there.
/// the check that a document, layer, page item, path point, text range or `GroupItems` collection
/// `this` is still there.
/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and
/// `reflect` leaves it out.
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
@@ -493,6 +497,9 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
"TextRange" => {
text::check_range(&h, arg(&a, 0))?;
}
"GroupItems" => {
layers::check_groups(&h, arg(&a, 0))?;
}
_ => {}
}
Err(HostError::Error(message.clone()))
@@ -2331,13 +2338,17 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
return layers::scoped_remove_all(h, a);
}
let doc = items_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| {
let ids = top_items(&st.doc);
let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
(ids, refused, on_locked)
// A clipping layer emptied of its art releases its mask, so art added later is not made its
// clipping path.
let released = masks_cleared_by(&st.doc, &ids);
let tracing = release_makes_tracing(&st.doc, &released, &ids);
(ids, refused, on_locked, released, tracing)
});
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -2347,8 +2358,11 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if tracing {
return Err(HostError::Error(NOT_A_TRACING.into()));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
on_doc(h, doc.uid, true, |h| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
Ok(Data::Undefined)
}
@@ -2636,26 +2650,39 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
bounds(h, a, true)
}
/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an
/// object with nothing in it.
/// `controlBounds`: the visible bounds, taking in the anchors and direction handles of the paths
/// in the item.
fn item_control(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
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)])),
}
// 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)])) };
// Each object and anchor the walk visits is charged, so reading a large group's bounds again
// and again counts against the run.
let mut steps = 0u64;
let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r, &mut steps)));
h.charge_call(steps)?;
Ok(f.bounds(h.dom.coords.get(), r))
}
/// 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))),
/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and
/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as
/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping
/// path's.
fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
*steps += 1;
if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return r;
}
for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) {
*steps += 1;
r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out);
}
let children = n.children().map_or(&[][..], Vec::as_slice);
let children = if n.clips() { &children[..children.len().min(1)] } else { children };
for c in children {
r = take_in_handles(c, r, steps);
}
r
}
fn item_position(h: &Host, a: &[Data]) -> Answer {
@@ -2828,11 +2855,55 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
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()));
}
let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id]));
// A clip group named as a tracing, released with an image left first, would become one too.
if with_doc(h, item.doc, |_, st| release_makes_tracing(&st.doc, &released, &[item.id])) {
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}))?;
let params = json!({"ids": [item.id.0], "keepEmpty": true});
paths::see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| clear_releasing(h, &released, &params)));
h.dom.editing.set(kept);
r?;
Ok(Data::Undefined)
}
/// The clip groups and clipping layers whose clipping path is one of `ids`. Deleting a clipping
/// path releases its mask, so the object above it does not become the clipping path.
pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter()
.filter_map(|i| {
let p = d.parent_of(*i)?;
let n = d.node(p)?;
(n.clips() && n.children()?.first().is_some_and(|c| c.id == *i)).then_some(p)
})
.collect()
}
/// Whether releasing the masks of `released` and deleting `removed` would leave one of those groups
/// an ordinary group named as a tracing with an image first in it, which would make it a tracing.
pub(super) fn release_makes_tracing(d: &Document, released: &[NodeId], removed: &[NodeId]) -> bool {
if released.is_empty() {
return false;
}
let removed: std::collections::HashSet<NodeId> = removed.iter().copied().collect();
released.iter().filter_map(|g| d.node(*g)).any(|g| {
matches!(g.kind, NodeKind::Group { .. })
&& g.name.as_deref() == Some(crate::cmd::TRACE_NAME)
&& g.children().and_then(|c| c.iter().find(|n| !removed.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))
})
}
/// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`.
pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result<Data, HostError> {
for g in released {
command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?;
}
command(h, "edit.clear", params)
}
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
@@ -2981,6 +3052,19 @@ fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option<usize>) ->
}
}
/// Whether deleting every object in `removed` together would leave one of their parents, an
/// ordinary group named as a tracing, with an image first in it, which would make it a tracing.
pub(super) fn removal_makes_tracing(d: &Document, removed: &[NodeId]) -> bool {
let going: std::collections::HashSet<NodeId> = removed.iter().copied().collect();
let mut parents: Vec<NodeId> = removed.iter().filter_map(|i| d.parent_of(*i)).collect();
parents.sort_unstable_by_key(|p| p.0);
parents.dedup();
parents
.into_iter()
.filter(|p| named_as_tracing(d, *p))
.any(|p| d.children(Some(p)).and_then(|c| c.iter().find(|n| !going.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))))
}
/// 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| {
@@ -2996,6 +3080,8 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
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;
// The clipping path itself, put back where it is, stays the clipping path.
let mask_stays = from.is_some_and(|(p, j, _)| p == Some(to.parent) && j == 0);
let at = match (to.how, to.beside) {
(Placement::Top, _) => count,
(Placement::Bottom, _) => 0,
@@ -3007,11 +3093,19 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
{
i -= 1;
}
if how == Placement::Above { i + 1 } else { i }
let at = if how == Placement::Above { i + 1 } else { i };
// A place behind a clipping path is refused; an object put into the clip group
// itself goes directly above the clipping path.
if clips && at == 0 && !mask_stays {
return Err(HostError::Error("an object cannot go below a clipping mask".into()));
}
at
}
(_, None) => count,
};
let at = if clips { at.max(1) } else { at };
// Any other place for the clipping path is left to `node.move`, which refuses it.
let stays = mask_stays && at == 0;
let at = if clips && !stays { at.max(1) } else { at };
// The index `node.move` puts the object at: art stays below the ruler guides.
// This is `Node::insert_index` on the parent's children without the object, read in place
// so that no list of them is copied.
@@ -3170,7 +3264,7 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
}
/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name.
fn named_text(class: &str, name: Answer) -> Answer {
pub(super) fn named_text(class: &str, name: Answer) -> Answer {
match name? {
Data::String(n) => Ok(text(format!("[{class} {n}]"))),
_ => Ok(text(format!("[{class} ]"))),
@@ -3253,7 +3347,9 @@ const ENUMS: &[(&str, &[&str])] = &[
/// holds.
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
text::install_enums(realm)?;
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) {
for (name, members) in
ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(raster_capture::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS)
{
let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name);
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
@@ -3384,6 +3480,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
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") }));
document.extend(raster_capture::document_members(l));
classes.push(class("Document", None, document, None));
classes.push(class(
"Views",
@@ -3548,6 +3645,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
classes.extend(tracing::classes(l));
classes.extend(save_open::classes(l));
classes.extend(print::classes(l));
classes.extend(raster_capture::classes(l));
classes.extend(tags::classes(l));
classes
}
+71 -18
View File
@@ -12,8 +12,8 @@
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's
//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the
//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems`
//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's
//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems`
//! hold every group or compound path at any depth, in the order of the document's `pageItems`.
//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes
//! a sublayer on top of that layer's contents. The new layer becomes the current one.
@@ -68,6 +68,8 @@ enum Kind {
Compound,
/// Paths (`PathItem`).
Path,
/// Type (`TextFrame`), whose collection's other members are in `text.rs`.
Text,
}
impl Kind {
@@ -77,6 +79,7 @@ impl Kind {
Kind::Group => "GroupItems",
Kind::Compound => "CompoundPathItems",
Kind::Path => "PathItems",
Kind::Text => "TextFrames",
}
}
@@ -86,6 +89,7 @@ impl Kind {
Kind::Group => typename(n) == Some("GroupItem"),
Kind::Compound => typename(n) == Some("CompoundPathItem"),
Kind::Path => typename(n) == Some("PathItem"),
Kind::Text => typename(n) == Some("TextFrame"),
}
}
}
@@ -245,7 +249,9 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer {
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
}
set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v, json!({"opacity": v}))
// The number the getter reports, or one that stores as the opacity the layer has, leaves the
// layer as it is.
set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v || n.opacity == (v / 100.0) as f32, json!({"opacity": v}))
}
fn layer_color(h: &Host, a: &[Data]) -> Answer {
@@ -289,14 +295,12 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
}
/// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is
/// not counted.
/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop
/// lists the layers once. Each read is still charged for the search through the list.
fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
let at = with_doc(h, doc, |_, st| {
let parent = st.doc.parent_of(id);
let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len));
h.charge_call(count as u64)?;
let list = layer_list(&st.doc, parent);
let list = layers_listed(h, st, st.doc.parent_of(id))?;
h.charge_call(list.len() as u64)?;
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
})?;
@@ -642,6 +646,10 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Error("a document needs at least one layer".into()));
}
let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?;
// `layer.delete` takes at most this many rows; more is refused before anything is deleted.
if ids.len() > crate::cmd::layer::MAX_ROWS {
return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS)));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
@@ -760,8 +768,17 @@ fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer {
};
}
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) {
Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))),
// The text of a number that is not an array index is looked up as a name.
None => with_doc(h, doc, |_, st| {
let ids = art_list(h, st, kind, c)?;
h.charge_call(ids.len() as u64)?;
let name = vectorcraft_js::number_to_string(*n);
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id)))
}),
}
}
fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
@@ -778,6 +795,11 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
match arg(a, 1) {
Data::String(_) => art_by_name(h, a, kind),
// A number is a position only. A stale collection throws its stale error first.
Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => {
art_scope(h, arg(a, 0), kind.class())?;
Err(HostError::Error(NOT_FOUND.into()))
}
Data::Number(_) => match art_at(h, a, kind)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
@@ -833,6 +855,10 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
)));
}
// Deleting the objects above an image in an ordinary group named as a tracing would make it one.
if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) {
return Err(HostError::Error(super::NOT_A_TRACING.into()));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": true})))?;
}
@@ -982,6 +1008,20 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer {
held(h, a, Kind::Compound)
}
fn held_text(h: &Host, a: &[Data]) -> Answer {
held(h, a, Kind::Text)
}
/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists.
pub(super) fn text_scope(h: &Host, d: &Data) -> Result<(Doc, Option<NodeId>)> {
art_scope(h, d, Kind::Text.class())
}
/// The type objects directly in `container`, topmost first.
pub(super) fn text_list(h: &Host, st: &DocState, container: NodeId) -> Result<Rc<Vec<NodeId>>> {
art_list(h, st, Kind::Text, Some(container))
}
// ---- GroupItem and CompoundPathItem ----
fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result<Item> {
@@ -1005,11 +1045,16 @@ fn group_clipped(h: &Host, a: &[Data]) -> Answer {
}
/// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the
/// clipping mask. The group keeps its id either way.
/// clipping mask. The group keeps its id either way. A hidden or locked topmost object is refused
/// before it loses its paint.
fn group_set_clipped(h: &Host, a: &[Data]) -> Answer {
let on = boolean(arg(a, 1), "clipped")?;
let item = this_item_of(h, a, "GroupItem")?;
let (now, ok) = with_doc(h, item.doc, |_, st| (st.doc.node(item.id).is_some_and(crate::doc::Node::clips), editable(&st.doc, item.id)));
let (now, ok, top) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let top = d.node(item.id).and_then(|n| n.children()).and_then(|c| c.iter().rev().find(|c| !c.is_ruler_guide())).map(|c| c.id);
(d.node(item.id).is_some_and(crate::doc::Node::clips), editable(d, item.id), top.filter(|t| !editable(d, *t)))
});
if now == on {
return Ok(Data::Undefined);
}
@@ -1017,6 +1062,9 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer {
if !ok {
return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0)));
}
if let Some(t) = top.filter(|_| on) {
return Err(HostError::Error(format!("Cannot clip GroupItem {}: its topmost object {} is hidden or locked", item.id.0, t.0)));
}
on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?;
Ok(Data::Undefined)
}
@@ -1035,8 +1083,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
("pageItems", get(l, held_page_items), listed("PageItems")),
("groupItems", get(l, held_groups), listed("GroupItems")),
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
("textFrames", get(l, held_text), listed("TextFrames")),
]);
m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
m
}
"CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]),
@@ -1317,9 +1366,13 @@ fn layers_to_string(h: &Host, a: &[Data]) -> Answer {
Ok(text("[Layers]"))
}
fn groups_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Group.class())?;
check_groups(h, arg(a, 0))?;
Ok(text("[GroupItems]"))
}
/// Fails when `d` is not a `GroupItems` collection or the document, layer or group it lists is gone.
pub(super) fn check_groups(h: &Host, d: &Data) -> Result<()> {
art_scope(h, d, Kind::Group.class()).map(|_| ())
}
fn compounds_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Compound.class())?;
Ok(text("[CompoundPathItems]"))
@@ -1511,17 +1564,17 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("pageItems", get(l, held_page_items), listed("PageItems")),
("groupItems", get(l, held_groups), listed("GroupItems")),
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
("textFrames", get(l, held_text), listed("TextFrames")),
("zOrderPosition", get(l, layer_z_position), typed("number")),
("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")),
("isIsolated", get(l, layer_is_isolated), typed("boolean")),
("move", method(l, layer_move), typed("Layer")),
("move", method(l, layer_move), returns("Layer", &[("relativeObject", "*"), ("insertionLocation", "ElementPlacement")])),
("remove", method(l, layer_remove), returns("undefined", &[])),
("zOrder", method(l, layer_z_order), typed("undefined")),
("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
("toString", method(l, layer_to_string), returns("string", &[])),
]);
layer.extend(
["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"]
.map(|m| later(l, "Layer", m)),
["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)),
);
vec![
class("Layer", None, layer, None),
@@ -0,0 +1,696 @@
//! Rasterizing art and capturing it as an image in the script object model: `Document.rasterize`,
//! `Document.imageCapture` and their option classes, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/> describe.
//!
//! `rasterize` runs `object.rasterize` with the source art's ids, and `imageCapture` runs
//! `document.export` of an area of the page, inside the run's transaction. Every option is given to
//! the command, at the help page's default when the script leaves it out, so the document's raster
//! effects settings do not change the result.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - `clipBounds` is `[left, top, right, bottom]` in the run's script coordinates, as
//! `geometricBounds` gives them; the right edge must be right of the left one and the bottom edge
//! below the top one, and the numbers are never swapped.
//! - `rasterize` takes one page item or a list of at most [`super::MAX_LISTED`] of them, all of
//! this document, none listed twice, inside another listed one or a path of a compound path, and
//! none locked or in a locked layer or group. It keeps the selection, less the art it replaces,
//! and gives the new `RasterItem`: with `clippingMask`, the image inside its clip group.
//! `transparency` wins over `backgroundBlack`. `convertSpotColors`, `convertTextToOutlines` and
//! `includeLayers` true throw an error that says they are not available yet.
//! - `imageCapture` writes a PNG, and the file's name must end with `.png`. Without `clipBounds` it
//! captures the bounds of all the visible art, on the artboards or off them. With
//! `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with
//! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0
//! to 255. The file is written only where the script's `File` objects may write, and never over
//! an open document's file or a file one of them links, under any of its names (a hard link
//! included); on Unix it is never written over a file that has other hard links. Source paths
//! outside both the automation read and write roots are excluded before
//! filesystem probes.
//! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is
//! drawn; the resolution is never lowered to make it fit.
//! - `windowCapture` throws an error that says it is not available yet.
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_geom::Rect;
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
use super::{
Answer, Described, Doc, Host, Link, MAX_LISTED, STALE_ITEM, arg, boolean, class, command, command_value, coordinate, current, frame, given,
item_of, item_ref, later, method, named, num, on_doc, returns, text, this_doc, with_doc,
};
/// The lowest resolution the option classes take, in pixels per inch.
pub const MIN_RESOLUTION: f64 = 72.0;
/// The highest resolution the option classes take, in pixels per inch.
pub const MAX_RESOLUTION: f64 = 2400.0;
/// The most room `RasterizeOptions.padding` adds around the art, in points.
pub const MAX_PADDING: f64 = 1000.0;
/// The error of a source art object from another document.
pub const OTHER_DOCUMENT: &str = "The source art must be in this document";
/// The enumerations these members use, as `dom`'s are made.
pub(super) const ENUMS: &[(&str, &[&str])] =
&[("AntiAliasingMethod", &["ARTOPTIMIZED", "None", "TYPEOPTIMIZED"]), ("RasterizationColorModel", &["BITMAP", "DEFAULTCOLORMODEL", "GRAYSCALE"])];
/// The member of `enumeration` that `d` names (`"Enumeration.MEMBER"`).
fn member<'a>(d: &'a Data, enumeration: &str, what: &str) -> std::result::Result<&'a str, HostError> {
let members = ENUMS.iter().find(|(n, _)| *n == enumeration).map_or(&[][..], |(_, m)| *m);
let bad = || HostError::Type(format!("{what} must be a {enumeration} value"));
let Data::String(s) = d else { return Err(bad()) };
let m = s.strip_prefix(enumeration).and_then(|r| r.strip_prefix('.')).ok_or_else(bad)?;
if members.contains(&m) { Ok(m) } else { Err(bad()) }
}
/// A finite number from `lo` to `hi`.
fn number_in(d: &Data, what: &str, lo: f64, hi: f64) -> std::result::Result<f64, HostError> {
match d {
Data::Number(n) if n.is_finite() => {
if (lo..=hi).contains(n) {
Ok(*n)
} else {
Err(HostError::Range(format!("{what} must be from {lo} to {hi}")))
}
}
_ => Err(HostError::Type(format!("{what} must be a finite number"))),
}
}
/// The fields of the options object `d` of `class`, or `None` when the script gave none.
fn options<'a>(d: &'a Data, class: &str) -> std::result::Result<Option<&'a [(String, Data)]>, HostError> {
match given(d) {
None | Some(Data::Null) => Ok(None),
Some(Data::Object(items)) if items.iter().any(|(k, v)| k == "typename" && matches!(v, Data::String(s) if s == class)) => Ok(Some(items)),
Some(_) => Err(HostError::Type(format!("the options must be a {class} object"))),
}
}
/// `clipBounds`, `[left, top, right, bottom]` in the run's script coordinates, as a rectangle in
/// document coordinates; `None` when the script gave none.
fn clip_bounds(h: &Host, doc: Doc, d: &Data) -> std::result::Result<Option<Rect>, HostError> {
let a = match given(d) {
None | Some(Data::Null) => return Ok(None),
Some(Data::Array(a)) if a.len() == 4 => a,
Some(_) => return Err(HostError::Type("clipBounds must be an array of four numbers [left, top, right, bottom]".into())),
};
let mut n = [0.0; 4];
for (o, d) in n.iter_mut().zip(a) {
*o = coordinate(d, "clipBounds")?;
}
let f = with_doc(h, doc, |_, st| frame(st))?;
let c = h.dom.coords.get();
let (p0, p1) = (f.to_document(c, [n[0], n[1]]), f.to_document(c, [n[2], n[3]]));
if p1.x <= p0.x || p1.y <= p0.y {
return Err(HostError::Range("clipBounds must have its right edge right of its left edge and its bottom edge below its top edge".into()));
}
Ok(Some(Rect::new(p0.x, p0.y, p1.x, p1.y)))
}
/// Throws when an image of `region` at `ppi` would be more than 64 megapixels or longer than the
/// renderer draws on a side, before anything is drawn.
fn check_size(region: Rect, ppi: f64) -> std::result::Result<(), HostError> {
let scale = ppi / 72.0;
let (w, h) = ((region.width() * scale).round().max(1.0), (region.height() * scale).round().max(1.0));
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
if w * h > crate::cmd::menucmds::MAX_PIXELS || w > side || h > side {
return Err(HostError::Range(format!(
"the image would be {w} × {h} pixels; images are limited to 64 megapixels and {side} pixels a side: lower the resolution or the bounds"
)));
}
Ok(())
}
// ---- Rasterize ----
/// `object.rasterize`'s params for the `RasterizeOptions` fields `items` (`None`: the defaults),
/// with every option given.
fn rasterize_params(items: Option<&[(String, Data)]>) -> std::result::Result<Map<String, Value>, HostError> {
let (mut anti_alias, mut black, mut clear, mut clip, mut model, mut padding, mut ppi) = ("art", false, false, false, "document", 0.0, 300.0);
for (k, v) in items.unwrap_or_default() {
if matches!(v, Data::Undefined) {
continue;
}
let what = format!("RasterizeOptions.{k}");
match k.as_str() {
"antiAliasingMethod" => {
anti_alias = match member(v, "AntiAliasingMethod", &what)? {
"None" => "none",
"TYPEOPTIMIZED" => "type",
_ => "art",
}
}
"backgroundBlack" => black = boolean(v, &what)?,
"transparency" => clear = boolean(v, &what)?,
"clippingMask" => clip = boolean(v, &what)?,
"colorModel" => {
model = match member(v, "RasterizationColorModel", &what)? {
"BITMAP" => "bitmap",
"GRAYSCALE" => "grayscale",
_ => "document",
}
}
"padding" => padding = number_in(v, &what, 0.0, MAX_PADDING)?,
"resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?,
"convertSpotColors" | "convertTextToOutlines" | "includeLayers" if boolean(v, &what)? => {
return Err(HostError::Error(format!("{what} is not available yet")));
}
_ => {}
}
}
let background = if clear {
"transparent"
} else if black {
"black"
} else {
"white"
};
let mut p = Map::new();
p.insert("ppi".into(), json!(ppi));
p.insert("background".into(), json!(background));
p.insert("antiAlias".into(), json!(anti_alias));
p.insert("padding".into(), json!(padding));
p.insert("colorModel".into(), json!(model));
p.insert("clippingMask".into(), json!(clip));
Ok(p)
}
/// The ids of the source art `d` names for `rasterize` in the document `doc`: one page item, or a
/// list of them, none inside another listed one. The command checks that none is listed twice or
/// locked.
fn sources(h: &Host, doc: Doc, d: &Data) -> std::result::Result<Vec<u64>, HostError> {
let list: Vec<&Data> = match d {
Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("rasterize takes at most {MAX_LISTED} objects"))),
Data::Array(a) => a.iter().collect(),
Data::Undefined | Data::Null => return Err(HostError::Type("rasterize needs the source art, a page item or a list of them".into())),
d => vec![d],
};
if list.is_empty() {
return Err(HostError::Error("rasterize needs at least one page item".into()));
}
h.charge_call(16 * list.len() as u64)?;
let mut ids = Vec::with_capacity(list.len());
for d in list {
let item = item_of(h, d)?;
if item.doc.uid != doc.uid {
return Err(HostError::Error(OTHER_DOCUMENT.into()));
}
ids.push(item.id.0);
}
let listed: std::collections::HashSet<u64> = ids.iter().copied().collect();
let inside = with_doc(h, doc, |_, st| {
ids.iter().find_map(|id| {
let up = st.doc.ancestry(crate::NodeId(*id))?;
up.iter().any(|a| a.0 != *id && listed.contains(&a.0)).then_some(())
})
});
if inside.is_some() {
return Err(HostError::Error("a source page item is inside another one, which is listed too".into()));
}
Ok(ids)
}
/// `document.rasterize(sourceArt, clipBounds?, options?)`: `object.rasterize` of the source art,
/// which the image replaces in one undo step. → the new `RasterItem`.
fn doc_rasterize(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let ids = sources(h, doc, arg(a, 1))?;
let clip = clip_bounds(h, doc, arg(a, 2))?;
let mut p = rasterize_params(options(arg(a, 3), "RasterizeOptions")?)?;
p.insert("ids".into(), json!(ids));
if let Some(r) = clip {
p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1]));
}
// The image's id is read from the command's own result inside the run's savepoint, so an id
// that a script number cannot hold exactly still names the image, and a missing one undoes the edit.
let (r, image) = on_doc(h, doc.uid, true, |h| {
let (r, value) = command_value(h, "object.rasterize", &Value::Object(p))?;
let image = value.get("imageId").and_then(Value::as_u64).ok_or_else(|| HostError::Error("the image was not made".into()))?;
Ok((r, image))
})?;
super::save_open::command_warnings(h, "rasterize", &r);
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
Ok(item_ref(h, st, crate::NodeId(image)))
}
// ---- Image capture ----
/// A channel of `matteColor`: a finite number from 0 to 255.
fn channel(items: &[(String, Data)], key: &str) -> std::result::Result<u8, HostError> {
let d = items.iter().find(|(k, _)| k == key).map_or(&Data::Undefined, |(_, v)| v);
let n = number_in(d, &format!("ImageCaptureOptions.matteColor.{key}"), 0.0, 255.0)?;
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let byte = n.round() as u8;
Ok(byte)
}
/// The capture's resolution and `document.export`'s `background` and `antiAlias` for the
/// `ImageCaptureOptions` fields `items` (`None`: the defaults).
fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f64, String, &'static str), HostError> {
let (mut anti_alias, mut matte, mut clear, mut ppi) = (false, false, false, 150.0);
let mut color = [255u8; 3];
for (k, v) in items.unwrap_or_default() {
if matches!(v, Data::Undefined) {
continue;
}
let what = format!("ImageCaptureOptions.{k}");
match k.as_str() {
"antiAliasing" => anti_alias = boolean(v, &what)?,
"matte" => matte = boolean(v, &what)?,
"transparency" => clear = boolean(v, &what)?,
"resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?,
"matteColor" => {
let Data::Object(c) = v else { return Err(HostError::Type(format!("{what} must be an RGBColor"))) };
color = [channel(c, "red")?, channel(c, "green")?, channel(c, "blue")?];
}
_ => {}
}
}
let background = if clear {
"transparent".to_string()
} else if matte {
format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2])
} else {
"white".to_string()
};
Ok((ppi, background, if anti_alias { "art" } else { "none" }))
}
/// The files a capture must not write over: the open documents' files and the files their linked
/// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns
/// and brushes included), with a DCS image's plate files, also when a file is missing, in the form
/// [`placed`] gives. A link's places are the ones opening the document looks at: its stored path
/// from the document's folder and its relative path from the folder of the file the document was
/// read from (a template opened as an untitled document has no file of its own), with a DCS
/// image's plate files beside each. The documents the interface has open while the run's slice
/// runs, such as one opened while the run was paused, count too.
fn sources_on_disk(h: &Host) -> Vec<Placed> {
let s = h.session.borrow();
let interface = h.interface_docs.borrow();
let mut paths: Vec<String> = Vec::new();
for st in s.documents().iter().chain(interface.iter()) {
paths.extend(st.path.clone());
paths.extend(crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st)));
}
paths.iter().filter_map(|p| source_place(p)).collect()
}
/// An open document or linked file inside the automation read or write roots: one that only a write
/// root covers is compared too, since a capture may write there. A path outside both is left out
/// before it is looked up, as no capture can write it; the refusal names only the requested path.
fn source_place(path: &str) -> Option<Placed> {
if crate::file_access::check_read(path).is_err() && crate::file_access::check_write_unrecorded(path).is_err() {
return None;
}
placed(std::path::Path::new(path))
}
/// A file as its folder's real path and its name.
type Placed = (std::path::PathBuf, std::ffi::OsString);
/// `p` as its folder's real path and its file name: from its real path with links followed, or,
/// for a file that is not there, from its folder's real path. `None` when neither the file nor its
/// folder is there.
fn placed(p: &std::path::Path) -> Option<Placed> {
let real = std::fs::canonicalize(p).ok().or_else(|| Some(std::fs::canonicalize(p.parent()?).ok()?.join(p.file_name()?)))?;
Some((real.parent()?.to_path_buf(), real.file_name()?.to_os_string()))
}
/// Whether two [`placed`] files are one file: the same folder, and the same name, or names that
/// differ only in letter case in a folder whose volume ignores case, or only in their Unicode
/// normalization form in a folder whose volume ignores that.
fn same_file(a: &Placed, b: &Placed) -> bool {
if !same_folder(&a.0, &b.0) {
return false;
}
if a.1 == b.1 {
return true;
}
let (x, y) = (a.1.to_string_lossy(), b.1.to_string_lossy());
let form = |s: &str| unicode_normalization::UnicodeNormalization::nfc(s).collect::<String>();
if form(&x) == form(&y) {
return ignores_normalization(&a.0);
}
let (lx, ly) = (x.to_lowercase(), y.to_lowercase());
if form(&lx) != form(&ly) || !ignores_case(&a.0) {
return false;
}
lx == ly || ignores_normalization(&a.0)
}
/// Whether file names in the real folder `folder` ignore their Unicode normalization form: the
/// first of the folder's first 256 entries whose name changes between the composed (NFC) and
/// decomposed (NFD) forms, and that is not a symbolic link, is looked up in the other form, and
/// names ignore the form when that finds the same entry. With no such entry, names ignore the form
/// on macOS, whose volumes (APFS and HFS+) look names up that way, and on Linux in a folder that
/// carries the casefold inode flag ([`casefolded`]): ext4 and f2fs casefolding also ignores the
/// form, as they are taken to when the flag can't be read. Elsewhere names keep the form.
fn ignores_normalization(folder: &std::path::Path) -> bool {
use unicode_normalization::UnicodeNormalization;
for entry in std::fs::read_dir(folder).into_iter().flatten().flatten().take(256) {
let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue };
let (c, d): (String, String) = (name.nfc().collect(), name.nfd().collect());
let other = if name == c { d } else { c };
if other != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) {
return finds_same(&entry.path(), &folder.join(other));
}
}
#[cfg(target_os = "linux")]
{
casefolded(folder)
}
#[cfg(not(target_os = "linux"))]
{
cfg!(target_os = "macos")
}
}
/// `FS_CASEFOLD_FL` from Linux's `include/uapi/linux/fs.h`: the folder looks names up casefolded.
#[cfg(target_os = "linux")]
const FS_CASEFOLD_FL: u32 = 0x4000_0000;
/// Whether the Linux folder `folder` carries the casefold inode flag, read with
/// `FS_IOC_GETFLAGS`. `true` when the folder can't be opened or its flags can't be read: `false`
/// only when the flags are read and the flag is clear.
#[cfg(target_os = "linux")]
fn casefolded(folder: &std::path::Path) -> bool {
std::fs::File::open(folder).ok().and_then(|d| rustix::fs::ioctl_getflags(&d).ok()).is_none_or(|f| has_casefold(f.bits()))
}
/// Whether the inode flags `bits` include `FS_CASEFOLD_FL`.
#[cfg(target_os = "linux")]
fn has_casefold(bits: u32) -> bool {
bits & FS_CASEFOLD_FL != 0
}
/// The check `imageCapture` makes on the file it writes, `p`, given as written or as the real path
/// of its folder with its name: it is none of the `sources` ([`sources_on_disk`]), not one of them
/// under another name, and has no other hard links.
fn capture_target_check(p: &std::path::Path, sources: &[Placed], shown: &str) -> Result<(), String> {
let real = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
if placed(&real).is_some_and(|t| sources.iter().any(|s| same_file(&t, s) || same_identity(&real, &s.0.join(&s.1)))) {
return Err(format!("imageCapture cannot write over an open document or a file it links: {shown}"));
}
if has_other_links(&real) {
return Err(format!("imageCapture cannot write over a file that has other hard links: {shown}"));
}
Ok(())
}
#[cfg(test)]
thread_local! {
/// Run once in `imageCapture` after its checks and before its export, for tests that change the
/// destination in between.
pub(crate) static BEFORE_CAPTURE_EXPORT: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
}
/// Whether two real paths are one file or folder: the same path, or, on Unix, the same device and
/// file number, so a path spelled in another letter case on a volume that ignores case still
/// matches. On Windows a real path carries the letter case stored on disk.
fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if a == b {
return true;
}
if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) {
return x.dev() == y.dev() && x.ino() == y.ino();
}
false
}
#[cfg(not(unix))]
{
a == b
}
}
/// Whether two existing paths name one file on disk, such as two hard links to it: the same device
/// and file number on Unix, or the same volume and file index on Windows. `false` when either is
/// missing.
fn same_identity(a: &std::path::Path, b: &std::path::Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
matches!((std::fs::metadata(a), std::fs::metadata(b)), (Ok(x), Ok(y)) if (x.dev(), x.ino()) == (y.dev(), y.ino()))
}
#[cfg(windows)]
{
same_file::is_same_file(a, b).unwrap_or(false)
}
#[cfg(not(any(unix, windows)))]
{
let _ = (a, b);
false
}
}
/// Whether the existing file at `p` has more than one name on Unix: writing into it in place, when
/// its folder refuses a replacement, would change the file under its other names too. Always
/// `false` off Unix, where [`same_identity`] compares the protected files instead.
fn has_other_links(p: &std::path::Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.nlink() > 1)
}
#[cfg(not(unix))]
{
let _ = p;
false
}
}
/// Whether `other`, a spelling of `entry` in other letter case, finds `entry` itself and not a
/// symbolic link or another file.
fn finds_same(entry: &std::path::Path, other: &std::path::Path) -> bool {
if !std::fs::symlink_metadata(other).is_ok_and(|m| !m.file_type().is_symlink()) {
return false;
}
match (std::fs::canonicalize(entry), std::fs::canonicalize(other)) {
(Ok(a), Ok(b)) => same_folder(&a, &b),
_ => false,
}
}
/// `name` with the letter case of every ASCII letter swapped, and other characters as they are.
fn swapped_case(name: &str) -> String {
name.chars().map(|c| if c.is_ascii_lowercase() { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() }).collect()
}
/// Whether file names in the real folder `folder` ignore letter case. Names keep case when two of
/// the folder's first 256 entries differ only in the case of ASCII letters. Otherwise the first of
/// them whose name has an ASCII letter and that is not a symbolic link is looked up with the case
/// of those letters swapped: names ignore case when that finds the same entry. With no such entry
/// on macOS, where a whole volume either ignores or keeps case, the nearest folder at or above
/// `folder` whose name has an ASCII letter, with its parent on the same volume, is looked up the
/// same way in its parent. When neither tells, names are taken to ignore case.
fn ignores_case(folder: &std::path::Path) -> bool {
let entries: Vec<std::fs::DirEntry> = std::fs::read_dir(folder).into_iter().flatten().flatten().take(256).collect();
let mut folded = std::collections::HashSet::new();
let names: std::collections::HashSet<String> = entries.iter().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
if !names.iter().all(|n| folded.insert(n.to_ascii_lowercase())) {
return false;
}
for entry in &entries {
let name = entry.file_name().to_string_lossy().into_owned();
let swapped = swapped_case(&name);
if swapped != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) {
return finds_same(&entry.path(), &folder.join(swapped));
}
}
#[cfg(target_os = "macos")]
for dir in folder.ancestors() {
use std::os::unix::fs::MetadataExt;
let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else { break };
let device = |p: &std::path::Path| std::fs::metadata(p).map(|m| m.dev()).ok();
let here = device(folder);
if here.is_none() || device(dir) != here || device(parent) != here {
break;
}
let name = name.to_string_lossy();
let swapped = swapped_case(&name);
if swapped != name {
return finds_same(dir, &parent.join(swapped));
}
}
true
}
/// `document.imageCapture(imageFile, clipBounds?, options?)`: `document.export` of a PNG of the
/// art inside `clipBounds`, or of all the visible art.
fn doc_image_capture(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let path = vectorcraft_js::file_ref_path(arg(a, 1)).ok_or_else(|| HostError::Type("imageCapture needs a File".into()))?;
let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase();
if !name.ends_with(".png") || name.len() <= ".png".len() {
return Err(HostError::Error("imageCapture writes a PNG file: give it a name that ends with .png".into()));
}
let clip = clip_bounds(h, doc, arg(a, 2))?;
let (ppi, background, anti_alias) = capture_settings(options(arg(a, 3), "ImageCaptureOptions")?)?;
let region = match clip {
Some(r) => r,
None => with_doc(h, doc, |_, st| crate::cmd::fileio::export_art_bounds(&st.doc, "png"))
.ok_or_else(|| HostError::Error("the document has no visible art to capture".into()))?,
};
check_size(region, ppi)?;
let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?;
let sources = sources_on_disk(h);
let shown = path.to_string();
// Checked here, and again as the export commits its file, so a destination changed into a link
// to a protected file while the art renders is refused too.
let guard = move |p: &std::path::Path| capture_target_check(p, &sources, &shown);
guard(&real).map_err(HostError::Error)?;
let plain = crate::cmd::findfiles::plain(real);
let Some(plain) = plain.to_str() else {
return Err(HostError::Error(format!("imageCapture cannot write to a path that is not valid UTF-8: {path}")));
};
let p = json!({
"path": plain,
"format": "png",
"rect": [region.x0, region.y0, region.width(), region.height()],
"ppi": ppi,
"background": background,
"antiAlias": anti_alias,
"includeArtboardFill": false,
});
#[cfg(test)]
BEFORE_CAPTURE_EXPORT.with(|f| f.borrow_mut().take().map(|f| f()));
h.disk.borrow_mut().exact = true;
let r = crate::file_access::with_write_guard(std::rc::Rc::new(guard), || on_doc(h, doc.uid, false, |h| command(h, "document.export", &p)));
h.disk.borrow_mut().exact = false;
super::save_open::command_warnings(h, "imageCapture", &r?);
Ok(Data::Undefined)
}
/// The members these add to `Document`.
pub(super) fn document_members(l: &Link) -> Vec<Described> {
let mut members = named(vec![
(
"rasterize",
method(l, doc_rasterize),
returns("RasterItem", &[("sourceArt", "*"), ("clipBounds", "Array"), ("options", "RasterizeOptions")]),
),
(
"imageCapture",
method(l, doc_image_capture),
returns("undefined", &[("imageFile", "File"), ("clipBounds", "Array"), ("options", "ImageCaptureOptions")]),
),
]);
members.push(later(l, "Document", "windowCapture"));
members
}
/// The fields a new options object starts with.
type Starts = fn() -> Vec<(&'static str, Data)>;
fn rasterize_starts() -> Vec<(&'static str, Data)> {
vec![
("antiAliasingMethod", text("AntiAliasingMethod.ARTOPTIMIZED")),
("backgroundBlack", Data::Bool(false)),
("clippingMask", Data::Bool(false)),
("colorModel", text("RasterizationColorModel.DEFAULTCOLORMODEL")),
("convertSpotColors", Data::Bool(false)),
("convertTextToOutlines", Data::Bool(false)),
("includeLayers", Data::Bool(false)),
("padding", num(0.0)),
("resolution", num(300.0)),
("transparency", Data::Bool(false)),
]
}
fn capture_starts() -> Vec<(&'static str, Data)> {
let white = Data::Object(vec![
("typename".to_string(), text("RGBColor")),
("red".to_string(), num(255.0)),
("green".to_string(), num(255.0)),
("blue".to_string(), num(255.0)),
]);
vec![
("antiAliasing", Data::Bool(false)),
("matte", Data::Bool(false)),
("matteColor", white),
("resolution", num(150.0)),
("transparency", Data::Bool(false)),
]
}
/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its
/// help page gives.
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
let all: [(&'static str, Starts); 2] = [("RasterizeOptions", rasterize_starts), ("ImageCaptureOptions", capture_starts)];
all.into_iter()
.map(|(name, starts)| {
let l = link.clone();
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
current(&l)?.charge_call(64)?;
let mut items = vec![("typename".to_string(), text(name))];
items.extend(starts().into_iter().map(|(k, v)| (k.to_string(), v)));
Ok(Data::Object(items))
});
HostClass { construct: Some(f), ..class(name, None, Vec::new(), None) }
})
.collect()
}
#[cfg(test)]
mod source_tests {
use super::*;
#[test]
fn capture_sources_keep_files_outside_automation_read_roots() {
let dir = vectorcraft_testkit::TempDir::new("capture-source-roots");
let readable = dir.join("readable");
let writable = dir.join("writable");
std::fs::create_dir(&readable).unwrap();
std::fs::create_dir(&writable).unwrap();
let inside = readable.join("doc.vectorcraft");
// An open document that only a write root covers: a capture to its path must still be
// refused.
let outside = writable.join("other.vectorcraft");
// Outside every root: no capture can write it, so it is not looked up.
let elsewhere = dir.join("linked.png");
std::fs::write(&inside, b"document").unwrap();
std::fs::write(&outside, b"document").unwrap();
std::fs::write(&elsewhere, b"linked").unwrap();
let roots = crate::file_access::AutomationRoots::new(&[&readable], &[&writable]).unwrap();
crate::file_access::confine(roots.as_ref(), || {
assert!(source_place(&inside.to_string_lossy()).is_some());
assert!(source_place(&elsewhere.to_string_lossy()).is_none());
let source = source_place(&outside.to_string_lossy()).expect("a source outside the read roots is still compared");
let target = placed(&outside).unwrap();
assert!(same_file(&target, &source));
});
}
/// In an empty Linux folder, names that differ only in their normalization form are one file
/// only when the folder is casefolded. On a folder without the flag they are distinct, and
/// nothing is written into the folder to find out.
#[cfg(target_os = "linux")]
#[test]
fn names_in_another_normalization_form_match_only_in_a_casefolded_empty_folder() {
let dir = vectorcraft_testkit::TempDir::new("capture-nfd-distinct");
let folder = std::fs::canonicalize(&*dir).unwrap();
let (linked, capture): (Placed, Placed) = ((folder.clone(), "cafe\u{301}.png".into()), (folder.clone(), "caf\u{e9}.png".into()));
assert_eq!(same_file(&capture, &linked), casefolded(&folder));
assert_eq!(std::fs::read_dir(&folder).unwrap().count(), 0);
}
/// A casefolded folder, which looks a name up in either normalization form, is recognized by
/// its inode flag. A folder whose flags can't be read is taken for one, so a capture is never
/// written over a source under a name in another normalization form.
#[cfg(target_os = "linux")]
#[test]
fn a_casefolded_folder_is_recognized_by_its_inode_flag() {
assert!(has_casefold(FS_CASEFOLD_FL));
assert!(has_casefold(FS_CASEFOLD_FL | 0x10));
assert!(!has_casefold(0x10));
assert!(!has_casefold(0));
let dir = vectorcraft_testkit::TempDir::new("capture-nfd-missing");
assert!(casefolded(&dir.join("missing")));
}
}
+21 -2
View File
@@ -19,8 +19,9 @@
//! commands may use.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - `saveAs` without options saves in the format the path's extension names; it writes the file
//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
//! - `saveAs` without options selects the format from the script's file name before resolving
//! symbolic links. A name without a recognized extension uses the document's current format.
//! Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
//! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds.
//! `exportFile` adds the format's extension unless the name already ends
//! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes
@@ -878,6 +879,24 @@ pub(super) fn exactly<T>(h: &Host, f: impl FnOnce() -> Result<T, HostError>) ->
r
}
/// Writes each warning in a command's answer `result` to the console after `method`'s name.
pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) {
if let Data::Object(items) = result {
for (key, value) in items {
let warnings: &[Data] = match (key.as_str(), value) {
("warning", Data::String(_)) => std::slice::from_ref(value),
("warnings", Data::Array(warnings)) => warnings,
_ => continue,
};
for warning in warnings {
if let Data::String(warning) = warning {
super::super::each_line(&format!("{method}: {warning}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
}
}
}
}
}
/// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s
/// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or
/// a linked image an open could not read. → the command's answer.
+154 -40
View File
@@ -1,4 +1,4 @@
//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its
//! Type in the script object model: the `textFrames` of a document, a layer and a group, each `TextFrame`, the `TextRange` of its
//! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and
//! `paragraphAttributes`, and `app.textFonts`, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/>,
@@ -8,6 +8,9 @@
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/> describe them.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A layer's or group's `textFrames` list the type directly in it, topmost first. Their `add()`,
//! `pointText`, `areaText` and `pathText` put the new type on top of its contents, and a hidden
//! or locked layer or group throws.
//! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so
//! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves
//! out to the whole character. One item of `characters` is one code point.
@@ -63,6 +66,10 @@ pub const STALE_RANGE: &str = "Stale text range";
/// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit
/// is stale.
const MAX_EDITS: usize = 100_000;
/// The most bytes the offset tables of the frames' indexes hold in a run. Past it the tables of
/// the other frames are given up; their text, generations and edits stay, and each frame's tables
/// are made again when it is next read.
const INDEX_BUDGET: usize = 64 << 20;
/// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units.
pub(super) struct Index {
@@ -106,6 +113,22 @@ impl Index {
Self { text, chars, bytes, words, paras }
}
/// The text alone, without its offset tables, for a frame whose tables were given up under
/// [`INDEX_BUDGET`]; [`observe`] makes them again before the index is read.
fn bare(text: String) -> Self {
Self { text, chars: Vec::new(), bytes: Vec::new(), words: Vec::new(), paras: Vec::new() }
}
fn is_bare(&self) -> bool {
self.chars.is_empty()
}
/// The bytes the offset tables hold.
fn table_bytes(&self) -> usize {
let pairs = self.words.capacity() + self.paras.capacity();
(self.chars.capacity() + self.bytes.capacity()) * size_of::<usize>() + pairs * size_of::<(usize, usize)>()
}
fn len(&self) -> usize {
self.chars.last().copied().unwrap_or(0)
}
@@ -206,10 +229,32 @@ pub(in crate::script) struct TextState {
made: Cell<u64>,
/// The span of each range object, by its number, whose `length` the script set.
resized: RefCell<HashMap<u64, (usize, usize, u64)>>,
/// The bytes the offset tables of the frames' indexes hold ([`INDEX_BUDGET`]).
table_bytes: Cell<usize>,
/// The styles the run's style objects name.
styles: styles::StyleState,
}
/// Puts `index` in the log of frame `key` and keeps the offset tables of all the frames within
/// [`INDEX_BUDGET`], giving up the tables of other frames first.
fn set_index(state: &TextState, frames: &mut HashMap<(u64, u64), Log>, key: (u64, u64), index: Index) {
let mut total = state.table_bytes.get() + index.table_bytes();
if let Some(l) = frames.get_mut(&key) {
total -= l.index.table_bytes();
l.index = Rc::new(index);
}
for (k, l) in frames.iter_mut() {
if total <= INDEX_BUDGET {
break;
}
if *k != key && !l.index.is_bare() {
total -= l.index.table_bytes();
l.index = Rc::new(Index::bare(l.index.text.clone()));
}
}
state.table_bytes.set(total);
}
fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> {
match &st.doc.node(id)?.kind {
NodeKind::Text(t) => Some(t),
@@ -235,29 +280,36 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc<Index
let mut frames = h.dom.text.frames.borrow_mut();
let key = (st.uid, id.0);
let now = Arc::as_ptr(&st.doc);
match frames.get_mut(&key) {
Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {}
let fresh = match frames.get_mut(&key) {
Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => None,
Some(l) => {
if l.reverts != st.reverts || !same_text(t, &l.index.text) {
let changed = l.reverts != st.reverts || !same_text(t, &l.index.text);
if changed {
l.stamp += 1;
l.floor = l.stamp;
l.edits.clear();
l.index = Rc::new(Index::new(t.plain_text()));
}
l.doc = Arc::downgrade(&st.doc);
l.reverts = st.reverts;
changed.then(|| t.plain_text())
}
None => {
let l = Log {
doc: Arc::downgrade(&st.doc),
reverts: st.reverts,
index: Rc::new(Index::new(t.plain_text())),
index: Rc::new(Index::bare(String::new())),
stamp: 0,
floor: 0,
edits: VecDeque::new(),
};
frames.insert(key, l);
Some(t.plain_text())
}
};
// Tables given up under the budget are made again from the text the log keeps.
let fresh = fresh.or_else(|| frames.get(&key).filter(|l| l.index.is_bare()).map(|l| l.index.text.clone()));
if let Some(text) = fresh {
set_index(&h.dom.text, &mut frames, key, Index::new(text));
}
let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
Ok((l.index.clone(), l.stamp))
@@ -348,9 +400,9 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser
l.floor = l.stamp;
l.edits.clear();
}
l.index = Rc::new(Index::new(now));
l.doc = Arc::downgrade(&st.doc);
l.reverts = st.reverts;
set_index(&h.dom.text, &mut frames, (st.uid, item.id.0), Index::new(now));
Ok(())
})
}
@@ -776,7 +828,11 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
} else if handle_of(rel, "TextRange").is_some() {
span_of(h, rel, &["TextRange"])?
} else {
return Err(HostError::Type("relativeObject must be a TextRange or a TextFrame".into()));
// A range of a removed frame keeps its own error.
span_of(h, rel, &["TextRange"]).map_err(|e| match e {
HostError::Error(m) if m == STALE_RANGE => HostError::Error(m),
_ => HostError::Type("relativeObject must be a TextRange or a TextFrame".into()),
})?
};
if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id {
return Err(HostError::Error("relativeObject must be text of the same text frame".into()));
@@ -1312,32 +1368,46 @@ fn frame_ids(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, Ho
Ok(ids)
}
/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists.
fn frames_scope(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Option<NodeId>), HostError> {
super::layers::text_scope(h, arg(a, 0))
}
fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "TextFrames")
Ok(frames_scope(h, a)?.0)
}
/// The type objects a `TextFrames` of `container` lists: the document's ([`frame_ids`]), or those
/// directly in a layer or group, topmost first.
fn listed(h: &Host, st: &DocState, container: Option<NodeId>) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
match container {
None => frame_ids(h, st),
Some(c) => super::layers::text_list(h, st, c),
}
}
fn frames_length(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64)))
let (doc, c) = frames_scope(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| listed(h, st, c).map(|l| l.len()))? as u64)))
}
fn frames_parent(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
let (doc, c) = frames_scope(h, a)?;
Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c))))
}
fn frames_at(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, c) = frames_scope(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
with_doc(h, doc, |_, st| Ok(listed(h, st, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
}
fn frames_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, c) = frames_scope(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st)?;
let ids = listed(h, st, c)?;
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -1365,29 +1435,40 @@ fn vertical_of(d: &Data) -> std::result::Result<bool, HostError> {
}
}
/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`.
fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer {
/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`, on
/// top of the contents of `container` when there is one.
fn point_text(h: &Host, (doc, container): (Doc, Option<NodeId>), anchor: Option<[f64; 2]>, vertical: bool) -> Answer {
let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?;
let (_, r) =
on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?;
let mut params = json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical});
if let Some(c) = container {
check_open(h, doc, c)?;
if let Some(o) = params.as_object_mut() {
o.insert("parent".into(), json!(c.0));
}
}
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &params))?;
new_ref(h, doc, result_id(&r))
}
/// The error for a layer or group that takes no new type.
const SHUT_CONTAINER: &str = "the layer or group is hidden or locked";
/// `add()`: empty point type at the origin.
fn frames_add(h: &Host, a: &[Data]) -> Answer {
point_text(h, frames_doc(h, a)?, None, false)
point_text(h, frames_scope(h, a)?, None, false)
}
/// `pointText(anchor, orientation?)`.
fn frames_point_text(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let scope = frames_scope(h, a)?;
let anchor = point(arg(a, 1), "anchor")?;
point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?)
point_text(h, scope, Some(anchor), vertical_of(arg(a, 2))?)
}
/// Turns the path `d` names into area type or type on a path with `text.createInPath`.
/// Turns the path `d` names into area type or type on a path with `text.createInPath`, and moves
/// it on top of the contents of the collection's layer or group when there is one.
fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, container) = frames_scope(h, a)?;
if handle_of(arg(a, 1), "PathItem").is_none() {
return Err(HostError::Type("textPath must be a PathItem".into()));
}
@@ -1407,12 +1488,35 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
}
let mode = if on_path { "onPath" } else { "area" };
let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical});
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
let id = result_id(&r);
if let (Some((base, postfix)), Some(id)) = (base, id) {
threads::thread_new(h, base, id, postfix)?;
// Makes the type, threaded after or before the base frame when there is one.
let make = |h: &Host| -> std::result::Result<Option<NodeId>, HostError> {
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
let id = result_id(&r);
if let (Some((base, postfix)), Some(id)) = (base, id) {
threads::thread_new(h, base, id, postfix)?;
}
Ok(id)
};
let Some(c) = container else {
return new_ref(h, doc, make(h)?);
};
check_open(h, doc, c)?;
// The path is moved as well as converted, so it must be one that `move` takes.
if !with_doc(h, doc, |_, st| editable(&st.doc, path.id)) {
return Err(HostError::Error(format!("Cannot move PathItem {}: it is hidden or locked", path.id.0)));
}
new_ref(h, doc, id)
super::refuse_protected_edit(h, path)?;
let id = super::atomically(h, |h| {
let id = make(h)?.ok_or_else(|| HostError::Error("the command made no object".into()))?;
super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?;
Ok(id)
})?;
new_ref(h, doc, Some(id))
}
/// Refuses a hidden or locked layer or group as the place for new type.
fn check_open(h: &Host, doc: Doc, container: NodeId) -> std::result::Result<(), HostError> {
if with_doc(h, doc, |_, st| st.doc.is_editable(container)) { Ok(()) } else { Err(HostError::Error(SHUT_CONTAINER.into())) }
}
/// `areaText(textPath, orientation?, baseFrame?, postFix?)`.
@@ -1425,17 +1529,22 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
in_path(h, a, true, &[2, 3])
}
/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a
/// locked artboard, stops it first, as `PageItems.removeAll()` does.
/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or
/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does.
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st)?;
let (doc, c) = frames_scope(h, a)?;
let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| {
let ids = listed(h, st, c)?;
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
Ok::<_, HostError>((ids, refused, on_locked))
// Type that clips a group or layer releases its mask, so the object above it is not made
// the clipping path.
let released = super::masks_cleared_by(&st.doc, &ids);
// So would deleting the type above an image in an ordinary group named as a tracing.
let tracing = super::release_makes_tracing(&st.doc, &released, &ids) || super::removal_makes_tracing(&st.doc, &ids);
Ok::<_, HostError>((ids, refused, on_locked, released, tracing))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -1445,8 +1554,13 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
// A clip group named as a tracing, released with an image left first, would become one.
if tracing {
return Err(HostError::Error(super::NOT_A_TRACING.into()));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, &params)))?;
}
Ok(Data::Undefined)
}
@@ -1802,8 +1916,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
named(vec![
("typename", get(l, frames_typename), typed("string")),
("length", get(l, frames_length), typed("number")),
("parent", get(l, frames_parent), typed("Document")),
("index", method(l, frames_index), returns("number", &[("itemKey", "*")])),
("parent", get(l, frames_parent), typed("*")),
("index", method(l, frames_index), returns("TextFrame", &[("itemKey", "*")])),
("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])),
("add", method(l, frames_add), returns("TextFrame", &[])),
("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])),
+11 -1
View File
@@ -858,6 +858,9 @@ struct Host {
args: RefCell<(Data, u64)>,
/// The run's state of the script object model (`app`).
dom: dom::State,
/// While a slice runs: the documents the interface has open ([`World::docs`] of the run's
/// job), which a capture must not write over either. Empty between slices.
interface_docs: RefCell<Vec<DocState>>,
/// The actions `app.doScript` can play.
actions: Vec<actions::Playable>,
/// The index of each open document's active artboard as the run starts, by document uid. The
@@ -1374,7 +1377,10 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
// the open documents; it also reads the files the documents open when the run began link to, as the
// person left them. A document a script's command opened gives it no file.
let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect();
let gate = host.disk.borrow().gate(documents, host.linked());
// The linked files are fixed at the run's first step, also when that step is an exact open that gets none.
let linked = host.linked();
let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { linked };
let gate = host.disk.borrow().gate(documents, linked);
let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect();
let r = crate::file_access::with_script_gate(gate, || s.execute(id, params));
// What the command opened, changed or gave another file is not as the person left it.
@@ -2432,6 +2438,7 @@ impl Session {
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
dom: dom::State::new(self.documents(), heap_bytes),
interface_docs: RefCell::new(Vec::new()),
actions: request.actions,
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
artboard_picks,
@@ -2988,6 +2995,8 @@ fn failure_frame(report: &Value) -> (String, String) {
fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result::Result<Progress, RunError>, String> {
let depth = std::mem::replace(&mut s.depth, 0);
job.world.swap(s);
// The interface's documents are the host's to read during the slice, and the job's again after.
std::mem::swap(&mut job.world.docs, &mut *job.host.interface_docs.borrow_mut());
// The run's front document draws and converts through its own profiles, and the interface's
// again after the slice.
s.sync_front_profiles();
@@ -3021,6 +3030,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
s.script_in_run = false;
// A panic in a member that opened the fence for one command skips its own reset.
s.script_unfenced = None;
std::mem::swap(&mut job.world.docs, &mut *job.host.interface_docs.borrow_mut());
job.world.swap(s);
s.depth = depth;
s.sync_front_profiles();