Merge main into feat/scripts-export-for-screens

This commit is contained in:
dotCooCoo committed 2026-12-03 11:15:24 -08:00
commit 644a4e6b8c
359 files changed
+25364 -1598

No files matched your search

+3 -2
View File
@@ -254,7 +254,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
// passed over.
// A document whose active artboard the script chose uses that choice, not the one the run
// started with.
// started with, nor the Artboard tool's selection from the start of the run.
let chosen = h.session.borrow().active().and_then(|st| {
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
Some((st.uid, super::dom::active_artboard(st)))
@@ -263,7 +263,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
Some(chosen) => std::slice::from_ref(chosen),
None => h.active_artboards.as_slice(),
};
let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard };
let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !chosen.as_ref().is_some_and(|(c, _)| c == uid));
let start = Start { active, picks, batch: s.artboard };
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
let outer = h.session.borrow_mut().set_replaying(true);
let r = command(h, &s.id, &params);
+145 -41
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:
@@ -99,11 +99,17 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
mod clipboard;
mod colors;
mod defaults;
mod images;
pub(super) mod layers;
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;
@@ -111,11 +117,15 @@ mod tracing;
mod transform;
mod variables;
#[cfg(test)]
pub(crate) use paths::POINT_LOOKS;
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
/// What [`after_command`] compares with, taken before each command a script runs
/// ([`variables::before_command`]).
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<crate::doc::DataSet>)> {
tracing::before_command(h);
variables::before_command(h, id)
}
@@ -124,13 +134,6 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
variables::after_command(h, before);
}
mod colors;
mod defaults;
mod paths;
#[cfg(test)]
pub(crate) use paths::POINT_LOOKS;
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
/// The error for an object that was deleted, or that came from an earlier run.
@@ -218,9 +221,6 @@ pub(super) struct State {
/// Each path whose points the run read, as the run last saw it, by document uid and then path
/// id ([`paths`]).
point_nodes: RefCell<std::collections::HashMap<u64, std::collections::HashMap<u64, Arc<crate::doc::Node>>>>,
/// The path whose points the object model is writing with `path.setAnchors`, the only path
/// that command changes ([`paths`]).
one_path: Cell<Option<Item>>,
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
/// points it read ([`paths`]).
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
@@ -292,11 +292,13 @@ impl State {
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
/// document, the selection and the undo histories are as they were before it, with no undo step
/// and no change to the document's saved state, and the growth its commands were charged is not
/// counted.
/// counted. Point changes that wait in [`State`] are written first, so a failure in `f` does not
/// put them back.
fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
if h.dom.saving.get() {
return f(h);
}
flush(h)?;
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
let styles = text::styles::mark(h);
let mark = h.growth_mark();
@@ -426,7 +428,7 @@ pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> {
/// Notes the changes a command made to the points of the paths the run has read
/// ([`paths::see_all_points`]).
pub(super) fn see_points(h: &Host) {
pub(super) fn see_points(h: &Host) -> std::result::Result<(), HostError> {
paths::see_all_points(h)
}
@@ -459,7 +461,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() }
}
@@ -470,7 +472,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 {
@@ -495,6 +498,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()))
@@ -1065,7 +1071,7 @@ fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Res
/// is made active, so bounds it reads take in type that the switch measured again (in the
/// document's own composite fonts, [`Session::set_active`]).
fn edit_item_with<T>(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
paths::see_all_points(h);
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, f));
h.dom.editing.set(kept);
@@ -2333,13 +2339,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(", ");
@@ -2349,8 +2359,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)
}
@@ -2638,26 +2651,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 {
@@ -2830,11 +2856,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";
@@ -2983,6 +3053,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| {
@@ -2998,6 +3081,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,
@@ -3009,11 +3094,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.
@@ -3172,7 +3265,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} ]"))),
@@ -3255,9 +3348,18 @@ const ENUMS: &[(&str, &[&str])] = &[
/// holds.
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
text::install_enums(realm)?;
// An enumeration the save options also define (`SVGFontType`) is defined once, with every member.
let screens = save_open::screens::ENUMS.iter().filter(|(n, _)| !save_open::ENUMS.iter().any(|(m, _)| m == n));
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(screens).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) {
// An enumeration the save or rasterize options also define (`SVGFontType`, `AntiAliasingMethod`) is defined once,
// with every member.
let screens = save_open::screens::ENUMS.iter().filter(|(n, _)| !save_open::ENUMS.iter().chain(raster_capture::ENUMS).any(|(m, _)| m == n));
for (name, members) in ENUMS
.iter()
.chain(save_open::ENUMS)
.chain(screens)
.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}"))))));
@@ -3388,6 +3490,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",
@@ -3552,6 +3655,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
}
+36 -11
View File
@@ -302,8 +302,8 @@ fn may_read(h: &Host, path: &str) -> bool {
/// The real path of the `File` `d` gives as an image to place or relink: one the script may read
/// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of
/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no
/// error names the path.
/// at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is, and no error names the path.
/// What the file holds is checked by the command that places or relinks it, which reads it once.
fn image_path(h: &Host, d: &Data, what: &str) -> Result<String, HostError> {
let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?;
if path.len() > super::super::files::MAX_PATH_CHARS {
@@ -321,13 +321,21 @@ fn image_path(h: &Host, d: &Data, what: &str) -> Result<String, HostError> {
if meta.len() > MAX_PLACED_BYTES {
return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20)));
}
let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned();
// What the file holds, read the way `file.place` reads it, before the document changes.
let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?;
if field(&info, "pixelWidth").is_none() {
return Err(HostError::Error(NOT_AN_IMAGE.into()));
Ok(crate::cmd::findfiles::plain(real).to_string_lossy().into_owned())
}
/// Runs `f`, which places or relinks a file `image_path` gave, with `file.place` and `links.relink`
/// refusing a file that holds no image before the document changes: that refusal is
/// [`NOT_AN_IMAGE`], which does not name the path. The command reads the file once, for its check
/// and for the image it places.
fn image_only<T>(h: &Host, f: impl FnOnce(&Host) -> Result<T, HostError>) -> Result<T, HostError> {
let kept = h.session.borrow().image_only.replace(Some(true));
let r = f(h);
let refused = h.session.borrow().image_only.replace(kept) == Some(false);
match r {
Err(HostError::Error(_)) if refused => Err(HostError::Error(NOT_AN_IMAGE.into())),
r => r,
}
Ok(path)
}
// ---- PlacedItem ----
@@ -397,7 +405,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
// 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 (_, placed) = image_only(h, |h| 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 =
@@ -414,7 +422,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
fn placed_relink(h: &Host, a: &[Data]) -> Answer {
let item = this_of(h, a, "PlacedItem")?;
let path = image_path(h, arg(a, 1), "relink's file")?;
edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?;
image_only(h, |h| edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path})))?;
Ok(Data::Undefined)
}
@@ -473,7 +481,8 @@ fn area_of(m: Affine) -> bool {
/// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix.
/// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted
/// image is refused before anything changes; the matrix the image has already changes nothing.
/// image is refused before anything changes, and so is a locked or hidden image or one on a locked
/// artboard, as the transform methods refuse them; the matrix the image has already changes nothing.
fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
let item = this_of(h, a, cls)?;
let m = matrix_value(arg(a, 1))?;
@@ -484,6 +493,22 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
if n.is_distorted_image() {
return Err(HostError::Error(DISTORTED.into()));
}
// The transform methods' refusals: a locked or hidden image, one inside a locked or hidden
// layer or group, and one on a locked artboard, whether or not the matrix changes.
let d = &st.doc;
let line = d.ancestry(item.id);
let any = |f: fn(&vectorcraft_doc::Node) -> bool| {
line.as_ref().is_none_or(|l| l.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(f)))
};
if any(|n| n.locked) {
return Err(HostError::Error(format!("{}: {}", super::transform::LOCKED, item.id.0)));
}
if any(|n| !n.visible) {
return Err(HostError::Error(format!("{}: {}", super::transform::HIDDEN, item.id.0)));
}
if super::on_locked_artboard(h, st, item.id) {
return Err(HostError::Error(format!("{}: {}", super::transform::ON_LOCKED_ARTBOARD, item.id.0)));
}
let f = frame(st)?;
let target = Affine::new(match h.dom.coords.get() {
Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]],
+103 -22
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))
})?;
@@ -305,7 +309,14 @@ fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
fn layer_has_selected(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))))))
let selected = with_doc(h, doc, |_, st| {
// The scan is charged by every selected object it looks at.
let objects = &st.selection.objects;
let found = objects.iter().position(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)));
h.charge_call(found.map_or(objects.len(), |i| i + 1) as u64)?;
Ok::<_, HostError>(found.is_some())
})?;
Ok(Data::Bool(selected))
}
/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every
@@ -332,7 +343,7 @@ fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec<NodeId>) -> u64 {
fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer {
let on = boolean(arg(a, 1), "hasSelectedArtwork")?;
let (doc, id) = this_layer(h, a)?;
let (ids, over) = with_doc(h, doc, |_, st| {
let (ids, over) = with_doc(h, doc, |s, st| {
let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id));
let selected = &st.selection.objects;
h.charge_call(selected.len() as u64)?;
@@ -345,10 +356,31 @@ fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer {
// The walk is charged by every node it looks at, hidden and locked ones included, whether
// or not anything is added.
h.charge_call(count)?;
// While an object is isolated, the art that holds it is replaced by the isolated object,
// or by what an isolated group or other container holds, as Select All takes it.
let isolated = st.isolation.and_then(|i| st.doc.node(i));
let path = isolated.and_then(|c| st.doc.ancestry(c.id)).unwrap_or_default();
let editable = path.iter().all(|i| st.doc.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template()));
let mut candidates = Vec::with_capacity(art.len());
for o in art {
match isolated {
Some(_) if path.contains(&o) && !editable => {}
Some(c) if path.contains(&o) && c.is_container() => {
// The same walk as the layer's, through any sublayer the container holds.
let visited = collect_editable_art(c, &mut candidates);
h.charge_call(visited)?;
}
Some(c) if path.contains(&o) => candidates.push(c.id),
_ => candidates.push(o),
}
}
let mut have: std::collections::HashSet<NodeId> = selected.iter().copied().collect();
let mut ids = Vec::new();
for o in art {
if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
for o in candidates {
if have.contains(&o)
|| !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o)
|| (s.guides_locked() && crate::is_guide_path(&st.doc, o))
{
continue;
}
// Only art that would be added counts toward the limit.
@@ -642,6 +674,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 +796,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 +823,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 +883,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 +1036,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 +1073,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 +1090,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 +1111,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 +1394,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 +1592,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),
+171 -15
View File
@@ -1,9 +1,10 @@
//! The matrix functions of `app`, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> describe them. A matrix is a plain
//! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the
//! `typename` `"Matrix"`; each function other than `isEqualMatrix` and `isSingularMatrix` gives a
//! new record, those two give a boolean, and none changes the records passed to it.
//! record with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and
//! `mValueTY`; a record passed in needs only those six, and each record a function gives also has
//! the `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives
//! a new record, those two give a boolean, and none changes the records passed to it.
//!
//! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix
//! does (ISO 32000-1, 8.3.4), in script coordinates with Y up.
@@ -19,7 +20,7 @@
//! - An argument that is not a finite number, or a matrix with a value that is not one, throws a
//! `TypeError`; a result with a value too large for a number throws a `RangeError`.
use vectorcraft_js::{Data, HostError};
use vectorcraft_js::{Data, HostError, MemberInfo};
use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text};
@@ -54,6 +55,24 @@ pub(super) fn app_members(link: &Link) -> Vec<Described> {
("isEqualMatrix", method(l, is_equal), returns("boolean", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])),
("isSingularMatrix", method(l, is_singular), returns("boolean", &[("matrix", "Matrix")])),
])
.into_iter()
.map(|(name, member, info)| (name, member, with_defaults(info)))
.collect()
}
/// `info` with the defaults of its left-out number arguments, which `reflect` reports: 0 for a
/// translation and an angle, 100 for a horizontal scale. A left-out vertical scale is the
/// horizontal one, so it has no fixed default and its description says so.
fn with_defaults(mut info: MemberInfo) -> MemberInfo {
for a in &mut info.arguments {
match a.name.as_str() {
"deltaX" | "deltaY" | "angle" => a.default = Some(num(0.0)),
"scaleX" => a.default = Some(num(100.0)),
"scaleY" => a.description = Some("The vertical scale; when it is left out, the horizontal scale.".into()),
_ => {}
}
}
info
}
/// The record for `m`, or a `RangeError` when a value is not finite.
@@ -125,26 +144,29 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 {
// Each product is split into its rounded value and the part that rounding drops, both exact.
// The five parts are added one at a time into a list of values that do not overlap, smallest
// first, whose sum is exact (Shewchuk's expansion).
let product = |a: f64, b: f64| {
let (a, b) = (Wide::of(a), Wide::of(b));
let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e));
[Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)]
};
let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w));
let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow);
nearest(exact)
}
/// `a·b` as its rounded value and the part that rounding drops, both exact.
fn product(a: f64, b: f64) -> [Wide; 2] {
let (a, b) = (Wide::of(a), Wide::of(b));
let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e));
[Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)]
}
/// Values that do not overlap, smallest first, held without allocating. Each value added keeps at
/// most one more, so the five parts of a sum and the two of a comparison fit.
/// most one more, so the five parts of a sum, the two of a comparison and the sixteen of an
/// inverse's rounding test fit.
#[derive(Clone, Copy)]
struct Parts {
v: [Wide; 8],
v: [Wide; 16],
n: usize,
}
impl Parts {
const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 8], n: 0 };
const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 16], n: 0 };
fn as_slice(&self) -> &[Wide] {
&self.v[..self.n]
@@ -416,9 +438,143 @@ fn invert(_: &Host, a: &[Data]) -> Answer {
// Each value is divided by the determinant before it is brought back into the range of a
// number, and the translations are taken whole, so a finite inverse is not lost to an
// intermediate value. Adding 0 turns -0 into 0.
let over = |w: Wide| w.div(det).value() + 0.0;
let plain = |v: f64| over(Wide::of(v));
record([plain(d), plain(0.0 - b), plain(0.0 - c), plain(a), over(products_difference(c, f, d, e)), over(products_difference(b, e, a, f))])
let exact_det = || difference_parts(a, d, b, c);
let zero = Wide::of(0.0);
let plain = |v: f64| quotient(Wide::of(v), || [Wide::of(v), zero, zero, zero], det, exact_det);
record([
plain(d),
plain(0.0 - b),
plain(0.0 - c),
plain(a),
quotient(products_difference(c, f, d, e), || difference_parts(c, f, d, e), det, exact_det),
quotient(products_difference(b, e, a, f), || difference_parts(b, e, a, f), det, exact_det),
])
}
/// `a·d − b·c` as four exact parts.
fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] {
let neg = |w: Wide| Wide { m: 0.0 - w.m, e: w.e };
let ([p, p_lost], [q, q_lost]) = (product(a, d), product(b, c));
[p, p_lost, neg(q), neg(q_lost)]
}
/// The quotient of `num` by `det`, from their rounded values `num` and `det` and their exact parts.
/// The result is the rounded quotient, which is within a few steps of the exact one, except where
/// that would decide overflow wrongly. When the rounded quotient overflows or lies within eight
/// steps of the largest number, the exact quotient is compared with 2^1024 − 2^970, the halfway
/// point between the largest number and 2^1024: at it or past it the result is infinite. Below it
/// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact
/// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the
/// even one. When the rounded quotient is below 2^-1023, where every number is a multiple of the
/// smallest number, the result is the multiple whose halfway points to its neighbors hold the exact
/// quotient, ties to the even one, so a quotient just past half the smallest number is not rounded
/// to 0. The exact parts are worked out only then. Adding 0 turns -0 into 0.
fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 {
if num.m == 0.0 {
return 0.0;
}
let v = num.div(det).value() + 0.0;
// 2^1024 − 9·2^971, eight steps below the largest number.
let near_top = f64::MAX - 8.0 * pow2(971);
let tiny = f64::MIN_POSITIVE / 2.0;
if v.is_finite() && v.abs() < near_top && v.abs() >= tiny {
return v;
}
let (exact_num, exact_det) = (exact_num(), exact_det());
let sign = |parts: &[Wide]| match parts.iter().copied().fold(Parts::EMPTY, grow).as_slice().last() {
Some(w) if w.m < 0.0 => -1.0,
_ => 1.0,
};
let (sn, sd) = (sign(&exact_num), sign(&exact_det));
if v.abs() < tiny {
return small_quotient(v, &exact_num, &exact_det, sn, sd);
}
// The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each
// `j·m` is split into its rounded value and the part that rounding drops.
let past = |j: f64| {
let scaled = |w: Wide, s: f64, e: i32| Wide { m: w.m * s, e: w.e.saturating_add(e) };
let times_j = |w: Wide| {
let hi = j * w.m * sd;
let lo = (j * sd).mul_add(w.m, 0.0 - hi);
[Wide::new(hi, w.e.saturating_add(970)), Wide::new(lo, w.e.saturating_add(970))]
};
let sum = exact_num
.iter()
.map(|&w| scaled(w, sn, 0))
.chain(exact_det.iter().map(|&w| scaled(w, 0.0 - sd, 1024)))
.chain(exact_det.iter().flat_map(|&w| times_j(w)))
.fold(Parts::EMPTY, grow);
match sum.as_slice().last() {
Some(w) if w.m > 0.0 => 1,
Some(w) if w.m < 0.0 => -1,
_ => 0,
}
};
if past(1.0) >= 0 {
return f64::INFINITY;
}
if v.is_finite() {
return v;
}
let even = |x: f64| x.to_bits() & 1 == 0;
let mut top = f64::MAX;
for k in 1..16u8 {
let below = top.next_down();
match past(f64::from(2 * k + 1)) {
1 => return top * sn * sd,
0 => return if even(top) { top } else { below } * sn * sd,
_ => top = below,
}
}
top * sn * sd
}
/// The exact quotient of `exact_num` by `exact_det`, whose signs are `sn` and `sd`, rounded to a
/// multiple of the smallest number, ties to the even multiple, starting from the rounded quotient
/// `v`, which is below 2^-1023 and within a few steps of it.
fn small_quotient(v: f64, exact_num: &[Wide; 4], exact_det: &[Wide; 4], sn: f64, sd: f64) -> f64 {
let step = f64::from_bits(1);
// The sign of |num| − j·2^-1075·|det|, with each `j·m` split into its rounded value and the
// part that rounding drops. `j` is odd and below 2^53, so it is exact.
let past = |j: f64| {
let times_j = |w: Wide| {
let hi = j * w.m * sd;
let lo = (j * sd).mul_add(w.m, 0.0 - hi);
[Wide::new(0.0 - hi, w.e.saturating_sub(1075)), Wide::new(0.0 - lo, w.e.saturating_sub(1075))]
};
let sum = exact_num.iter().map(|&w| Wide { m: w.m * sn, e: w.e }).chain(exact_det.iter().flat_map(|&w| times_j(w))).fold(Parts::EMPTY, grow);
match sum.as_slice().last() {
Some(w) if w.m > 0.0 => 1,
Some(w) if w.m < 0.0 => -1,
_ => 0,
}
};
// `k` steps; dividing by the smallest number is exact.
let mut k = v.abs() / step;
let even = |k: f64| k % 2.0 == 0.0;
for _ in 0..8 {
match past(2.0 * k + 1.0) {
1 => k += 1.0,
0 => {
k = if even(k) { k } else { k + 1.0 };
break;
}
_ => {
if k == 0.0 {
break;
}
match past(2.0 * k - 1.0) {
-1 => k -= 1.0,
0 => {
k = if even(k) { k } else { k - 1.0 };
break;
}
_ => break,
}
}
}
}
k * step * sn * sd + 0.0
}
fn is_equal(_: &Host, a: &[Data]) -> Answer {
+349 -134
View File
@@ -17,7 +17,8 @@
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
//! artboard.
//! artboard. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a
//! range error when it is assigned.
//! - A path in a compound path or compound shape reads that owner's paint, which the paint
//! commands change in its place, and a gradient that `filled = true` gives it is placed on that
//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and
@@ -52,9 +53,7 @@
//! throws an error that says it is not available yet on a path inside a compound path, throws
//! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides
//! are locked; assigning the value the path has runs no command.
//! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and
//! `changeStrokePattern` given as different values throw an error; gradients move with the art,
//! so `changeFillGradients` false throws an error that says it is not available yet.
//! - The transforms are `PageItem`'s, with their rules in [`super::transform`].
use std::rc::Rc;
use std::sync::Arc;
@@ -69,9 +68,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf
use vectorcraft_tools::params::gradient_params;
use super::{
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, command_value,
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, later, method, named, num,
number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of,
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point,
point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
};
use crate::{DocState, NodeId, NodeKind};
@@ -108,16 +107,27 @@ fn cannot_edit(id: NodeId) -> HostError {
HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0))
}
/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or
/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one.
fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> {
/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is
/// hidden or locked, or it is on a locked artboard.
fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option<HostError> {
if !editable(&st.doc, id) {
return Err(cannot_edit(id));
Some(cannot_edit(id))
} else if super::on_locked_artboard(h, st, id) {
Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)))
} else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) {
Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)))
} else {
None
}
if super::on_locked_artboard(h, st, id) {
return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)));
}
/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin.
fn in_canvas(p: Point, what: &str) -> std::result::Result<Point, HostError> {
if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD {
Ok(p)
} else {
Err(HostError::Range(format!("{what} is outside the canvas")))
}
Ok(())
}
/// The path `d` names, which must still be in its document.
@@ -131,9 +141,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError
path_of(h, arg(a, 0))
}
/// The path of the run `run`, document `uid` and id parts `high` and `low`, as a handle gives them.
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them.
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result<Item, HostError> {
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) {
return Err(HostError::Error(STALE_ITEM.into()));
}
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
path_of(h, &path_ref(h, Item { doc, id }))
}
@@ -149,12 +162,10 @@ fn read_path<T>(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::d
})
}
/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count).
fn path_ref(h: &super::Host, item: Item) -> Data {
let s = h.session.borrow();
match s.documents().iter().find(|d| d.uid == item.doc.uid) {
Some(st) => host_ref("PathItem", &super::node_handle(h, st, item.id)),
None => Data::Null,
}
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
host_ref("PathItem", &handle)
}
/// The index of the first point of each subpath of `subs`, followed by the number of points.
@@ -219,6 +230,8 @@ fn points_of(h: &super::Host, item: Item) -> std::result::Result<usize, HostErro
/// The subpath and the place in it of point `i`, among the subpaths `subs`.
fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> {
for (s, sp) in subs.iter().enumerate() {
#[cfg(test)]
tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1));
if i < sp.anchors.len() {
return Some((s, i));
}
@@ -248,7 +261,7 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with
/// the path's other point changes until [`flush`] writes them. The first change of a path writes
/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path
/// locked or is on a locked artboard ([`protected`]), unless it changes nothing. A path
/// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its
/// points read as the grid snaps them.
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
@@ -264,10 +277,13 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
let (same, refused, aligned) = read_path(h, item, |st, _, pd| {
let d = &st.doc;
let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned)));
(pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned)
let same = pd.subpaths == subs;
(same, if same { None } else { protected(h, st, item.id) }, aligned)
})?;
if !same {
refused?;
if let Some(e) = refused {
return Err(e);
}
*h.dom.pending.borrow_mut() = Some((item, subs));
if aligned {
flush(h)?;
@@ -325,12 +341,50 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
}
let subpaths: Vec<Value> =
subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::<Vec<_>>(), "closed": sp.closed})).collect();
// Changes made before this one are looked at in full first.
see_all_points(h);
let kept = h.dom.one_path.replace(Some(item));
let r = edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}));
h.dom.one_path.set(kept);
r?;
super::atomically(h, |h| {
// The anchors and segments the new points no longer have leave the selection before the
// points are written. The undo step of the edit keeps the selection from before that, so
// undoing it selects them again.
let mut kept = None;
if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) {
kept = Some(st.selection.clone());
let selection = &mut st.selection;
if let Some(anchors) = selection.anchors.get_mut(&item.id) {
anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len()));
}
if let Some(segments) = selection.segments.get_mut(&item.id) {
segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count()));
if segments.is_empty() {
selection.segments.remove(&item.id);
}
}
if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) {
selection.key_anchor = None;
}
if (selection.contains(item.id) || selection.anchors.contains_key(&item.id) || selection.segments.contains_key(&item.id))
&& (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty()))
{
selection.remove(item.id);
}
if kept.as_ref().is_some_and(|before| *before == st.selection) {
kept = None;
}
}
// The document as the edit's step keeps it, read after the switch to it, which can measure
// its type again.
let doc = super::edit_item_with(h, item, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone());
super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?;
Ok(doc)
})?;
if let Some((doc, selection)) = doc.zip(kept)
&& let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid)
&& let Some(step) = st.history.undo.last_mut().filter(|step| Arc::ptr_eq(&step.doc, &doc))
{
step.selection = Arc::new(selection);
}
Ok(())
})?;
Ok(())
}
@@ -340,26 +394,36 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node)
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
}
/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active
/// layer, then puts the drawing mode back.
fn drawing_normally<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal);
let r = f();
h.session.borrow_mut().draw_mode = kept;
r
/// Runs a path creation command with its layer placement recorded.
fn drawing_normally(h: &super::Host, parent: Option<NodeId>, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
let mut params = params.clone();
params["onLayer"] = json!(parent.map(|p| p.0));
super::command_value(h, id, &params)
}
/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which
/// must be one the user could edit ([`refuse_path_edit`]).
/// must be one the user could edit ([`protected`]).
/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the
/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put
/// back afterwards, so the edit changes only the path.
fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?;
if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) {
return Err(e);
}
if let Some(o) = params.as_object_mut() {
o.entry("ids").or_insert_with(|| json!([item.id.0]));
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") {
o.insert("objectOnly".into(), json!(true));
}
}
keeping_paint(h, || edit_item(h, item, id, &params))
let result = keeping_paint(h, || edit_item(h, item, id, &params))?;
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0)));
}
Ok(result)
}
/// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color
@@ -503,6 +567,11 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = path_items(h, st)?;
if h.session.borrow().menu.guides_locked
&& let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)));
}
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **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();
@@ -522,10 +591,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// The id in the result of a command that made an object, read from the command's own result so
/// that an id above 2^53 stays exact.
fn made_id(r: &Value) -> std::result::Result<NodeId, HostError> {
r["id"].as_u64().map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
/// The id in the JSON result of a command that made an object, read exactly, as the text creators
/// read it.
fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
}
/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept,
@@ -535,7 +604,8 @@ fn made_id(r: &Value) -> std::result::Result<NodeId, HostError> {
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
let made = keeping_paint(h, || {
on_doc(h, doc.uid, true, |h| {
let id = made_id(&drawing_normally(h, || command_value(h, id, params))?.1)?;
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
if reversed {
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
}
@@ -700,9 +770,10 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
let ap = h.session.borrow().new_art();
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
};
let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?.1)?;
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?;
if unpainted {
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]}))?;
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?;
}
Ok(id)
})
@@ -716,8 +787,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
fn path_points(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
let [high, low] = id_parts(item.id);
Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low]))
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
Ok(host_ref("PathPoints", &handle))
}
fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
@@ -728,7 +799,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
let closed = boolean(arg(a, 1), "closed")?;
let item = this_path(h, a)?;
edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
edit_points(h, item, |subs| {
if subs.is_empty() && closed {
subs.push(SubPath::new(Vec::new(), closed));
} else {
subs.iter_mut().for_each(|sp| sp.closed = closed);
}
})?;
Ok(Data::Undefined)
}
@@ -806,7 +883,7 @@ fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer {
if clipping {
return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0)));
}
see_all_points(h);
see_all_points(h)?;
let kept = h.dom.editing.replace(Some(item));
let r = on_doc(h, item.doc.uid, true, |h| {
command(h, "select.set", &json!({"ids": [item.id.0]}))?;
@@ -835,8 +912,8 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer {
let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?;
let c = h.dom.coords.get();
let anchors: Vec<Anchor> =
script.iter().map(|p| on_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] };
script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
let subs = if anchors.is_empty() && !closed { Vec::new() } else { vec![SubPath::new(anchors, closed)] };
write_path(h, item, subs)?;
cut_points(h, item);
Ok(Data::Undefined)
@@ -924,10 +1001,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul
Ok(match linked {
true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}),
true => json!({"swatch": name}),
false => json!({"color": colors::param(color)}),
false => json!({"color": colors::param(color), "keepModel": true}),
})
}
Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})),
Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})),
Paint::Gradient(g) => {
let mut g = g.clone();
if g.geom.is_some() || g.freeform.is_some() {
@@ -1180,6 +1257,20 @@ pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, c
Ok(((new_width - width).abs() > 1e-9).then_some(new_width))
}
/// The largest stroke weight in the path `item`'s own appearance, in points.
pub(super) fn largest_stroke_weight(h: &super::Host, item: Item) -> std::result::Result<f64, HostError> {
read_path(h, item, |_, n, _| {
n.appearance
.items
.iter()
.filter_map(|item| match item {
vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width),
vectorcraft_doc::AppearanceItem::Fill(_) => None,
})
.fold(0.0, f64::max)
})
}
/// Whether `item` is a path, so [`resized_stroke_weight`] applies to it.
pub(super) fn is_path(h: &super::Host, item: Item) -> bool {
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))
@@ -1200,8 +1291,8 @@ pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std
fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) };
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
let item = path_at(h, *run, *uid, *high, *low)?;
let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
flush_other(h, item)?;
Ok(item)
}
@@ -1240,8 +1331,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer {
}
fn point_ref(h: &super::Host, item: Item, i: usize) -> Data {
let [high, low] = id_parts(item.id);
host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))])
let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec();
handle.extend([float(i as u64), float(point_cuts(h, item))]);
host_ref("PathPoint", &handle)
}
/// How many times the points read of `item` have gone stale, after [`see_points`] notes a change
@@ -1293,7 +1385,10 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
POINT_LOOKS.with(|n| n.set(n.get() + 1));
let node = {
let s = h.session.borrow();
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned())
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| {
h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone());
node_arc(&st.doc, NodeId(key.1)).cloned()
})
};
// A path that is gone makes its points stale, so that an undo that brings it back leaves them
// stale.
@@ -1316,55 +1411,81 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
/// change that a later command reverses still makes the points stale. Paths under the object that
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
/// object model's own, and their points stay valid. A document that is the one the run last looked
/// at is skipped, as are its paths. While the object model writes one path's points
/// ([`super::State`]'s `one_path`), only that path and tracked paths in its outermost enclosing
/// Objects on Path group are looked at in its document.
pub(super) fn see_all_points(h: &super::Host) {
let keys: Vec<(u64, u64)> = {
let seen = h.dom.point_nodes.borrow();
if seen.values().all(|paths| paths.is_empty()) {
return;
}
/// at is skipped, as are its paths. The look is charged by the objects it looks at.
pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostError> {
let (keys, looked_at): (Vec<(u64, u64)>, u64) = {
let s = h.session.borrow();
let mut docs = h.dom.point_docs.borrow_mut();
let one = h.dom.one_path.get();
let seen = h.dom.point_nodes.borrow();
let mut keys = Vec::new();
// The documents that changed since the last look, kept as they are now.
for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) {
// Editing a path in an Objects on Path group can move other paths in the group.
let mut moved = Vec::new();
match s.documents().iter().find(|d| d.uid == *uid) {
Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue,
Some(st) => {
if let Some(item) = one.filter(|i| i.doc.uid == *uid) {
let d = &st.doc;
let group = d.ancestry(item.id).and_then(|a| {
a.into_iter().filter_map(|id| d.node(id)).find(|g| vectorcraft_doc::objects_on_path::is_objects_on_path(g))
});
if let Some(g) = group {
g.walk(&mut |n: &crate::doc::Node| {
if n.id != item.id && paths.contains_key(&n.id.0) {
moved.push((*uid, n.id.0));
}
});
let mut looked_at = 0u64;
docs.retain(|uid, before| {
let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc);
if after.is_some_and(|after| Arc::ptr_eq(before, after)) {
return true;
}
// A document none of whose paths the run still holds points of is not looked at; reading
// points again keeps it as it is then.
if seen.get(uid).is_none_or(std::collections::HashMap::is_empty) {
return false;
}
// Editing a path in an Objects on Path group can move the other paths in the group, so
// the outermost such group is looked at in place of the path.
// Each node is paired with the node of the same id under the same parent now, so that no
// node is searched for through the whole document.
let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) {
Some(item) => {
let group = before
.ancestry(item.id)
.and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)));
let id = group.unwrap_or(item.id);
node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id)))).into_iter().collect()
}
None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at),
};
// A group that moved to another parent keeps its node, so a node with children that is
// not found under its old parent is looked for among all the nodes now, listed once.
let mut all: Option<std::collections::HashMap<NodeId, &Arc<crate::doc::Node>>> = None;
while let Some((node, mut now)) = todo.pop() {
looked_at += 1;
if now.is_none()
&& node.children().is_some()
&& let Some(d) = after
{
let all = all.get_or_insert_with(|| {
let mut m = std::collections::HashMap::new();
let mut stack: Vec<&Arc<crate::doc::Node>> = d.layers.iter().collect();
while let Some(n) = stack.pop() {
m.insert(n.id, n);
stack.extend(n.children().into_iter().flatten());
}
}
docs.insert(*uid, st.doc.clone());
looked_at += m.len() as u64;
m
});
now = all.get(&node.id).copied();
}
None => {
docs.remove(uid);
if now.is_some_and(|n| Arc::ptr_eq(node, n)) {
continue;
}
if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) {
keys.push((*uid, node.id.0));
}
if let Some(children) = node.children() {
todo.extend(paired(children, now.and_then(|n| n.children()), &mut looked_at));
}
}
match one {
Some(item) if item.doc.uid == *uid => {
keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0)));
keys.append(&mut moved);
}
_ => keys.extend(paths.keys().map(|id| (*uid, *id))),
if let Some(after) = after {
*before = after.clone();
true
} else {
false
}
}
keys
});
(keys, looked_at)
};
if looked_at > 0 {
h.charge_call(looked_at)?;
}
let editing = h.dom.editing.get();
for (uid, id) in keys {
let own = || match editing {
@@ -1377,6 +1498,20 @@ pub(super) fn see_all_points(h: &super::Host) {
};
see_points(h, (uid, id), own);
}
Ok(())
}
/// Pairs each node of `before` with the node of the same id in `after`, adding to `looked_at` the
/// nodes of `after` it looks at.
fn paired<'a>(
before: &'a [Arc<crate::doc::Node>],
after: Option<&'a Vec<Arc<crate::doc::Node>>>,
looked_at: &mut u64,
) -> Vec<(&'a Arc<crate::doc::Node>, Option<&'a Arc<crate::doc::Node>>)> {
let after = after.map_or(&[][..], Vec::as_slice);
*looked_at += after.len() as u64;
let now: std::collections::HashMap<NodeId, &Arc<crate::doc::Node>> = after.iter().map(|n| (n.id, n)).collect();
before.iter().map(|n| (n, now.get(&n.id).copied())).collect()
}
fn points_at(h: &super::Host, a: &[Data]) -> Answer {
@@ -1444,8 +1579,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer {
/// point of the path removed or replaced since `this` was read.
pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) };
let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low)?;
let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
flush_other(h, item)?;
if whole(*cuts) != Some(point_cuts(h, item)) {
return Err(HostError::Error(STALE_POINT.into()));
@@ -1482,17 +1617,7 @@ fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Resul
let p = point(arg(a, 1), what)?;
let (item, _) = this_point(h, a)?;
let fr = with_doc(h, item.doc, |_, st| frame(st))?;
on_canvas(fr.to_document(h.dom.coords.get(), p), what)
}
/// `p`, a point a script gave in document coordinates, when it is on the canvas (within
/// [`crate::MAX_COORD`] of the origin); a `RangeError` otherwise.
fn on_canvas(p: Point, what: &str) -> std::result::Result<Point, HostError> {
if p.x.is_finite() && p.y.is_finite() && p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD {
Ok(p)
} else {
Err(HostError::Range(format!("{what} is outside the canvas")))
}
in_canvas(fr.to_document(h.dom.coords.get(), p), what)
}
fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer {
@@ -1560,12 +1685,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[
if held {
return true;
}
if !sel.contains(id) || sel.segments.contains_key(&id) {
if !sel.contains(id) {
return false;
}
match sel.partial(id) {
None => true,
Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)),
Some(picked) => locate(subs, i).is_some_and(|(s, j)| {
picked.contains(&(s, j))
&& !sel
.segments
.get(&id)
.is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j)))
}),
}
}
@@ -1577,12 +1708,19 @@ fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool {
/// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point
/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in
/// [`super::State`] are written first only when they add or remove points of this path, since
/// the selection names anchors by their place in the document's path.
/// [`super::State`] are written first when they add or remove points of this path or invalidate
/// selected segments.
fn pt_selected(h: &super::Host, a: &[Data]) -> Answer {
let (item, i) = this_point(h, a)?;
let moved = match &*h.dom.pending.borrow() {
Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?,
Some((waiting, subs)) if same_path(*waiting, item) => read_path(h, item, |st, _, pd| {
!same_layout(subs, &pd.subpaths)
|| st
.selection
.segments
.get(&item.id)
.is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count())))
})?,
_ => false,
};
if moved {
@@ -1650,22 +1788,31 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
let picked: Vec<usize> = read_path(h, item, |st, _, pd| {
let sel = &st.selection;
let held = held_selected(&st.doc, sel, item.id);
if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) {
if !held && !sel.contains(item.id) {
return Vec::new();
}
let mut out = Vec::new();
let mut first = 0;
let segments = sel.segments.get(&item.id);
let ends: std::collections::BTreeSet<_> = segments
.into_iter()
.flatten()
.filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())]))
.flatten()
.collect();
let partial = sel.partial(item.id).filter(|_| !held);
let mut picked = Vec::new();
let mut offset = 0;
for (s, sp) in pd.subpaths.iter().enumerate() {
let n = sp.anchors.len();
out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j));
first += n;
for j in 0..sp.anchors.len() {
if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) {
picked.push(offset + j);
}
}
offset += sp.anchors.len();
}
out
picked
})?;
h.charge_call(picked.len() as u64)?;
let [high, low] = id_parts(item.id);
let cuts = float(point_cuts(h, item));
let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect();
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
Ok(Data::Array(points))
}
@@ -1723,10 +1870,13 @@ fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option<crate::d
if !wait {
// The points are written first, and the selection is then set with selection
// commands, which the journal records with the edit.
// The current layer and the highlighted Layers rows are put back after the selection is set.
let (layer, rows) = with_doc(h, item.doc, |_, st| (st.active_layer, st.highlighted_rows()));
flush(h)?;
on_doc(h, item.doc.uid, false, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
super::restore_selection(h, &doc, &sel)
super::restore_selection(h, &doc, &sel)?;
super::restore_layer(h, item.doc.uid, layer, &rows)
})?;
}
}
@@ -1815,7 +1965,7 @@ pub(super) fn path_item_members(l: &Link) -> Vec<Described> {
),
("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap), typed("StrokeCap")),
("strokeJoin", property(l, path_stroke_join, path_set_stroke_join), typed("StrokeJoin")),
("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")),
("strokeMiterLimit", property(l, path_miter, path_set_miter), MemberInfo { min: Some(1.0), max: Some(500.0), ..typed("number") }),
("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")),
("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")),
("selectedPathPoints", get(l, path_selected_points), typed("Array")),
@@ -1897,13 +2047,78 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
#[cfg(test)]
mod tests {
use std::cell::Cell;
use super::*;
use crate::Session;
thread_local! {
pub(super) static LOCATE_STEPS: Cell<usize> = const { Cell::new(0) };
}
#[test]
fn selected_points_do_not_rescan_subpaths() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128];
s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap();
s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap();
LOCATE_STEPS.with(|steps| steps.set(0));
let out = s
.execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"}))
.unwrap();
assert_eq!(out["log"], json!([2]));
LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get()));
}
#[test]
fn undoing_a_point_write_selects_the_anchors_it_removed_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 3]]})).unwrap();
let source = "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 0], [10, 0], [10, 10]]); \
vc.log(p.selectedPathPoints.length); app.undo();";
let out = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap();
assert_eq!(out["log"], json!([1]));
let id = NodeId(id.as_u64().unwrap());
let anchors: Vec<(usize, usize)> = s.active().unwrap().selection.anchors.get(&id).map(|a| a.iter().copied().collect()).unwrap_or_default();
assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed");
}
#[test]
fn undoing_a_point_write_in_a_background_document_selects_its_anchors_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let text = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 3]]})).unwrap();
let uid = s.active().unwrap().uid;
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let st = s.document_mut(uid).unwrap();
let NodeKind::Text(t) = &mut Arc::make_mut(&mut st.doc).node_mut(NodeId(text)).unwrap().kind else { panic!("not a text object") };
t.cached_bounds = None;
let before_activation = st.doc.clone();
let source = "var d; for (var i = 0; i < app.documents.length; i++) { if (app.documents[i].pathItems.length) d = app.documents[i]; } \
d.pathItems[0].setEntirePath([[0, 0], [10, 0], [10, 10]]); app.activeDocument = d; app.undo();";
s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap();
let id = NodeId(id.as_u64().unwrap());
let st = s.documents().iter().find(|d| d.uid == uid).unwrap();
assert!(!Arc::ptr_eq(&st.doc, &before_activation));
assert!(matches!(&st.doc.node(NodeId(text)).unwrap().kind, NodeKind::Text(t) if t.cached_bounds.is_some()));
assert_eq!(st.doc.node(id).and_then(|n| n.path_data()).map(|pd| pd.subpaths[0].anchors.len()), Some(4));
let anchors: Vec<(usize, usize)> = st.selection.anchors.get(&id).map(|a| a.iter().copied().collect()).unwrap_or_default();
assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed");
}
#[test]
fn a_made_id_above_two_to_the_53_stays_exact() {
assert_eq!(made_id(&json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993)));
assert_eq!(made_id(&json!({"id": 7})), Ok(NodeId(7)));
assert!(made_id(&json!({"id": 1.5})).is_err());
assert!(made_id(&json!({})).is_err());
let made = |v: Value| made_id(&(Data::Undefined, v));
assert_eq!(made(json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993)));
assert_eq!(made(json!({"id": 7})), Ok(NodeId(7)));
assert!(made(json!({"id": 1.5})).is_err());
assert!(made(json!({})).is_err());
}
}
@@ -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")));
}
}
+29 -8
View File
@@ -20,8 +20,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
@@ -34,8 +35,8 @@
//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not
//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page
//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to
//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one
//! `unit`, more than 0 and at most 1000.
//! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is
//! one drawing unit. It is at least 0.0001 and at most 1000.
//! - An option the classes here map is applied; a listed option that is not mapped is accepted at
//! the default its help page gives and throws an error that says it is not available yet at any
//! other value; a property the help pages do not list throws an error that names it, unless it is
@@ -753,10 +754,12 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result:
Data::Number(n) if n.is_finite() => *n,
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
};
if !(n > 0.0 && n <= 1000.0) {
return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000")));
// A percentage: the DXF writer's `scale` is `n / 100`, and its smallest scale (1e-6) is
// 0.0001%.
if !(0.0001..=1000.0).contains(&n) {
return Err(HostError::Range(format!("{what} must be at least 0.0001 and at most 1000")));
}
p.insert("scale".into(), json!(n));
p.insert("scale".into(), json!((n / 100.0).max(*vectorcraft_cad::SCALE_RANGE.start())));
}
"version" => {
let version = match pick("AutoCADCompatibility")? {
@@ -893,6 +896,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.
@@ -1023,7 +1044,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into()));
}
// A raster file has one pixel per point at 100%, whatever the document's raster effects resolution.
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`.
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100.
if !matches!(kind.format, "svg" | "dxf") {
p.insert("scale".into(), json!(hs / 100.0));
}
+247 -60
View File
@@ -1,12 +1,16 @@
//! 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/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/> and
//! <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.
@@ -33,6 +37,8 @@
//! value; set on an empty range it changes nothing. A paragraph attribute reads the first
//! paragraph the range touches and sets every one of them. A text range has the members of
//! both its `characterAttributes` and its `paragraphAttributes`.
//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes
//! the paint away. `strokeWeight` is 0 to 1000 points.
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
@@ -40,13 +46,14 @@ use std::rc::Rc;
use std::sync::{Arc, Weak};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject};
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref};
use super::{
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item,
editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property,
returns, text, typed, typename_of, whole, with_doc,
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of,
doc_ref, edit_item, editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc,
page_items, point, property, returns, text, typed, typename_of, whole, with_doc,
};
use crate::{DocState, Document, NodeId, NodeKind};
@@ -59,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 {
@@ -102,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)
}
@@ -202,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),
@@ -231,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))
@@ -303,6 +359,27 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc<Index>, usize, usize, u
})
}
/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing
/// changed, when the frame or a layer or group it is in is hidden or locked, or the frame is on a
/// locked artboard.
fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
refuse_protected(h, item, "TextFrame")?;
edit_item(h, item, id, params)
}
/// Throws `Cannot edit` for the `class` object of `item` when it or a layer or group it is in is
/// hidden or locked, or it is on a locked artboard.
fn refuse_protected(h: &Host, item: Item, class: &str) -> std::result::Result<(), HostError> {
let (ok, on_locked) = with_doc(h, item.doc, |_, st| (editable(&st.doc, item.id), super::on_locked_artboard(h, st, item.id)));
if !ok {
return Err(HostError::Error(format!("Cannot edit {class} {}: it, or a layer or group it is in, is hidden or locked", item.id.0)));
}
if on_locked {
return Err(HostError::Error(format!("Cannot edit {class} {}: it is on a locked artboard", item.id.0)));
}
Ok(())
}
/// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`.
/// When the text is not what that edit gives, every earlier range goes stale.
fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> {
@@ -323,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(())
})
}
@@ -453,7 +530,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer {
return Ok(Data::Undefined);
}
let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count());
edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?;
edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?;
record(h, r.item, &index, s, e - s, &insert)?;
Ok(Data::Undefined)
}
@@ -547,6 +624,7 @@ fn new_ref(h: &Host, doc: Doc, id: Option<NodeId>) -> Answer {
/// `null` when the type has nothing to outline and the command removed it.
fn frame_outline(h: &Host, a: &[Data]) -> Answer {
let item = this_frame(h, a)?;
refuse_protected(h, item, "TextFrame")?;
let (_, r) = on_doc(h, item.doc.uid, true, |h| {
command(h, "select.set", &json!({"ids": [item.id.0]}))?;
super::command_value(h, "type.createOutlines", &json!({}))
@@ -568,6 +646,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer {
Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))),
Some(true) => {}
}
refuse_protected(h, item, "TextFrame")?;
let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" };
let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?;
new_ref(h, item.doc, result_id(&r).or(Some(item.id)))
@@ -730,35 +809,44 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
let (r, part) = this_part(h, a)?;
let contents = contents_of(arg(a, 1))?;
let (index, s, e, _) = resolve(h, r)?;
let at = if before || matches!(arg(a, 2), Data::Undefined) {
// The place, and whether it is the end of a range, which rounds up to a character boundary.
let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) {
let (items, spans) = part_spans(&index, part, s, e);
let span = |k: usize| match spans {
None => index.char_span(k),
Some(list) => list.get(k).copied(),
};
if before {
items.clone().next().and_then(span).map_or(s, |(x, _)| x)
(items.clone().next().and_then(span).map_or(s, |(x, _)| x), false)
} else {
items.clone().next_back().and_then(span).map_or(e, |(_, y)| y)
(items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true)
}
} else {
let rel = arg(a, 2);
let target = if handle_of(rel, "TextFrame").is_some() {
whole_span(h, item_of(h, rel)?)?.1
} else if handle_of(rel, "TextRange").is_some() {
span_of(h, rel, &["TextRange"])?
} else {
span_of(h, rel, &["TextRange"]).map_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()));
}
let (_, ts, te, _) = resolve(h, target)?;
if text_placement(arg(a, 3))? { te } else { ts }
if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) }
};
// A place inside a character (between the two halves of a surrogate pair) moves to its edge.
let b = index.byte(at, after);
let at = index.text[..b].encode_utf16().count();
if contents.is_empty() {
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
return Ok(range_ref(h, r.item, at, at, stamp, "TextRange"));
}
let b = index.byte(at, false);
let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next());
let (lead, trail) = match part {
Part::Characters => ("", ""),
@@ -774,7 +862,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
),
};
let insert = format!("{lead}{contents}{trail}");
edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?;
edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?;
record(h, r.item, &index, at, 0, &insert)?;
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
let start = at + lead.encode_utf16().count();
@@ -804,9 +892,12 @@ enum Attr {
Underline,
StrikeThrough,
TextFont,
FillColor,
StrokeColor,
StrokeWeight,
}
const ATTRS: [(&str, Attr); 11] = [
const ATTRS: [(&str, Attr); 14] = [
("size", Attr::Size),
("leading", Attr::Leading),
("autoLeading", Attr::AutoLeading),
@@ -818,6 +909,9 @@ const ATTRS: [(&str, Attr); 11] = [
("underline", Attr::Underline),
("strikeThrough", Attr::StrikeThrough),
("textFont", Attr::TextFont),
("fillColor", Attr::FillColor),
("strokeColor", Attr::StrokeColor),
("strokeWeight", Attr::StrokeWeight),
];
/// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with
@@ -920,11 +1014,28 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize)
Attr::Underline => Data::Bool(s.underline),
Attr::StrikeThrough => Data::Bool(s.strikethrough),
Attr::TextFont => font_ref(h, &s.font_family, &s.font_style),
Attr::FillColor => colors::of_paint(&s.fill),
Attr::StrokeColor => colors::of_paint(&s.stroke),
Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)),
}
}
/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after.
fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> {
/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a
/// `strokeWidth` it is given.
fn stroke_scale(t: &TextObject) -> f64 {
vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0)
}
/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after in
/// the document `doc` (a color as given when there is none).
fn attr_param(
h: &Host,
attr: Attr,
name: &str,
v: &Data,
first: (&TextObject, &CharStyle, usize),
doc: Option<&vectorcraft_doc::Document>,
) -> std::result::Result<(Value, Data), HostError> {
let finite = || number(v, name);
Ok(match attr {
Attr::Size => {
@@ -991,6 +1102,21 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &
let (family, style) = font_of(h, v)?;
(json!({"font": family, "style": style}), font_ref(h, &family, &style))
}
Attr::FillColor | Attr::StrokeColor => {
let color = colors::assigned(v, name)?;
let given = color.map_or_else(|| json!("none"), |c| colors::param(&c));
// The paint reads back as the text's document stores it: an RGB color in a CMYK document as CMYK.
let paint = color.map_or(Paint::None, |c| Paint::solid(doc.map_or(c, |d| crate::cmd::newart::stored_color_in(d, c))));
let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" };
(json!({ key: given }), colors::of_paint(&paint))
}
Attr::StrokeWeight => {
let n = finite()?;
if !(0.0..=1000.0).contains(&n) {
return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into()));
}
(json!({"strokeWidth": n}), num(n))
}
})
}
@@ -1021,10 +1147,11 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let styles = styles_in(t, ba, bb, false)?;
let first = styles.first().map(|(s, p)| (s.clone(), *p)).unwrap_or_else(|| (CharStyle::default(), 0));
let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?;
let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1), Some(&st.doc))?;
// A leading set on characters with auto leading fixes it even where auto gives that value.
let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants);
let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p));
// An empty range changes nothing, also one inside a character that `ba..bb` widens to it.
let unchanged = s == e || ba == bb || styles.iter().all(|(st, p)| has(st, *p));
let fixed = match (attr, &wants) {
(Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?),
_ => None,
@@ -1042,7 +1169,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
super::atomically(h, |h| {
for (start, end, leading) in &spans {
let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading});
edit_item(h, r.item, "text.setRangeStyle", &p)?;
edit_text(h, r.item, "text.setRangeStyle", &p)?;
}
Ok(())
})?;
@@ -1054,7 +1181,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
o.insert("start".into(), json!(ba));
o.insert("end".into(), json!(bb));
}
let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?;
let answer = edit_text(h, r.item, "text.setRangeStyle", &p)?;
if let Attr::TextFont = attr {
let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?;
@@ -1216,7 +1343,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
o.insert("start".into(), json!(ba));
o.insert("end".into(), json!(bb));
}
edit_item(h, r.item, id, &p)?;
edit_text(h, r.item, id, &p)?;
Ok(Data::Undefined)
}
@@ -1250,32 +1377,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()))
@@ -1303,29 +1444,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()));
}
@@ -1336,6 +1488,7 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) {
return Err(HostError::Error("TextFrames: path positions are not available yet".into()));
}
refuse_protected(h, path, "PathItem")?;
let (orientation, base) = if on_path { (4, 5) } else { (2, 3) };
let vertical = vertical_of(arg(a, orientation))?;
let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?;
@@ -1344,12 +1497,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?)`.
@@ -1362,17 +1538,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(", ");
@@ -1380,10 +1561,15 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
}
if !on_locked.is_empty() {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
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)
}
@@ -1557,6 +1743,7 @@ fn attr_type(attr: Attr) -> &'static str {
match attr {
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
Attr::TextFont => "TextFont",
Attr::FillColor | Attr::StrokeColor => "Color",
_ => "number",
}
}
@@ -1738,8 +1925,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")])),
+9 -2
View File
@@ -342,7 +342,8 @@ fn target_span(h: &Host, d: &Data) -> std::result::Result<Span, HostError> {
span_of(h, d, &TEXT)
}
/// `applyTo(textItem, clearingOverrides?)`.
/// `applyTo(textItem, clearingOverrides?)`. Throws `Cannot edit`, with nothing changed, when the
/// text frame is protected as for any other text edit.
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
let style = this_style(h, a)?;
let target = target_span(h, arg(a, 1))?;
@@ -355,6 +356,7 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Error("the text is in another document than the style".into()));
}
let (index, s, e, _) = resolve(h, target)?;
super::refuse_protected(h, target.item, "TextFrame")?;
h.charge_call(16 + (e - s) as u64)?;
let (start, end) = if style.para {
let (_, ba, bb) = para_range(&index, s, e);
@@ -429,6 +431,8 @@ fn char_value(h: &Host, attr: Attr, m: &Map<String, Value>) -> Data {
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
None => Data::Undefined,
},
// A style's colors and stroke weight are not available yet (`char_members`).
Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight => Data::Undefined,
}
}
@@ -467,7 +471,7 @@ fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
let leading = old.get("leading").and_then(Value::as_f64);
let sample = CharStyle { size, leading, ..base };
let t = TextObject::point(Point::default(), "", sample.clone());
let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?;
let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0), None)?;
let mut attrs = old.clone();
for (k, v) in param.as_object().into_iter().flatten() {
let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue };
@@ -538,6 +542,9 @@ fn char_members(link: &Link) -> Vec<Described> {
ATTRS
.iter()
.map(|&(name, attr)| {
if matches!(attr, Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight) {
return super::super::later(link, "CharacterAttributes", name);
}
let data_type = match attr {
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
Attr::TextFont => "TextFont",
+47 -5
View File
@@ -128,6 +128,10 @@ pub(super) struct State {
prev: RefCell<HashMap<(u64, u64), u64>>,
sources: RefCell<HashMap<(u64, u64), NodeId>>,
descendants: RefCell<HashMap<(u64, u64), HashSet<NodeId>>>,
/// For each document uid, stores the last noted revert count ([`crate::DocState::reverts`])
/// and the lowest id the run could allocate after the first note or the latest revert
/// ([`note_document`]).
marks: RefCell<HashMap<u64, (u64, u64)>>,
retraces: Cell<usize>,
}
@@ -208,6 +212,37 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) {
});
}
/// Before each command a script runs: notes the active document ([`note_document`]).
pub(super) fn before_command(h: &Host) {
let s = h.session.borrow();
if let Some(st) = s.active() {
note_document(h, st);
}
}
/// Records the next object id when the run first notes the document `st`. A revert resets
/// the mark to the reloaded document's next object id and keeps the descendant snapshots.
/// Loaded objects have ids below the mark; objects the run makes afterward have ids at or above it.
fn note_document(h: &Host, st: &crate::DocState) {
let mut marks = h.dom.tracing.marks.borrow_mut();
match marks.get_mut(&st.uid) {
Some((reverts, _)) if *reverts == st.reverts => {}
Some((reverts, mark)) => {
*reverts = st.reverts;
*mark = st.doc.peek_next_id();
}
None => {
marks.insert(st.uid, (st.reverts, st.doc.peek_next_id()));
}
}
}
/// Returns the lowest id the run could allocate in document `uid` after its first note or latest
/// revert ([`note_document`]).
fn mark(h: &Host, uid: u64) -> Option<u64> {
h.dom.tracing.marks.borrow().get(&uid).map(|(_, mark)| *mark)
}
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))
@@ -325,15 +360,22 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result<
/// 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| {
let (visited, result) = read_group(h, item, |st, group| {
note_document(h, st);
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.
// A tracing with a record is checked against the objects its trace made. A tracing without
// a record is checked against its first descendant snapshot, which survives reverts.
// If the group id is below the document's mark, members at or above the mark are also added.
// A revert resets the mark to the reloaded document's next object id.
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)?),
None => descendants.get(&(item.doc.uid, item.id.0)),
};
let newer = match made {
Some(_) => None,
None => mark(h, item.doc.uid).filter(|m| group.id.0 < *m),
};
let source = group.children().and_then(|c| c.first()).map(|n| n.id);
let mut visited = 0u64;
@@ -345,7 +387,7 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
(Some(m), _) => !m.contains(n.id),
(None, Some(ids)) => !ids.contains(&n.id),
(None, None) => false,
};
} || newer.is_some_and(|m| n.id.0 >= m);
// Added artwork is reported before a locked object, whichever comes first.
if added {
return Ok((visited, Err(HostError::Error(refusal.into()))));
+42 -14
View File
@@ -20,11 +20,16 @@
//! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own
//! scale in percent, the square root of the area it scales by (stroke weights and effects scale
//! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to
//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any
//! other value, and a scale of strokes and effects with positions left as they are, throws an
//! error that says so.
//! 100000, which sets the stroke weight to that percent of what it was, at most 1000 points.
//! When strokes and effects scale on a path, the scale and every stroke layer's resulting weight
//! must stay finite, and each weight can reach at most 1000 points. Any other value, and a scale
//! of strokes and effects with positions left as they are, throws an error that says so.
//! - A path without points takes any transformation about any point named. `DOCUMENTORIGIN`
//! still uses the first artboard's bottom-left corner; other named points use the origin.
//! Its linked opacity mask, strokes, effects and patterns transform with the same options.
//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a
//! locked object, and an object on a locked artboard are refused with nothing changed, and so are
//! locked object, an object on a locked artboard and a guide while guides are locked are refused
//! with nothing changed, and so are
//! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object
//! past the canvas.
@@ -36,13 +41,16 @@ use super::matrix::{self, Matrix};
use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc};
/// The error for an object on a locked artboard.
const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard";
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard";
/// The error for a locked object.
const LOCKED: &str = "cannot transform locked objects";
pub(super) const LOCKED: &str = "cannot transform locked objects";
/// The error for a guide while guides are locked.
const GUIDES_LOCKED: &str = "cannot transform a guide while guides are locked";
/// The error for a hidden object.
const HIDDEN: &str = "cannot transform hidden objects";
pub(super) const HIDDEN: &str = "cannot transform hidden objects";
/// The identity matrix.
const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
@@ -132,8 +140,17 @@ fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> {
}
/// The point of `r` (document coordinates, Y down) that the `Transformation` member `name`
/// ([`anchor_name`]) names.
fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result<Point, HostError> {
/// ([`anchor_name`]) names. Without bounds, a path uses the origin except for `DOCUMENTORIGIN`.
fn anchor(h: &Host, item: Item, r: Option<Rect>, name: &str) -> std::result::Result<Point, HostError> {
if r.is_none() && !paths::is_path(h, item) {
return Err(HostError::Error("the object has no bounds".into()));
}
if name == "DOCUMENTORIGIN" {
return with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])));
}
let Some(r) = r else {
return Ok(Point::ORIGIN);
};
let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
Ok(match name {
"TOPLEFT" => Point::new(r.x0, r.y0),
@@ -144,7 +161,6 @@ fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result<Poin
"BOTTOMLEFT" => Point::new(r.x0, r.y1),
"BOTTOM" => Point::new(cx, r.y1),
"BOTTOMRIGHT" => Point::new(r.x1, r.y1),
"DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?,
_ => Point::new(cx, cy),
})
}
@@ -215,12 +231,13 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
if on_locked {
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
}
// The identity acts the same about every point, so an object without bounds (an empty path)
// takes it too.
if h.session.borrow().menu.guides_locked && with_doc(h, item.doc, |_, st| crate::is_guide_path(&st.doc, item.id)) {
return Err(HostError::Error(format!("{GUIDES_LOCKED}: {}", item.id.0)));
}
// The identity acts the same about every point for any object.
let o = match (about, bounds) {
_ if m == IDENTITY => Point::ORIGIN,
(Some(name), Some(r)) => anchor(h, item, r, name)?,
(Some(_), None) => return Err(HostError::Error("the object has no bounds".into())),
(Some(name), r) => anchor(h, item, r, name)?,
(None, _) => Point::ORIGIN,
};
let xf = on_page(m, o);
@@ -242,6 +259,17 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
}
let c = xf.as_coeffs();
let identity = xf == Affine::IDENTITY;
// Every stroke layer's weight is checked with the factor `object.transform` applies.
let factor = if opts.strokes { vectorcraft_doc::Scaling::factor(xf) } else { None };
if let Some(k) = factor
&& paths::is_path(h, item)
&& (!k.is_finite() || {
let width = paths::largest_stroke_weight(h, item)? * k;
!width.is_finite() || width > paths::MAX_STROKE_WIDTH
})
{
return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into()));
}
let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity };
// The transformation and the stroke weight change together or not at all.
atomically(h, |h| {
+14 -2
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.
@@ -1513,8 +1519,10 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
dom::after_command(host, before);
// Style objects follow only a command that is kept.
if crossed.is_ok() {
dom::see_points(host);
// The command stays kept when the look at its changes passes a limit, which ends the run.
let seen = dom::see_points(host);
dom::after_kept_command(host);
seen?;
} else {
session.borrow_mut().script_style_trail = StyleTrail::default();
}
@@ -2432,6 +2440,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 +2997,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 +3032,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();