mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 21:12:57 -05:00
Merge main into feat/scripts-scriptui-palettes
This commit is contained in:
commit
d8caffae61
48 files changed
+4981
-212
No files matched your search
@@ -258,7 +258,17 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
// A document whose active artboard the script chose uses that choice, not the one the run
|
||||
// started with.
|
||||
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)))
|
||||
});
|
||||
let active = match &chosen {
|
||||
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 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);
|
||||
|
||||
+106
-57
@@ -18,7 +18,8 @@
|
||||
//!
|
||||
//! Collections are counted from 0, and `pageItems` lists art topmost first, as
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/> reads the frontmost path as
|
||||
//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
|
||||
//! `pathItems[0]`; the `layers` module gives the order of a layer's, a group's and a compound
|
||||
//! path's lists. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
|
||||
//! gives, and a script may name the application's members without `app.`, as
|
||||
//! <https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/> describes; here
|
||||
//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active
|
||||
@@ -99,6 +100,7 @@ use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod clipboard;
|
||||
mod images;
|
||||
pub(super) mod layers;
|
||||
mod matrix;
|
||||
pub mod preferences;
|
||||
mod print;
|
||||
@@ -182,6 +184,14 @@ pub(super) enum Coords {
|
||||
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
|
||||
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many nodes the layer lists of `Layers` objects have looked at on this thread.
|
||||
pub(crate) static LAYER_SCANS: Cell<u64> = const { Cell::new(0) };
|
||||
/// How many lists of art the art collections have built on this thread.
|
||||
pub(crate) static ART_SCANS: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
|
||||
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
|
||||
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
|
||||
@@ -219,6 +229,21 @@ pub(super) struct State {
|
||||
editing: Cell<Option<Item>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
|
||||
/// used first, each kept while its document is unchanged.
|
||||
art: RefCell<Vec<layers::ArtList>>,
|
||||
/// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used
|
||||
/// first, each kept while its document is unchanged.
|
||||
layers: RefCell<Vec<layers::LayerList>>,
|
||||
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
|
||||
pub(super) active_artboards: RefCell<Vec<u64>>,
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
|
||||
pub(super) chosen_artboards: RefCell<Vec<(u64, u64)>>,
|
||||
/// Each open document's uid and the index of its active artboard when the run started.
|
||||
pub(super) boards_at_start: Vec<(u64, usize)>,
|
||||
/// Each document made during the run whose active artboard `setActiveArtboardIndex` chose,
|
||||
/// with the index it chose the first time.
|
||||
pub(super) boards_chosen_in_new: RefCell<Vec<(u64, usize)>>,
|
||||
/// `app.userInteractionLevel` ([`save_open`]).
|
||||
save_options: save_open::State,
|
||||
/// The print option objects ([`print`]).
|
||||
@@ -236,9 +261,9 @@ pub(super) struct State {
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The state of a run whose heap is `heap_bytes`.
|
||||
pub(super) fn new(heap_bytes: usize) -> Self {
|
||||
Self { preset_limit: heap_bytes as u64, ..Self::default() }
|
||||
/// The state of a run that starts with the documents `docs` open and whose heap is `heap_bytes`.
|
||||
pub(super) fn new(docs: &[DocState], heap_bytes: usize) -> Self {
|
||||
Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), preset_limit: heap_bytes as u64, ..Self::default() }
|
||||
}
|
||||
|
||||
/// Whether a call's own savepoint is open: its commands take none of their own.
|
||||
@@ -445,7 +470,7 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo
|
||||
}
|
||||
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document, page item, path point or text range `this` is still there.
|
||||
/// the check that a document, layer, page item, path point or text range `this` is still there.
|
||||
/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and
|
||||
/// `reflect` leaves it out.
|
||||
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
@@ -458,7 +483,10 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
|
||||
"Document" => {
|
||||
doc_of(&h, arg(&a, 0), "Document")?;
|
||||
}
|
||||
"PageItem" | "PathItem" | "TextFrame" | "PlacedItem" | "RasterItem" => {
|
||||
"Layer" => {
|
||||
layers::layer_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
c if c == "PageItem" || ITEM_CLASSES.contains(&c) => {
|
||||
item_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
"PathPoint" => {
|
||||
@@ -926,14 +954,27 @@ fn on_doc<T>(
|
||||
keep_selection: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
atomically(h, |h| on_doc_steps(h, uid, keep_selection, f))
|
||||
on_doc_layer(h, uid, keep_selection, true, f)
|
||||
}
|
||||
|
||||
/// The steps of [`on_doc`].
|
||||
/// [`on_doc`], with `keep_layer` false for `f`s that choose the current layer (`layers.add()`,
|
||||
/// `activeLayer = layer`): the selection is put back, and the layer `f` left current stays current.
|
||||
fn on_doc_layer<T>(
|
||||
h: &Host,
|
||||
uid: u64,
|
||||
keep_selection: bool,
|
||||
keep_layer: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
atomically(h, |h| on_doc_steps(h, uid, keep_selection, keep_layer, f))
|
||||
}
|
||||
|
||||
/// The steps of [`on_doc_layer`].
|
||||
fn on_doc_steps<T>(
|
||||
h: &Host,
|
||||
uid: u64,
|
||||
keep_selection: bool,
|
||||
keep_layer: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
let (index, active, before, layer, activated) = {
|
||||
@@ -947,6 +988,12 @@ fn on_doc_steps<T>(
|
||||
command(h, "document.activate", &json!({"index": index}))?;
|
||||
}
|
||||
let r = f(h);
|
||||
let layer = if keep_layer {
|
||||
layer
|
||||
} else {
|
||||
let s = h.session.borrow();
|
||||
s.active().filter(|st| st.uid == uid).map_or(layer, |st| (st.active_layer, st.highlighted_rows()))
|
||||
};
|
||||
let mut restored = Ok(());
|
||||
if keep_selection {
|
||||
let doc = {
|
||||
@@ -2169,22 +2216,35 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
}
|
||||
|
||||
fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
Ok(text("PageItems"))
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
layers::scoped_typename(h, a)?;
|
||||
return Ok(text("[PageItems]"));
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
Ok(text("[PageItems]"))
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
@@ -2204,6 +2264,9 @@ fn position(n: f64) -> Option<usize> {
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no object has it.
|
||||
fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
@@ -2227,6 +2290,9 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
@@ -2243,6 +2309,9 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
@@ -2260,6 +2329,9 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted,
|
||||
/// and so does an object on a locked artboard.
|
||||
fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = top_items(&st.doc);
|
||||
@@ -2434,8 +2506,14 @@ fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
|
||||
}
|
||||
|
||||
/// The percentage a page item's or a layer's `opacity` reports for `opacity`, rounded to four
|
||||
/// decimals.
|
||||
fn reported_opacity(opacity: f32) -> f64 {
|
||||
(f64::from(opacity) * 100.0 * 1e4).round() / 1e4
|
||||
}
|
||||
|
||||
fn item_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4)))
|
||||
read_item(h, a, |_, n| Ok(num(reported_opacity(n.opacity))))
|
||||
}
|
||||
|
||||
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -2452,7 +2530,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
// Only the exact number the getter reports counts as the same opacity.
|
||||
let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v);
|
||||
let now = d.node(item.id).filter(|n| reported_opacity(n.opacity) == v).map(|n| f64::from(n.opacity) * 100.0);
|
||||
let keeps_other =
|
||||
crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]);
|
||||
(now, keeps_other)
|
||||
@@ -2831,7 +2909,11 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
|
||||
}
|
||||
let (parent, beside) = match how {
|
||||
Placement::Top | Placement::Bottom => {
|
||||
if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) {
|
||||
if matches!(t.kind, NodeKind::Compound { .. }) {
|
||||
if !d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })) {
|
||||
return Err(HostError::Error("a compound path holds only paths".into()));
|
||||
}
|
||||
} else if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) {
|
||||
return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer"))));
|
||||
}
|
||||
(target, None)
|
||||
@@ -3089,19 +3171,6 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn layer_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) };
|
||||
let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) };
|
||||
find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into())))
|
||||
}
|
||||
|
||||
fn layer_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
layer_name(h, a)?;
|
||||
Ok(text("Layer"))
|
||||
}
|
||||
|
||||
/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name.
|
||||
fn named_text(class: &str, name: Answer) -> Answer {
|
||||
match name? {
|
||||
@@ -3118,10 +3187,6 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Document", doc_name(h, a))
|
||||
}
|
||||
|
||||
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Layer", layer_name(h, a))
|
||||
}
|
||||
|
||||
/// `toString()` of an object without a name: `[Class]`.
|
||||
fn class_text(name: &'static str) -> HostMember {
|
||||
HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]")))))
|
||||
@@ -3191,7 +3256,9 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
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) {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
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}"))))));
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
@@ -3312,7 +3379,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(layers::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(print::document_members(l));
|
||||
@@ -3351,7 +3419,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
named(vec![
|
||||
("typename", get(l, items_typename), typed("string")),
|
||||
("length", get(l, items_length), typed("number")),
|
||||
("parent", get(l, items_parent), typed("Document")),
|
||||
("parent", get(l, items_parent), typed("*")),
|
||||
("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])),
|
||||
("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])),
|
||||
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
|
||||
@@ -3455,28 +3523,18 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
),
|
||||
),
|
||||
]);
|
||||
page_item.extend(layers::page_item_members(l));
|
||||
page_item.extend(
|
||||
[
|
||||
"artworkKnockout",
|
||||
"isIsolated",
|
||||
"layer",
|
||||
"pixelAligned",
|
||||
"sliced",
|
||||
"uRL",
|
||||
"uuid",
|
||||
"wrapInside",
|
||||
"wrapOffset",
|
||||
"wrapped",
|
||||
"bringInPerspective",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "PageItem", m)),
|
||||
["artworkKnockout", "isIsolated", "pixelAligned", "sliced", "uRL", "uuid", "wrapInside", "wrapOffset", "wrapped", "bringInPerspective"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "PageItem", m)),
|
||||
);
|
||||
page_item.extend(variables::page_item_members(l));
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
let own = |c: &&&str| **c == "TextFrame" || images::CLASSES.contains(c) || tracing::CLASSES.contains(c);
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| {
|
||||
let mut members = variables::item_members(l, c);
|
||||
let mut members = layers::members(c, l);
|
||||
members.extend(variables::item_members(l, c));
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
}
|
||||
@@ -3486,21 +3544,12 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(layers::classes(l));
|
||||
classes.extend(images::classes(l));
|
||||
tracing::add_trace(&mut classes, l);
|
||||
classes.extend(tracing::classes(l));
|
||||
classes.extend(save_open::classes(l));
|
||||
classes.extend(print::classes(l));
|
||||
classes.push(class(
|
||||
"Layer",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, layer_typename), typed("string")),
|
||||
("name", get(l, layer_name), typed("string")),
|
||||
("toString", method(l, layer_to_string), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
));
|
||||
classes.extend(tags::classes(l));
|
||||
classes
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 {
|
||||
|
||||
@@ -397,21 +397,33 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into()));
|
||||
}
|
||||
doc_of(h, arg(a, 0), "PathItems")
|
||||
}
|
||||
|
||||
/// `typename` of the paths of a document that is still open.
|
||||
fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
Ok(Data::String("PathItems".into()))
|
||||
}
|
||||
|
||||
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
@@ -420,6 +432,9 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no path has it.
|
||||
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
@@ -443,6 +458,9 @@ fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
|
||||
}
|
||||
|
||||
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
@@ -459,6 +477,9 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
@@ -476,6 +497,9 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
@@ -1813,8 +1837,9 @@ 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("Document")),
|
||||
("parent", get(l, items_parent), typed("*")),
|
||||
("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])),
|
||||
("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])),
|
||||
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/> describe.
|
||||
//!
|
||||
//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's
|
||||
@@ -26,6 +27,12 @@
|
||||
//! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art.
|
||||
//! An SVG with `embedRasterImages` false also writes the document's embedded images beside it,
|
||||
//! and when one of those files may not be written, none of them is.
|
||||
//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF
|
||||
//! (`.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.
|
||||
//! - 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
|
||||
@@ -40,8 +47,8 @@
|
||||
//! save of one artboard writes only the file at the path, holding that artboard. Without
|
||||
//! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of
|
||||
//! artboard numbers throws.
|
||||
//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no
|
||||
//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`.
|
||||
//! - `Document.path` is a `Folder` for the folder of the document's file. A file saved or opened
|
||||
//! under a relative path is in the process's working folder. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`.
|
||||
//! `fullName` and `path` of a document whose file the automation read roots do not allow throw
|
||||
//! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`.
|
||||
//! Assigning its current value runs no command.
|
||||
@@ -64,6 +71,7 @@ use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{
|
||||
@@ -86,6 +94,15 @@ pub(in crate::script) struct State {
|
||||
/// The enumerations these members use, as `dom`'s are made.
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]),
|
||||
("AutoCADColors", &["Max8Colors", "Max16Colors", "Max256Colors", "TrueColors"]),
|
||||
(
|
||||
"AutoCADCompatibility",
|
||||
&["AutoCADRelease13", "AutoCADRelease18", "AutoCADRelease14", "AutoCADRelease21", "AutoCADRelease15", "AutoCADRelease24"],
|
||||
),
|
||||
("AutoCADExportFileFormat", &["DXF", "DWG"]),
|
||||
("AutoCADExportOption", &["PreserveAppearance", "MaximizeEditability"]),
|
||||
("AutoCADRasterFormat", &["PNG", "JPEG"]),
|
||||
("AutoCADUnit", &["Points", "Picas", "Inches", "Millimeters", "Centimeters", "Pixels"]),
|
||||
(
|
||||
"Compatibility",
|
||||
&[
|
||||
@@ -182,6 +199,10 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]),
|
||||
];
|
||||
|
||||
/// Other names of enumeration members: `(enumeration, name, member)` makes `enumeration.name` the
|
||||
/// same value as `enumeration.member`.
|
||||
pub(super) const ALIASES: &[(&str, &str, &str)] = &[("ExportType", "AUTOCAD", "AutoCAD")];
|
||||
|
||||
const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS";
|
||||
const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS";
|
||||
|
||||
@@ -196,7 +217,8 @@ enum Default {
|
||||
Member(&'static str, &'static str),
|
||||
/// The help page gives no default: any value throws.
|
||||
Unset,
|
||||
/// White as an `RGBColor`: red, green and blue each 255.
|
||||
/// White as an `RGBColor`: red, green and blue each 255 (its `typename`, when it has one,
|
||||
/// `RGBColor`).
|
||||
White,
|
||||
}
|
||||
|
||||
@@ -209,7 +231,7 @@ impl Default {
|
||||
(Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m),
|
||||
(Default::White, Data::Object(items)) => {
|
||||
let get = |k: &str| items.iter().find(|(name, _)| name == k).map(|(_, v)| v);
|
||||
matches!(get("typename"), Some(Data::String(t)) if t == "RGBColor")
|
||||
get("typename").is_none_or(|t| matches!(t, Data::String(t) if t == "RGBColor"))
|
||||
&& ["red", "green", "blue"].iter().all(|k| matches!(get(k), Some(Data::Number(n)) if *n == 255.0))
|
||||
}
|
||||
_ => false,
|
||||
@@ -656,9 +678,118 @@ fn svg_starts() -> Vec<(&'static str, Data)> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The members of the enumeration `name` in [`ENUMS`].
|
||||
fn members_of(name: &str) -> &'static [&'static str] {
|
||||
ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m)
|
||||
}
|
||||
|
||||
fn autocad_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("ExportOptionsAutoCAD.{name}");
|
||||
let pick = |enumeration: &str| member(d, enumeration, members_of(enumeration), &what);
|
||||
match name {
|
||||
"alterPathsForAppearance" => {
|
||||
p.insert("alterPaths".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"colors" => {
|
||||
let colors = match pick("AutoCADColors")? {
|
||||
"Max8Colors" => json!(8),
|
||||
"Max16Colors" => json!(16),
|
||||
"Max256Colors" => json!(256),
|
||||
_ => json!("true"),
|
||||
};
|
||||
p.insert("colors".into(), colors);
|
||||
}
|
||||
"convertTextToOutlines" => {
|
||||
p.insert("outlineText".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"exportFileFormat" => {
|
||||
if pick("AutoCADExportFileFormat")? == "DWG" {
|
||||
return Err(HostError::Error(
|
||||
"AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
"exportOption" => {
|
||||
let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" };
|
||||
p.insert("preserve".into(), json!(preserve));
|
||||
}
|
||||
"exportSelectedArtOnly" => {
|
||||
p.insert("selectedOnly".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"rasterFormat" => {
|
||||
p.insert("rasterFormat".into(), json!(if pick("AutoCADRasterFormat")? == "JPEG" { "jpeg" } else { "png" }));
|
||||
}
|
||||
"scaleLineweights" => {
|
||||
p.insert("scaleLineweights".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"unit" => {
|
||||
let unit = match pick("AutoCADUnit")? {
|
||||
"Points" => Unit::Points,
|
||||
"Picas" => Unit::Picas,
|
||||
"Inches" => Unit::Inches,
|
||||
"Millimeters" => Unit::Millimeters,
|
||||
"Centimeters" => Unit::Centimeters,
|
||||
_ => Unit::Pixels,
|
||||
};
|
||||
p.insert("unit".into(), json!(unit.key()));
|
||||
}
|
||||
"unitScaleRatio" => {
|
||||
let n = match d {
|
||||
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")));
|
||||
}
|
||||
p.insert("scale".into(), json!(n));
|
||||
}
|
||||
"version" => {
|
||||
let version = match pick("AutoCADCompatibility")? {
|
||||
"AutoCADRelease13" => "R13",
|
||||
"AutoCADRelease14" => "R14",
|
||||
"AutoCADRelease15" => "2000",
|
||||
"AutoCADRelease18" => "2004",
|
||||
"AutoCADRelease21" => "2007",
|
||||
_ => "2010",
|
||||
};
|
||||
p.insert("version".into(), json!(version));
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn autocad_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("alterPathsForAppearance", Data::Bool(false)),
|
||||
("convertTextToOutlines", Data::Bool(false)),
|
||||
("exportFileFormat", text("AutoCADExportFileFormat.DWG")),
|
||||
("exportOption", text("AutoCADExportOption.MaximizeEditability")),
|
||||
("exportSelectedArtOnly", Data::Bool(false)),
|
||||
("scaleLineweights", Data::Bool(false)),
|
||||
("version", text("AutoCADCompatibility.AutoCADRelease24")),
|
||||
]
|
||||
}
|
||||
|
||||
/// The options object `d` with the options of a new `class` object it leaves out, or holds as
|
||||
/// `undefined`, added.
|
||||
fn with_starts(class: &OptionClass, d: &Data) -> Data {
|
||||
let Data::Object(items) = d else { return d.clone() };
|
||||
let mut items = items.clone();
|
||||
for (k, v) in (class.starts)() {
|
||||
match items.iter_mut().find(|(n, _)| n == k) {
|
||||
Some((_, held)) if matches!(held, Data::Undefined) => *held = v,
|
||||
Some(_) => {}
|
||||
None => items.push((k.to_string(), v)),
|
||||
}
|
||||
}
|
||||
Data::Object(items)
|
||||
}
|
||||
|
||||
const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts };
|
||||
const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts };
|
||||
const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts };
|
||||
const AUTOCAD: OptionClass = OptionClass { name: "ExportOptionsAutoCAD", map: autocad_map, kept: &[], starts: autocad_starts };
|
||||
|
||||
/// An `ExportType`: the format `document.export` writes, the extensions a file name may already
|
||||
/// end with (the first is added), and its option class (`None`: no options are taken).
|
||||
@@ -669,9 +800,9 @@ struct ExportKind {
|
||||
}
|
||||
|
||||
fn export_kind(d: &Data) -> std::result::Result<ExportKind, HostError> {
|
||||
let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m);
|
||||
let raster = |format, extensions| ExportKind { format, extensions, options: None };
|
||||
Ok(match member(d, "ExportType", all, "exportType")? {
|
||||
Ok(match member(d, "ExportType", members_of("ExportType"), "exportType")? {
|
||||
"AutoCAD" => ExportKind { format: "dxf", extensions: &["dxf"], options: Some(&AUTOCAD) },
|
||||
"PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) },
|
||||
"JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) },
|
||||
"SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) },
|
||||
@@ -848,11 +979,26 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
None => Map::new(),
|
||||
},
|
||||
Some(o) => match kind.options {
|
||||
// An AutoCAD option left out takes its help page's default, not the DXF writer's.
|
||||
Some(class) if class.name == AUTOCAD.name => options_params(class, &with_starts(class, o))?,
|
||||
Some(class) => options_params(class, o)?,
|
||||
None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())),
|
||||
None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))),
|
||||
},
|
||||
};
|
||||
// A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed
|
||||
// colors, and `AutoCADColors.TrueColors` with it throws.
|
||||
if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) {
|
||||
match p.get("colors") {
|
||||
None => {
|
||||
p.insert("colors".into(), json!(256));
|
||||
}
|
||||
Some(c) if c.as_str() == Some("true") => {
|
||||
return Err(HostError::Error("AutoCADColors.TrueColors needs AutoCADRelease18 or a later version".into()));
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0));
|
||||
@@ -860,7 +1006,8 @@ 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.
|
||||
if kind.format != "svg" {
|
||||
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`.
|
||||
if !matches!(kind.format, "svg" | "dxf") {
|
||||
p.insert("scale".into(), json!(hs / 100.0));
|
||||
}
|
||||
let format = if svgz { "svgz" } else { kind.format };
|
||||
@@ -1140,7 +1287,7 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its
|
||||
/// help page gives for the options mapped here.
|
||||
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]);
|
||||
let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG, &AUTOCAD]);
|
||||
all.map(|c| {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
|
||||
@@ -2484,7 +2484,7 @@ impl Session {
|
||||
engine: engine.clone(),
|
||||
file: request.file.clone(),
|
||||
palette_event: RefCell::new(palette_event),
|
||||
dom: dom::State::new(heap_bytes),
|
||||
dom: dom::State::new(self.documents(), heap_bytes),
|
||||
actions: request.actions,
|
||||
palette_actions: RefCell::new(None),
|
||||
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
|
||||
@@ -2804,6 +2804,10 @@ impl Session {
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
let start: Vec<(u64, usize)> = host.dom.boards_at_start.iter().chain(host.dom.boards_chosen_in_new.borrow().iter()).copied().collect();
|
||||
if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &start, self.documents()) {
|
||||
report["activeArtboards"] = boards;
|
||||
}
|
||||
// The run ran a Copy or Cut, and the clipboard still holds what one put there.
|
||||
if host.copied.get()
|
||||
&& self.clipboard_copied
|
||||
|
||||
Reference in new issue
Block a user