mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
Merge main into fix/remove-all-trace-group
This commit is contained in:
commit
65b85dbc8f
337 files changed
+21802
-1268
No files matched your search
@@ -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, ¶ms);
|
||||
|
||||
@@ -107,6 +107,9 @@ mod matrix;
|
||||
mod paths;
|
||||
pub mod preferences;
|
||||
mod print;
|
||||
mod raster_capture;
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
@@ -122,6 +125,7 @@ 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)
|
||||
}
|
||||
|
||||
@@ -424,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)
|
||||
}
|
||||
|
||||
@@ -1067,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);
|
||||
@@ -2859,7 +2863,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
// A compound path whose last path this is stays, empty, as it does after `move`.
|
||||
let params = json!({"ids": [item.id.0], "keepEmpty": true});
|
||||
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, |h| clear_releasing(h, &released, ¶ms)));
|
||||
h.dom.editing.set(kept);
|
||||
@@ -3344,7 +3348,9 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) {
|
||||
for (name, members) in
|
||||
ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(raster_capture::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS)
|
||||
{
|
||||
let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name);
|
||||
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
|
||||
@@ -3475,6 +3481,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",
|
||||
@@ -3639,6 +3646,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
|
||||
}
|
||||
|
||||
@@ -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]],
|
||||
|
||||
@@ -309,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
|
||||
@@ -336,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)?;
|
||||
@@ -349,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.
|
||||
@@ -1046,11 +1074,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);
|
||||
}
|
||||
@@ -1058,6 +1091,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)
|
||||
}
|
||||
|
||||
@@ -342,7 +342,12 @@ 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();
|
||||
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()));
|
||||
@@ -361,8 +366,24 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
{
|
||||
selection.remove(item.id);
|
||||
}
|
||||
if kept.as_ref().is_some_and(|before| *before == st.selection) {
|
||||
kept = None;
|
||||
}
|
||||
}
|
||||
edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))
|
||||
// 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(())
|
||||
}
|
||||
@@ -862,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]}))?;
|
||||
@@ -1236,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 { .. })))
|
||||
@@ -1376,38 +1411,67 @@ 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.
|
||||
pub(super) fn see_all_points(h: &super::Host) {
|
||||
let keys: Vec<(u64, u64)> = {
|
||||
/// 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 seen = h.dom.point_nodes.borrow();
|
||||
let mut keys = Vec::new();
|
||||
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)));
|
||||
node_arc(before, group.unwrap_or(item.id)).into_iter().collect()
|
||||
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 => before.layers.iter().collect(),
|
||||
None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at),
|
||||
};
|
||||
while let Some(node) = todo.pop() {
|
||||
if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) {
|
||||
// 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());
|
||||
}
|
||||
looked_at += m.len() as u64;
|
||||
m
|
||||
});
|
||||
now = all.get(&node.id).copied();
|
||||
}
|
||||
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(children);
|
||||
todo.extend(paired(children, now.and_then(|n| n.children()), &mut looked_at));
|
||||
}
|
||||
}
|
||||
if let Some(after) = after {
|
||||
@@ -1417,8 +1481,11 @@ pub(super) fn see_all_points(h: &super::Host) {
|
||||
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 {
|
||||
@@ -1431,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 {
|
||||
@@ -1992,6 +2073,46 @@ mod tests {
|
||||
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() {
|
||||
let made = |v: Value| made_id(&(Data::Undefined, v));
|
||||
|
||||
@@ -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")));
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,9 @@
|
||||
//! commands may use.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `saveAs` without options saves in the format the path's extension names; it writes the file
|
||||
//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
|
||||
//! - `saveAs` without options selects the format from the script's file name before resolving
|
||||
//! symbolic links. A name without a recognized extension uses the document's current format.
|
||||
//! Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
|
||||
//! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds.
|
||||
//! `exportFile` adds the format's extension unless the name already ends
|
||||
//! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes
|
||||
@@ -31,8 +32,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
|
||||
@@ -738,10 +739,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")? {
|
||||
@@ -878,6 +881,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.
|
||||
@@ -1006,7 +1027,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));
|
||||
}
|
||||
|
||||
@@ -1026,8 +1026,16 @@ 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.
|
||||
fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> {
|
||||
/// 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 => {
|
||||
@@ -1096,8 +1104,9 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &
|
||||
}
|
||||
Attr::FillColor | Attr::StrokeColor => {
|
||||
let color = colors::assigned(v, name)?;
|
||||
let paint = color.map_or(Paint::None, Paint::solid);
|
||||
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))
|
||||
}
|
||||
@@ -1138,7 +1147,7 @@ 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);
|
||||
// An empty range changes nothing, also one inside a character that `ba..bb` widens to it.
|
||||
|
||||
@@ -471,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 };
|
||||
|
||||
@@ -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()))));
|
||||
|
||||
@@ -20,9 +20,13 @@
|
||||
//! - `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, an object on a locked artboard and a guide while guides are locked are refused
|
||||
//! with nothing changed, and so are
|
||||
@@ -37,16 +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];
|
||||
@@ -136,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),
|
||||
@@ -148,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),
|
||||
})
|
||||
}
|
||||
@@ -222,12 +234,10 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
|
||||
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, so an object without bounds (an empty path)
|
||||
// takes it too.
|
||||
// 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);
|
||||
@@ -249,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| {
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user