Merge main into feat/scripts-api-layer-path-items

This commit is contained in:
dotCooCoo committed 2026-12-02 18:24:31 -08:00
commit 4010eb5be2
36 files changed
+1998 -197

No files matched your search

+1 -1
View File
@@ -39,7 +39,7 @@ const CLASSES: &[(&str, &[&str])] = &[
("PatternColor", &[]),
];
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
pub(super) fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
let mut items = vec![("typename".to_string(), text(class))];
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
Data::Object(items)
+46 -9
View File
@@ -27,8 +27,10 @@
//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only
//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file.
//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a
//! matrix with no area or one that puts a corner of the image outside the canvas is refused.
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`,
//! and assigning the matrix it reads runs nothing; a matrix with no area, one that puts a
//! corner of the image outside the canvas, or one a nearly singular image cannot reach exactly
//! is refused.
//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system.
use std::cell::RefCell;
@@ -291,7 +293,8 @@ fn doc_raster(h: &Host, a: &[Data]) -> Answer {
// ---- files ----
/// Whether the script may read `path` now by its own read scope and the read roots
/// ([`crate::file_access::ScriptGate`]), without the open documents' files a command may also read.
/// ([`crate::file_access::ScriptGate`]), without the open documents' files, or the files they link
/// to, that a command may also read.
fn may_read(h: &Host, path: &str) -> bool {
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok()
@@ -496,16 +499,50 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
return Err(HostError::Range("the matrix puts the image outside the canvas".into()));
}
let old = im.xf;
// The coordinate frame only changes the signs of the linear part, so any change to it
// counts; the offsets compare in points, which absorbs the rounding of the frame.
let same = old.as_coeffs().iter().zip(target.as_coeffs()).enumerate().all(|(k, (o, t))| if k < 4 { *o == t } else { (o - t).abs() <= 1e-9 });
if same {
// Unchanged means the numbers the `matrix` getter reports, compared exactly, so a small
// change such as `mValueTX` from 0 to 5e-10 still moves the image. A change that the
// conversion to document space rounds away leaves the image's matrix as it is and runs nothing.
// A coefficient the script left as the getter reports keeps the image's own value, so the
// conversion back does not shift an untouched axis.
let olds = old.as_coeffs();
let [a0, b0, c0, d0, e0, f0] = olds;
let reported = match h.dom.coords.get() {
Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0],
Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top],
};
let mut wanted = target.as_coeffs();
for ((w, o), (r, v)) in wanted.iter_mut().zip(olds).zip(reported.iter().zip(m.iter())) {
if r == v {
*w = o;
}
}
if wanted == olds {
return Ok(None);
}
if !area_of(old) {
return Err(HostError::Error("the image has no area to transform".into()));
}
Ok(Some((target * old.inverse()).as_coeffs()))
let target = Affine::new(wanted);
let [ta, tb, tc, td, te, tf] = wanted;
if [ta, tb, tc, td] == [a0, b0, c0, d0] {
// A move alone: the offset difference, without the error an inverse adds.
return Ok(Some([1.0, 0.0, 0.0, 1.0, te - e0, tf - f0]));
}
// A nearly singular image loses precision through the inverse; refuse a change that would
// not land where the script asked rather than move the image somewhere else.
let delta = target * old.inverse();
let landed = delta * old;
if landed.as_coeffs() == olds {
return Ok(None);
}
let close = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].iter().all(|&(x, y)| {
let (p, q) = (landed * Point::new(x, y), target * Point::new(x, y));
(p.x - q.x).abs() <= 1e-6 && (p.y - q.y).abs() <= 1e-6
});
if !close || !area_of(landed) {
return Err(HostError::Range("the matrix cannot be applied exactly to this image".into()));
}
Ok(Some(delta.as_coeffs()))
})?;
if let Some(d) = delta {
edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?;
@@ -653,7 +690,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
]);
let mut placed = named(vec![
("file", property(l, placed_file, placed_set_file), typed("File")),
("relink", method(l, placed_relink), returns("undefined", &[("relinkFile", "File")])),
("relink", method(l, placed_relink), returns("undefined", &[("relinkFrom", "File")])),
("embed", method(l, placed_embed), returns("undefined", &[])),
("matrix", property(l, placed_matrix, placed_set_matrix), typed("Matrix")),
("boundingBox", get(l, placed_box), typed("Array")),
+134 -45
View File
@@ -20,7 +20,7 @@
//! - `locked` true means the layer is locked.
//! - `clipped = true` makes the group's topmost object, which must be a path, a compound path or
//! type, its clipping path, as the Layers panel's clipping mask button does; `false` releases it.
//! - A layer's `color` is an object `{red, green, blue}` with values from 0 to 255.
//! - A layer's `color` is an `RGBColor` object with values from 0 to 255.
//! - `CompoundPathItems.add()` makes an empty compound path. The first path a script moves into it
//! gives it its paint, as Make Compound Path takes the paint of a path it joins.
//! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a
@@ -41,9 +41,9 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_
use super::{
Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard,
arg, boolean, class_text, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref,
later, method, named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, returns, text, typed, typename, whole,
with_doc,
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref, later, method,
named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, reported_opacity, returns, text, typed, typename,
whole, with_doc,
};
use crate::script::{Host, Link};
use crate::{DocState, Document, NodeId, NodeKind};
@@ -233,7 +233,7 @@ fn layer_set_dim(h: &Host, a: &[Data]) -> Answer {
}
fn layer_opacity(h: &Host, a: &[Data]) -> Answer {
read_layer(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4)))
read_layer(h, a, |_, n| Ok(num(reported_opacity(n.opacity))))
}
fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer {
@@ -241,14 +241,13 @@ 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| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v}))
set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v, json!({"opacity": v}))
}
fn layer_color(h: &Host, a: &[Data]) -> Answer {
read_layer(h, a, |_, n| {
let [r, g, b] = layer_flags(n).3.rgb();
let item = |k: &str, v: u8| (k.to_string(), num(f64::from(v)));
Ok(Data::Object(vec![item("red", r), item("green", g), item("blue", b)]))
Ok(super::colors::color_object("RGBColor", &[("red", f64::from(r)), ("green", f64::from(g)), ("blue", f64::from(b))]))
})
}
@@ -280,10 +279,6 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Layer", layer_name(h, a))
}
fn board_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Artboard", board_name(h, a))
}
fn layer_typename(h: &Host, a: &[Data]) -> Answer {
this_layer(h, a)?;
Ok(text("Layer"))
@@ -295,6 +290,8 @@ fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
let at = with_doc(h, doc, |_, st| {
let list = layer_ids(h, st, st.doc.parent_of(id))?;
// The scan is charged by itself: a list kept from an earlier read was charged once.
h.charge_call(list.len() as u64)?;
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
})?;
at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into()))
@@ -305,35 +302,59 @@ fn layer_has_selected(h: &Host, a: &[Data]) -> Answer {
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))))))
}
/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every
/// child visited, including skipped children.
fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec<NodeId>) -> u64 {
let mut count = 0;
for child in n.children().into_iter().flatten() {
count += 1;
if child.is_ruler_guide() || !child.visible || child.locked || child.is_template() {
continue;
}
if child.is_layer() {
count += collect_editable_art(child, out);
} else {
out.push(child.id);
}
}
count
}
/// `hasSelectedArtwork = false` deselects the layer's art with `select.toggle`; `true` adds its
/// visible, unlocked art with `select.add`. The rest of the selection, ruler guides included, stays,
/// and no command runs when there is nothing to deselect or add.
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, total) = with_doc(h, doc, |_, st| {
let (ids, over) = with_doc(h, doc, |_, 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)?;
if !on {
return (selected.iter().copied().filter(inside).collect::<Vec<_>>(), 0);
return Ok::<_, HostError>((selected.iter().copied().filter(inside).collect::<Vec<_>>(), false));
}
let locks = st.doc.locked_artboards();
let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default();
let mut art = Vec::new();
let count = st.doc.node(id).map_or(0, |n| collect_editable_art(n, &mut art));
// 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)?;
let mut have: std::collections::HashSet<NodeId> = selected.iter().copied().collect();
let mut ids = Vec::new();
for o in art {
if selected.len() + ids.len() > MAX_LISTED {
break;
if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
continue;
}
if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
have.insert(o);
ids.push(o);
// Only art that would be added counts toward the limit.
if selected.len() + ids.len() >= MAX_LISTED {
return Ok((ids, true));
}
have.insert(o);
ids.push(o);
}
let total = selected.len() + ids.len();
(ids, total)
});
if total > MAX_LISTED {
Ok((ids, false))
})?;
if over {
return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects")));
}
if ids.is_empty() {
@@ -478,8 +499,7 @@ fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option<NodeId>)> {
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
[_, _, _, _, _] => {
// A collection read before its document was reverted is stale, as its layer is.
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
let (doc, id) = held_layer(h, doc, id)?;
let (doc, id) = layer_of(h, &host_ref("Layer", &handle))?;
Ok((doc, Some(id)))
}
_ => Err(type_error("Layers")),
@@ -492,6 +512,8 @@ fn layer_list(d: &Document, parent: Option<NodeId>) -> Vec<NodeId> {
None => Some(&d.layers),
Some(p) => d.children(Some(p)),
};
#[cfg(test)]
super::LAYER_SCANS.with(|c| c.set(c.get() + list.map_or(0, |l| l.len() as u64)));
list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect()
}
@@ -612,7 +634,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
if parent.is_none() {
return Err(HostError::Error("a document needs at least one layer".into()));
}
let ids = with_doc(h, doc, |_, st| layer_list(&st.doc, parent));
let ids = with_doc(h, doc, |_, st| layer_ids(h, st, parent))?;
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<_>>()})))?;
}
@@ -664,6 +686,8 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> R
return Ok(ids);
}
}
#[cfg(test)]
super::ART_SCANS.with(|c| c.set(c.get() + 1));
let ids: Vec<NodeId> = match container {
None => {
let all = page_items(h, st)?;
@@ -756,7 +780,7 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
/// `pageItems.removeAll()` is stopped.
fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
let all = art_list(h, st, kind, c)?;
let d = &st.doc;
let listed: std::collections::HashSet<NodeId> = all.iter().copied().collect();
@@ -766,7 +790,22 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
let locks = d.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))
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let masks: Vec<u64> = ids
.iter()
.filter(|i| {
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
let kids = p.children().map_or(&[][..], Vec::as_slice);
p.clips()
&& kids.first().is_some_and(|f| f.id == **i)
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
})
})
.map(|i| i.0)
.take(20)
.collect();
Ok::<_, HostError>((ids, refused, on_locked, masks))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -776,8 +815,14 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if !masks.is_empty() {
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!(
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
)));
}
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| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": true})))?;
}
Ok(Data::Undefined)
}
@@ -976,6 +1021,7 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer {
if now == on {
return Ok(Data::Undefined);
}
super::refuse_protected_edit(h, item)?;
if !ok {
return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0)));
}
@@ -988,11 +1034,6 @@ pub(super) fn page_item_members(l: &Link) -> Vec<Described> {
named(vec![("layer", get(l, item_layer), typed("Layer"))])
}
/// A collection member's type for `reflect`.
fn listed(data_type: &str) -> MemberInfo {
MemberInfo { collection: true, ..typed(data_type) }
}
/// The members a page item class adds to `PageItem`'s.
pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
match class {
@@ -1012,6 +1053,11 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
}
}
/// What `reflect` tells of a member whose value is a collection of class `data_type`.
fn listed(data_type: &str) -> MemberInfo {
MemberInfo { collection: true, ..typed(data_type) }
}
// ---- Document ----
fn doc_layers(h: &Host, a: &[Data]) -> Answer {
@@ -1187,6 +1233,10 @@ fn board_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Artboard"))
}
fn board_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Artboard", board_name(h, a))
}
/// `rulerOrigin`: where the rulers measure from with this artboard active, from its top-left corner
/// with Y down.
fn board_ruler_origin(h: &Host, a: &[Data]) -> Answer {
@@ -1273,6 +1323,24 @@ fn boards_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Artboards"))
}
/// `toString()` of a collection: `[Class]`, after the same checks of the collection as `typename`.
fn layers_to_string(h: &Host, a: &[Data]) -> Answer {
layers_scope(h, arg(a, 0))?;
Ok(text("[Layers]"))
}
fn groups_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Group.class())?;
Ok(text("[GroupItems]"))
}
fn compounds_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Compound.class())?;
Ok(text("[CompoundPathItems]"))
}
fn boards_to_string(h: &Host, a: &[Data]) -> Answer {
boards_doc(h, a)?;
Ok(text("[Artboards]"))
}
/// An artboard index argument: a whole number below `len` (`len + 1` with `insert`).
fn board_index_arg(d: &Data, len: usize, what: &str) -> Result<usize> {
let n = number(d, what)?;
@@ -1360,12 +1428,13 @@ fn boards_add(h: &Host, a: &[Data]) -> Answer {
add_board(h, a, None)
}
/// `artboards.insert(artboardRect, index)`: a new artboard at `index`.
/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → nothing.
fn boards_insert(h: &Host, a: &[Data]) -> Answer {
if matches!(arg(a, 2), Data::Undefined) {
return Err(HostError::Type("insert needs an index".into()));
}
add_board(h, a, Some(arg(a, 2)))
add_board(h, a, Some(arg(a, 2)))?;
Ok(Data::Undefined)
}
fn boards_remove(h: &Host, a: &[Data]) -> Answer {
@@ -1382,16 +1451,36 @@ fn boards_active(h: &Host, a: &[Data]) -> Answer {
}
/// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the
/// document changes, and no command runs.
/// document changes, and no command runs. The artboard is kept by its id even when it is already
/// active only as the fallback (no artboard chosen yet), so an artboard inserted before it later
/// in the run moves it to the next index instead of taking its place.
fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
let doc = boards_doc(h, a)?;
let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st)));
let i = board_index_arg(arg(a, 1), len, "index")?;
if i != now {
{
let mut s = h.session.borrow_mut();
let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id);
drop(s);
}
{
let mut chosen = h.dom.chosen_artboards.borrow_mut();
let reverts = with_doc(h, doc, |_, st| st.reverts);
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
*generation = reverts;
} else {
chosen.push((doc.uid, reverts));
}
}
// A document made during the run has no index from the start of the run, so the first choice
// records one; an artboard inserted before it later still puts it in the report.
if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) {
let mut made = h.dom.boards_chosen_in_new.borrow_mut();
if !made.iter().any(|(uid, _)| *uid == doc.uid) {
made.push((doc.uid, i));
}
}
if i != now {
let mut moved = h.dom.active_artboards.borrow_mut();
if !moved.contains(&doc.uid) {
moved.push(doc.uid);
@@ -1466,7 +1555,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("getByName", method(l, layers_by_name), returns("Layer", &[("name", "string")])),
("add", method(l, layers_add), returns("Layer", &[])),
("removeAll", method(l, layers_remove_all), returns("undefined", &[])),
("toString", class_text("Layers"), returns("string", &[])),
("toString", method(l, layers_to_string), returns("string", &[])),
]),
Some(super::function(l, layers_at)),
),
@@ -1482,7 +1571,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("getByName", method(l, groups_by_name), returns("GroupItem", &[("name", "string")])),
("add", method(l, groups_add), returns("GroupItem", &[])),
("removeAll", method(l, groups_remove_all), returns("undefined", &[])),
("toString", class_text("GroupItems"), returns("string", &[])),
("toString", method(l, groups_to_string), returns("string", &[])),
]);
m.push(later(l, "GroupItems", "createFromFile"));
m
@@ -1500,7 +1589,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("getByName", method(l, compounds_by_name), returns("CompoundPathItem", &[("name", "string")])),
("add", method(l, compounds_add), returns("CompoundPathItem", &[])),
("removeAll", method(l, compounds_remove_all), returns("undefined", &[])),
("toString", class_text("CompoundPathItems"), returns("string", &[])),
("toString", method(l, compounds_to_string), returns("string", &[])),
]),
Some(super::function(l, compounds_at)),
),
@@ -1532,11 +1621,11 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("index", method(l, boards_index), returns("Artboard", &[("itemKey", "*")])),
("getByName", method(l, boards_by_name), returns("Artboard", &[("name", "string")])),
("add", method(l, boards_add), returns("Artboard", &[("artboardRect", "Array")])),
("insert", method(l, boards_insert), returns("Artboard", &[("artboardRect", "Array"), ("index", "number")])),
("insert", method(l, boards_insert), returns("undefined", &[("artboardRect", "Array"), ("index", "number")])),
("remove", method(l, boards_remove), returns("undefined", &[("index", "number")])),
("getActiveArtboardIndex", method(l, boards_active), returns("number", &[])),
("setActiveArtboardIndex", method(l, boards_set_active), returns("undefined", &[("index", "number")])),
("toString", class_text("Artboards"), returns("string", &[])),
("toString", method(l, boards_to_string), returns("string", &[])),
]),
Some(super::function(l, boards_at)),
),
+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 {
+1 -1
View File
@@ -1985,6 +1985,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
None,
named(vec![
("typename", get(l, items_typename), typed("string")),
("toString", super::class_text("PathItems"), returns("string", &[])),
("length", get(l, items_length), typed("number")),
("parent", get(l, items_parent), typed("*")),
("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])),
@@ -2004,7 +2005,6 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
method(l, items_star),
returns("PathItem", &with(&center, &[("innerRadius", "number"), ("points", "number"), ("reversed", "boolean")])),
),
("toString", class_text("PathItems"), returns("string", &[])),
]),
Some(super::function(l, items_at)),
),