mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into fix/remove-all-image-frame-clip
This commit is contained in:
commit
b63ed69db5
93 files changed
+7241
-570
No files matched your search
@@ -274,6 +274,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
h.session.borrow_mut().set_replaying(outer);
|
||||
super::dom::forget_removed(h)?;
|
||||
if let Err(e) = r {
|
||||
let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id));
|
||||
return Err(match e {
|
||||
|
||||
@@ -111,6 +111,7 @@ mod print;
|
||||
mod raster_capture;
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT;
|
||||
mod resources;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
@@ -120,19 +121,35 @@ mod variables;
|
||||
|
||||
pub(super) use colors::of_color as color_data;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::index_builds;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS};
|
||||
|
||||
pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources};
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
|
||||
/// Resources a command's steps removed or renamed (a document's uid, the kind and the name), and
|
||||
/// the names the steps compared.
|
||||
type GoneResources = (HashSet<(u64, ResourceKind, String)>, u64);
|
||||
|
||||
/// What [`after_command`] compares with, taken before each command a script runs
|
||||
/// ([`variables::before_command`]).
|
||||
/// ([`variables::before_command`]). The resources earlier commands removed stay noted until the
|
||||
/// run next looks up a resource object or [`forget_removed`] runs.
|
||||
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<crate::doc::DataSet>)> {
|
||||
tracing::before_command(h);
|
||||
variables::before_command(h, id)
|
||||
}
|
||||
|
||||
/// Charges the run for the resource names the last command's steps compared, whether it was kept
|
||||
/// or not, and whether `vc.run` or the object model ran it.
|
||||
pub(super) fn charge_scanned(h: &Host) -> std::result::Result<(), HostError> {
|
||||
let scanned = std::mem::take(&mut h.dom.resources_gone.borrow_mut().1);
|
||||
if scanned > 0 {
|
||||
h.charge_call(scanned)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// After each command a script runs ([`variables::after_command`]).
|
||||
pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataSet>)>) {
|
||||
variables::after_command(h, before);
|
||||
@@ -205,7 +222,8 @@ thread_local! {
|
||||
/// 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
|
||||
/// written yet, how many times each path's points went stale and each path as the run last saw its
|
||||
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
|
||||
/// points, the swatches, symbols, styles and brushes the run's objects name, whether a call's own
|
||||
/// savepoint ([`atomically`]) is open, the settings of each
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, the lists of art and
|
||||
/// layers its layers and groups gave, the active artboard of each document, and the tool
|
||||
@@ -237,6 +255,12 @@ pub(super) struct State {
|
||||
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
|
||||
/// change.
|
||||
editing: Cell<Option<Item>>,
|
||||
/// The resources the steps of kept commands removed or renamed, which the next lookup of a
|
||||
/// resource object or [`forget_removed`] marks stale, and how many names the last command's
|
||||
/// steps compared, which [`charge_scanned`] charges when the command ends.
|
||||
resources_gone: RefCell<GoneResources>,
|
||||
/// The swatches, symbols, styles and brushes the run's objects name ([`resources`]).
|
||||
resources: RefCell<resources::Table>,
|
||||
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.
|
||||
@@ -308,6 +332,9 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return f(h);
|
||||
}
|
||||
flush(h)?;
|
||||
// The removals noted before `f` are applied first, so that a failure drops only the ones its
|
||||
// commands noted.
|
||||
resources::settle_removed(h);
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let styles = text::styles::mark(h);
|
||||
let mark = h.growth_mark();
|
||||
@@ -325,11 +352,20 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
// The resources `f`'s commands removed are back with the documents.
|
||||
h.dom.resources_gone.borrow_mut().0.clear();
|
||||
// Style objects are put back with the documents.
|
||||
text::styles::put_back(h, styles);
|
||||
r
|
||||
}
|
||||
|
||||
/// Makes the run's swatch, symbol, style and brush objects whose resource a command removed or
|
||||
/// renamed stale, so a new resource that takes the name later is not theirs, and checks every
|
||||
/// object against the documents after a `vc.run` command. The check is charged to the run.
|
||||
pub(super) fn forget_removed(h: &Host) -> std::result::Result<(), HostError> {
|
||||
resources::forget_removed(h)
|
||||
}
|
||||
|
||||
/// A document's uid, the document as it was, and the ids of its page items then.
|
||||
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
@@ -1057,11 +1093,31 @@ fn ends_run(e: &HostError) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed, and notes
|
||||
/// the swatches, symbols, styles and brushes it removed or renamed with the ones earlier commands
|
||||
/// removed.
|
||||
pub(super) fn after_kept_command(h: &Host) {
|
||||
let (taken, scanned) = {
|
||||
let mut s = h.session.borrow_mut();
|
||||
let trail = &mut s.script_style_trail;
|
||||
(std::mem::take(&mut trail.resources_gone), std::mem::take(&mut trail.resources_scanned))
|
||||
};
|
||||
{
|
||||
let mut gone = h.dom.resources_gone.borrow_mut();
|
||||
gone.0.extend(taken);
|
||||
gone.1 = gone.1.saturating_add(scanned);
|
||||
}
|
||||
text::styles::after_command(h);
|
||||
}
|
||||
|
||||
/// After a command that is not kept: the resource names its steps compared are charged
|
||||
/// ([`charge_scanned`]), and the resources they removed are not marked stale.
|
||||
pub(super) fn keep_scanned(h: &Host) {
|
||||
let scanned = std::mem::take(&mut h.session.borrow_mut().script_style_trail.resources_scanned);
|
||||
let mut gone = h.dom.resources_gone.borrow_mut();
|
||||
gone.1 = gone.1.saturating_add(scanned);
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the
|
||||
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
|
||||
/// paths stay valid through the change ([`paths::see_all_points`]).
|
||||
@@ -3410,8 +3466,17 @@ 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(raster_capture::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS)
|
||||
// An enumeration the save or rasterize options also define (`SVGFontType`, `AntiAliasingMethod`) is defined once,
|
||||
// with every member.
|
||||
let screens = save_open::screens::ENUMS.iter().filter(|(n, _)| !save_open::ENUMS.iter().chain(raster_capture::ENUMS).any(|(m, _)| m == n));
|
||||
for (name, members) in ENUMS
|
||||
.iter()
|
||||
.chain(save_open::ENUMS)
|
||||
.chain(screens)
|
||||
.chain(print::ENUMS)
|
||||
.chain(raster_capture::ENUMS)
|
||||
.chain(images::ENUMS)
|
||||
.chain(tracing::ENUMS)
|
||||
{
|
||||
let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name);
|
||||
@@ -3422,6 +3487,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
paths::install_enums(realm)?;
|
||||
resources::install_enums(realm)?;
|
||||
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
let l = link;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
@@ -3535,9 +3601,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(resources::document_members(l));
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
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));
|
||||
@@ -3694,13 +3760,16 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|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));
|
||||
match *c {
|
||||
"PathItem" => members.extend(paths::path_item_members(l)),
|
||||
"SymbolItem" => members.extend(resources::symbol_item_members(l)),
|
||||
_ => {}
|
||||
}
|
||||
class(c, Some("PageItem"), members, None)
|
||||
}));
|
||||
classes.extend(paths::classes(l));
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(resources::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(layers::classes(l));
|
||||
|
||||
@@ -10,14 +10,16 @@
|
||||
//! Components are checked when a color is assigned to an object, and a value out of range throws a
|
||||
//! `RangeError` with nothing changed.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0,
|
||||
//! and `new SpotColor()` starts with a `tint` of 100;
|
||||
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
|
||||
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
|
||||
//! says. A color read from an object gives that object the same color when it is assigned back.
|
||||
//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it
|
||||
//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to
|
||||
//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
//! any other paint gives white. A `SpotColor` (<https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/>)
|
||||
//! can be assigned to a path's `fillColor` and `strokeColor`, not to a swatch's `color`.
|
||||
//! `GradientColor` and `PatternColor` can be read from an object but not assigned yet.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
@@ -27,7 +29,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{Link, current, num, text};
|
||||
|
||||
/// The classes whose objects can be read from a fill or stroke but not assigned yet.
|
||||
/// The classes whose objects [`assigned`] refuses as not available yet. A path's `fillColor` and
|
||||
/// `strokeColor` take a `SpotColor` before [`assigned`] runs; a swatch's or spot's `color` does not.
|
||||
const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"];
|
||||
|
||||
/// The components of each color class, with the value `new` gives them.
|
||||
@@ -121,8 +124,20 @@ fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -
|
||||
}
|
||||
}
|
||||
|
||||
/// The `spot` and the `tint` (0 to 100, 0 when left out) of `d` when it is a `SpotColor`, else
|
||||
/// `None`.
|
||||
pub(super) fn spot_parts(d: &Data) -> std::result::Result<Option<(&Data, f64)>, HostError> {
|
||||
let Data::Object(o) = d else { return Ok(None) };
|
||||
if !matches!(o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v), Some(Data::String(s)) if s == "SpotColor") {
|
||||
return Ok(None);
|
||||
}
|
||||
let tint = component(o, "SpotColor", "tint", 0.0, 100.0)?;
|
||||
let spot = o.iter().find(|(k, _)| k == "spot").map_or(&Data::Undefined, |(_, v)| v);
|
||||
Ok(Some((spot, tint)))
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
fn unit(v: f64, scale: f64) -> f32 {
|
||||
pub(super) fn unit(v: f64, scale: f64) -> f32 {
|
||||
(v / scale) as f32
|
||||
}
|
||||
|
||||
|
||||
@@ -634,8 +634,12 @@ fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn layers_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => layers_by_name(h, a),
|
||||
// A number is a position here, never a name ([`layers_at`]).
|
||||
Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())),
|
||||
// A number is a position here, never a name ([`layers_at`]). A stale collection throws its
|
||||
// stale error first.
|
||||
Data::Number(n) if super::position(*n).is_none() => {
|
||||
layers_scope(h, arg(a, 0))?;
|
||||
Err(HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
Data::Number(_) => match layers_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
@@ -1479,8 +1483,12 @@ fn boards_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn boards_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => boards_by_name(h, a),
|
||||
// A number is a position here, never a name ([`boards_at`]).
|
||||
Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())),
|
||||
// A number is a position here, never a name ([`boards_at`]). A stale collection throws its
|
||||
// stale error first.
|
||||
Data::Number(n) if super::position(*n).is_none() => {
|
||||
boards_doc(h, a)?;
|
||||
Err(HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
Data::Number(_) => match boards_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
|
||||
@@ -405,10 +405,12 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
}
|
||||
// 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)
|
||||
let doc = keeping_paths(h, item, || {
|
||||
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)
|
||||
@@ -421,10 +423,67 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The object whose paint the path `n` with id `id` shows: its compound path or compound shape
|
||||
/// when it is a member of one, since the paint commands paint that owner in its place.
|
||||
fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node {
|
||||
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times this thread listed a document's paths ([`path_items`]), for the tests.
|
||||
pub(crate) static PATH_LIST_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Runs `f`, a command that changes the paint, stroke or points of the path `item` and adds,
|
||||
/// removes and reorders no object of its own. When it succeeds, the document made no new object,
|
||||
/// and the path is not inside a Shaper group, the lists of the document's, its layers' and its
|
||||
/// groups' paths ([`path_items`]) stay kept. An edit inside a Shaper group regenerates the group's
|
||||
/// paths, which can drop a path without making a new id.
|
||||
fn keeping_paths<T>(h: &super::Host, item: Item, f: impl FnOnce() -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
let doc_state = |h: &super::Host, run: &mut dyn FnMut(&DocState)| {
|
||||
let s = h.session.borrow();
|
||||
if let Some(st) = s.documents().iter().find(|d| d.uid == item.doc.uid) {
|
||||
run(st);
|
||||
}
|
||||
};
|
||||
let mut kept = None;
|
||||
doc_state(h, &mut |st| {
|
||||
let in_shaper = st.doc.ancestry(item.id).unwrap_or_default().iter().filter_map(|i| st.doc.node(*i)).any(|a| a.extras().shaper.is_some());
|
||||
if !in_shaper {
|
||||
let listed = h.dom.paths.borrow().iter().any(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc));
|
||||
if listed {
|
||||
kept = Some((st.doc.clone(), st.doc.peek_next_id()));
|
||||
}
|
||||
}
|
||||
});
|
||||
let r = f()?;
|
||||
if let Some((before, next)) = kept {
|
||||
doc_state(h, &mut |st| {
|
||||
if st.doc.peek_next_id() == next {
|
||||
for list in h.dom.paths.borrow_mut().iter_mut().filter(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &before)) {
|
||||
list.1 = st.doc.clone();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The object whose paint the path `n` with id `id` shows: the outermost compound shape it is
|
||||
/// inside, at any depth, or else its compound path when it is a member of one. The paint setters
|
||||
/// paint that owner ([`edit_paint`]).
|
||||
pub(super) fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node {
|
||||
let ancestors = d.ancestry(id).unwrap_or_default();
|
||||
let above = ancestors.split_last().map_or(&[][..], |(_, rest)| rest);
|
||||
if let Some(shape) = above.iter().filter_map(|i| d.node(*i)).find(|p| p.is_compound_shape()) {
|
||||
return shape;
|
||||
}
|
||||
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })).unwrap_or(n)
|
||||
}
|
||||
|
||||
/// Runs the paint command `id` with `params` on the object whose paint the path shows
|
||||
/// ([`paint_owner`]).
|
||||
fn edit_paint(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
|
||||
let owner = read_path(h, item, |st, n, _| paint_owner(&st.doc, item.id, n).id)?;
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.insert("ids".into(), json!([owner.0]));
|
||||
}
|
||||
edit_path(h, item, id, params)
|
||||
}
|
||||
|
||||
/// A script's new path goes on the active layer while it is shown and unlocked, or the topmost
|
||||
@@ -462,7 +521,11 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r
|
||||
o.insert("objectOnly".into(), json!(true));
|
||||
}
|
||||
}
|
||||
let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?;
|
||||
let result = if KEEP_PATHS.contains(&id) {
|
||||
keeping_paint(h, || keeping_paths(h, item, || edit_item(h, item, id, ¶ms)))?
|
||||
} else {
|
||||
keeping_paint(h, || edit_item(h, item, id, ¶ms))?
|
||||
};
|
||||
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
|
||||
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
|
||||
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
|
||||
@@ -472,6 +535,10 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The commands [`edit_path`] runs that change only paint, stroke or fill rule, after which the
|
||||
/// document's paths are the ones listed before ([`keeping_paths`]).
|
||||
const KEEP_PATHS: &[&str] = &["paint.setFill", "paint.setStroke", "stroke.set", "object.setOverprint", "path.setFillRule"];
|
||||
|
||||
/// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color
|
||||
/// and gradient and the recent colors as they were before it.
|
||||
fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
@@ -508,6 +575,8 @@ fn path_items(h: &super::Host, st: &DocState, container: Option<NodeId>) -> std:
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
PATH_LIST_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. });
|
||||
let ids: Rc<Vec<NodeId>> = match container {
|
||||
Some(c) => {
|
||||
@@ -1060,9 +1129,15 @@ fn path_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(host_ref("PathPoints", &handle))
|
||||
}
|
||||
|
||||
/// Whether the path of `item` is closed: it has a subpath and every subpath is. Setting `closed` on
|
||||
/// a path with no subpath gives it an empty closed one ([`path_set_closed`]).
|
||||
fn is_closed(h: &super::Host, item: Item) -> std::result::Result<bool, HostError> {
|
||||
read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))
|
||||
}
|
||||
|
||||
fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let item = this_path(h, a)?;
|
||||
read_points(h, item, |subs| Data::Bool(!subs.is_empty() && subs.iter().all(|sp| sp.closed)))
|
||||
Ok(Data::Bool(is_closed(h, item)?))
|
||||
}
|
||||
|
||||
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -1178,7 +1253,7 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
let script: Vec<[f64; 2]> = list.iter().map(|d| point(d, "each point")).collect::<std::result::Result<_, _>>()?;
|
||||
let f = with_doc(h, item.doc, |_, st| frame(st))?;
|
||||
let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?;
|
||||
let closed = is_closed(h, item)?;
|
||||
let c = h.dom.coords.get();
|
||||
let anchors: Vec<Anchor> =
|
||||
script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
|
||||
@@ -1248,7 +1323,7 @@ fn set_paint(h: &super::Host, item: Item, fill: bool, color: Option<Color>) -> s
|
||||
Some(c) => json!({"color": colors::param(&c)}),
|
||||
None => json!({"none": true}),
|
||||
};
|
||||
edit_path(h, item, id, params)?;
|
||||
edit_paint(h, item, id, params)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1311,7 +1386,7 @@ fn set_painted(h: &super::Host, a: &[Data], fill: bool) -> Answer {
|
||||
let now = if fill { !look.fill.is_none() } else { !look.stroke.is_none() };
|
||||
if now != on {
|
||||
let params = if on { new_art_params(h, item, fill)? } else { json!({"none": true}) };
|
||||
edit_path(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?;
|
||||
edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -1325,14 +1400,37 @@ fn path_set_stroked(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn path_fill_color(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(colors::of_paint(&this_look(h, a)?.1.fill))
|
||||
let (item, look) = this_look(h, a)?;
|
||||
super::resources::paint_color(h, item.doc, &look.fill)
|
||||
}
|
||||
|
||||
fn path_stroke_color(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(colors::of_paint(&this_look(h, a)?.1.stroke))
|
||||
let (item, look) = this_look(h, a)?;
|
||||
super::resources::paint_color(h, item.doc, &look.stroke)
|
||||
}
|
||||
|
||||
/// Links the fill (`fill`) or the stroke to the Spot `spot` at `tint` (0 to 100), unless it is
|
||||
/// linked to it at that tint already. A `SpotColor` without a `spot`, as a color linked to a global
|
||||
/// process swatch reads, throws: it does not name the swatch it was read from.
|
||||
fn set_spot_color(h: &super::Host, a: &[Data], fill: bool, spot: &Data, tint: f64) -> Answer {
|
||||
if matches!(spot, Data::Undefined) {
|
||||
return Err(HostError::Error("SpotColor.spot must be a Spot; a color read from a global process swatch cannot be assigned yet".into()));
|
||||
}
|
||||
let (item, look) = this_look(h, a)?;
|
||||
let now = if fill { &look.fill } else { &look.stroke };
|
||||
let at_tint = |t: &f32| *t == colors::unit(tint, 100.0);
|
||||
let name = super::resources::assigned_spot(h, spot, item.doc)?;
|
||||
let same = matches!(now, Paint::Solid { swatch: Some(n), tint: t, .. } if *n == name && at_tint(t));
|
||||
if !same {
|
||||
edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, json!({"swatch": name, "tint": tint}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn set_color(h: &super::Host, a: &[Data], fill: bool) -> Answer {
|
||||
if let Some((spot, tint)) = colors::spot_parts(arg(a, 1))? {
|
||||
return set_spot_color(h, a, fill, spot, tint);
|
||||
}
|
||||
let color = colors::assigned(arg(a, 1), if fill { "fillColor" } else { "strokeColor" })?;
|
||||
let (item, look) = this_look(h, a)?;
|
||||
let now = if fill { &look.fill } else { &look.stroke };
|
||||
@@ -1353,7 +1451,7 @@ fn path_set_stroke_color(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// Runs `stroke.set` with `params` on the path, unless `same`.
|
||||
fn set_stroke_option(h: &super::Host, item: Item, same: bool, params: Value) -> Answer {
|
||||
if !same {
|
||||
edit_path(h, item, "stroke.set", params)?;
|
||||
edit_paint(h, item, "stroke.set", params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -1551,9 +1649,10 @@ pub(super) fn paint_held_by_compound(h: &super::Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| paint_owner(&st.doc, item.id, n).id != item.id))
|
||||
}
|
||||
|
||||
/// Sets the stroke weight of the path `item` to `weight` points.
|
||||
/// Sets the stroke weight of the path `item` to `weight` points, on the object whose paint the
|
||||
/// path shows ([`edit_paint`]).
|
||||
pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std::result::Result<(), HostError> {
|
||||
edit_path(h, item, "stroke.set", json!({"weight": weight})).map(|_| ())
|
||||
edit_paint(h, item, "stroke.set", json!({"weight": weight})).map(|_| ())
|
||||
}
|
||||
|
||||
// ---- PathPoints ----
|
||||
@@ -1831,11 +1930,12 @@ fn points_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Some(p) => p,
|
||||
None => origin?,
|
||||
};
|
||||
let closed = last.is_none() && is_closed(h, item)?;
|
||||
// The kept starts are dropped, so that `counted` is their only copy and grows in place.
|
||||
*h.dom.point_starts.borrow_mut() = None;
|
||||
edit_points(h, item, |subs| match subs.last_mut() {
|
||||
Some(sp) => sp.anchors.push(Anchor::corner(p)),
|
||||
None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)),
|
||||
None => subs.push(SubPath::new(vec![Anchor::corner(p)], closed)),
|
||||
})?;
|
||||
if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) {
|
||||
let grown = Rc::make_mut(&mut counted);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,7 +13,8 @@
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/> describe.
|
||||
//!
|
||||
//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's
|
||||
//! transaction. The file is a `File` object, and the method reads and writes only where that
|
||||
//! transaction and writes command warnings to the run's console.
|
||||
//! The file is a `File` object, and the method reads and writes only where that
|
||||
//! `File` may ([`super::super::files`]): the path is checked before the command runs, and the
|
||||
//! command's own reads and writes leave out the files of the open documents that `vc.run`'s
|
||||
//! commands may use.
|
||||
@@ -26,6 +27,8 @@
|
||||
//! `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
|
||||
//! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art.
|
||||
//! An SVG export writes a compressed file when `compressed` is true, which adds `.svgz`, and
|
||||
//! when the name ends with `.svgz`.
|
||||
//! 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
|
||||
@@ -75,6 +78,8 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
pub(super) mod screens;
|
||||
|
||||
use super::{
|
||||
Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, class, command, current, doc_ref, get, given, method, named,
|
||||
num, on_doc, property, returns, text, this_doc, typed, whole,
|
||||
@@ -642,6 +647,16 @@ fn svg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Res
|
||||
"compressed" => {
|
||||
p.insert("_svgz".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"cssProperties" => {
|
||||
let locations = ["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"];
|
||||
let styling = match member(d, "SVGCSSPropertyLocation", &locations, &what)? {
|
||||
"ENTITIES" => "entities",
|
||||
"PRESENTATIONATTRIBUTES" => "presentation",
|
||||
"STYLEELEMENTS" => "css",
|
||||
_ => "style",
|
||||
};
|
||||
p.insert("styling".into(), json!(styling));
|
||||
}
|
||||
"preserveEditability" => {
|
||||
p.insert("preserveEditing".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
@@ -655,7 +670,6 @@ fn svg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Res
|
||||
|
||||
const SVG_KEPT: &[(&str, Default)] = &[
|
||||
("artboardRange", Default::Text("")),
|
||||
("cssProperties", Default::Member("SVGCSSPropertyLocation", "STYLEATTRIBUTES")),
|
||||
("documentEncoding", Default::Member("SVGDocumentEncoding", "ASCII")),
|
||||
("DTD", Default::Member("SVGDTDVersion", "SVG1_1")),
|
||||
("fontSubsetting", Default::Member("SVGFontSubsetting", "ALLGLYPHS")),
|
||||
@@ -673,6 +687,7 @@ fn svg_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("compressed", Data::Bool(false)),
|
||||
("coordinatePrecision", num(3.0)),
|
||||
("cssProperties", text("SVGCSSPropertyLocation.STYLEATTRIBUTES")),
|
||||
("embedRasterImages", Data::Bool(false)),
|
||||
("includeVariablesAndDatasets", Data::Bool(false)),
|
||||
("preserveEditability", Data::Bool(false)),
|
||||
@@ -1020,7 +1035,9 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
// An SVG export to a name that ends with `.svgz` writes a compressed file, whatever `compressed` holds.
|
||||
let svgz_name = path.rsplit(['/', '\\']).next().is_some_and(|n| n.to_lowercase().ends_with(".svgz"));
|
||||
let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false) || (kind.format == "svg" && svgz_name);
|
||||
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));
|
||||
if (hs - vs).abs() > 1e-9 {
|
||||
@@ -1303,6 +1320,9 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
("saved", property(l, doc_saved, doc_set_saved), typed("boolean")),
|
||||
("close", method(l, doc_close), returns("undefined", &[("saveOptions", "SaveOptions")])),
|
||||
])
|
||||
.into_iter()
|
||||
.chain(screens::document_members(l))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its
|
||||
@@ -1317,5 +1337,6 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
});
|
||||
HostClass { construct: Some(f), ..class(c.name, None, Vec::new(), None) }
|
||||
})
|
||||
.chain(screens::classes(link))
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
//! `Document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, fileNamePrefix?)`
|
||||
//! with `ExportForScreensItemToExport`, the option classes `ExportForScreensOptionsJPEG`,
|
||||
//! `ExportForScreensOptionsPNG24`, `ExportForScreensOptionsPNG8`,
|
||||
//! `ExportForScreensOptionsWebOptimizedSVG` and `ExportForScreensPDFOptions`, and the enumerations
|
||||
//! they use, as the scripting reference pages
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/Document.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsJPEG.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG24.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG8.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsWebOptimizedSVG.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensPDFOptions.html> and
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html> describe.
|
||||
//!
|
||||
//! The method runs `document.exportForScreens` with one format row into the folder, which goes
|
||||
//! through the script's file grants as a `File` opened for writing there would, and the command
|
||||
//! writes only where the script's `File` objects may ([`super::exactly`]).
|
||||
//! With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. SVG raster images are
|
||||
//! embedded; `RasterImageLocation.LINK` returns an error.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the reference pages do not state:
|
||||
//! - `exportFolder` is a `Folder`, or a `File` read as the folder at its path. The files go into
|
||||
//! that folder, without sub-folders, each named `<fileNamePrefix><name><suffix>.<extension>` as
|
||||
//! `document.exportForScreens` names them (`@2x` after a raster file of twice the size), with
|
||||
//! the characters a file name may not hold in the prefix written as `-`. The export keeps its
|
||||
//! settings in the document, as an export from the dialog does.
|
||||
//! - `itemToExport` exports, in this order, the artboards of `artboards` (`all`, the default, or a
|
||||
//! range of artboard numbers such as `1-3, 5`; `""` for none), the assets of `assets` (their ids)
|
||||
//! and, with `document` true, the bounds of the whole document's art (a PDF of every artboard).
|
||||
//! One that names nothing throws. Each of the three is its own export: when a later one throws,
|
||||
//! the files of the earlier ones stay written.
|
||||
//! - `ExportForScreensType.SE_JPEG100`, `SE_JPEG80`, `SE_JPEG50` and `SE_JPEG20` write JPEG at a
|
||||
//! quality of 100, 80, 50 and 20. A scale factor is from 0.01 to 64 and a resolution from 0.72
|
||||
//! to 4608 ppi.
|
||||
//! - `RasterImageLocation.PRESERVE`, the default, embeds raster images as `EMBED` does, and
|
||||
//! `SVGFontType.SVGFONT`, the default, writes text as SVG text elements.
|
||||
//! - Options are read as `Document.exportFile` reads them: a listed option that is not mapped is
|
||||
//! accepted at its default and throws at any other value, and a property the pages do not list
|
||||
//! throws an error that names it, unless it is `undefined`. The options object's class must be
|
||||
//! the one of `exportFormat`, and an omitted options object takes the defaults a new one holds.
|
||||
//! `null` in place of the options, `itemToExport` or `fileNamePrefix` throws a TypeError.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{
|
||||
Answer, Default, Described, Host, Link, MAX_TEXT_BYTES, OptionClass, arg, boolean, builtin_preset_name, current, exactly, fresh, given, member,
|
||||
method, named, num, on_doc, plain, refused, returns, text, this_doc, typename, warned, whole, whole_in, written_as_range,
|
||||
};
|
||||
|
||||
/// The enumerations these members use, as `dom`'s are made.
|
||||
pub(in crate::script::dom) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("ExportForScreensType", &["SE_JPEG100", "SE_JPEG20", "SE_JPEG50", "SE_JPEG80", "SE_PDF", "SE_PNG24", "SE_PNG8", "SE_SVG"]),
|
||||
("ExportForScreensScaleType", &["SCALEBYFACTOR", "SCALEBYHEIGHT", "SCALEBYRESOLUTION", "SCALEBYWIDTH"]),
|
||||
("AntiAliasingMethod", &["ARTOPTIMIZED", "None", "TYPEOPTIMIZED"]),
|
||||
("JPEGCompressionMethodType", &["BASELINEOPTIMIZED", "BASELINESTANDARD", "PROGRESSIVE"]),
|
||||
("RasterImageLocation", &["EMBED", "LINK", "PRESERVE"]),
|
||||
("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]),
|
||||
("SVGFontType", &["OUTLINEFONT", "SVGFONT"]),
|
||||
("SVGIdType", &["SVGIDMINIMAL", "SVGIDREGULAR", "SVGIDUNIQUE"]),
|
||||
];
|
||||
|
||||
/// The members of `enumeration` in [`ENUMS`].
|
||||
fn members(enumeration: &str) -> &'static [&'static str] {
|
||||
ENUMS.iter().find(|(n, _)| *n == enumeration).map_or(&[][..], |(_, m)| *m)
|
||||
}
|
||||
|
||||
/// The member of `enumeration` that `d` names.
|
||||
fn pick<'a>(d: &'a Data, enumeration: &str, what: &str) -> std::result::Result<&'a str, HostError> {
|
||||
member(d, enumeration, members(enumeration), what)
|
||||
}
|
||||
|
||||
/// The least and most pixels per point a raster file of an export has.
|
||||
const SCALE_FACTORS: (f64, f64) = (0.01, 64.0);
|
||||
|
||||
// ---- Raster options ----
|
||||
|
||||
/// The options JPEG, PNG24 and PNG8 share: anti-aliasing and the size, the size kept under `_scale`
|
||||
/// and `_scaleValue` until [`size`] reads them together.
|
||||
fn raster_map(class: &str, name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("{class}.{name}");
|
||||
match name {
|
||||
"antiAliasing" => {
|
||||
let mode = match pick(d, "AntiAliasingMethod", &what)? {
|
||||
"ARTOPTIMIZED" => "art",
|
||||
"TYPEOPTIMIZED" => "type",
|
||||
_ => "none",
|
||||
};
|
||||
p.insert("antiAlias".into(), json!(mode));
|
||||
}
|
||||
"scaleType" => {
|
||||
p.insert("_scale".into(), json!(pick(d, "ExportForScreensScaleType", &what)?));
|
||||
}
|
||||
"scaleTypeValue" => match d {
|
||||
Data::Number(n) if n.is_finite() && *n > 0.0 => {
|
||||
p.insert("_scaleValue".into(), json!(n));
|
||||
}
|
||||
Data::Number(_) => return Err(HostError::Range(format!("{what} must be a number above 0"))),
|
||||
_ => return Err(HostError::Type(format!("{what} must be a number"))),
|
||||
},
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The format row's size from `_scale` and `_scaleValue`: a factor (`scale`), a width or a height
|
||||
/// in pixels (`width`, `height`), or a resolution (`ppi`).
|
||||
fn size(p: &mut Map<String, Value>) -> std::result::Result<(), HostError> {
|
||||
let how = p.remove("_scale").and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "SCALEBYFACTOR".into());
|
||||
let value = p.remove("_scaleValue").and_then(|v| v.as_f64()).unwrap_or(1.0);
|
||||
let (lo, hi) = SCALE_FACTORS;
|
||||
let (key, per_point) = match how.as_str() {
|
||||
"SCALEBYWIDTH" => ("width", None),
|
||||
"SCALEBYHEIGHT" => ("height", None),
|
||||
"SCALEBYRESOLUTION" => ("ppi", Some(value / 72.0)),
|
||||
_ => ("scale", Some(value)),
|
||||
};
|
||||
if per_point.is_some_and(|f| !(lo..=hi).contains(&f)) {
|
||||
let range = if key == "ppi" { "from 0.72 to 4608" } else { "from 0.01 to 64" };
|
||||
return Err(HostError::Range(format!("scaleTypeValue must be {range} with ExportForScreensScaleType.{how}")));
|
||||
}
|
||||
p.insert(key.into(), json!(value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn jpeg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
const CLASS: &str = "ExportForScreensOptionsJPEG";
|
||||
let what = format!("{CLASS}.{name}");
|
||||
match name {
|
||||
"compressionMethod" => {
|
||||
let method = match pick(d, "JPEGCompressionMethodType", &what)? {
|
||||
"BASELINEOPTIMIZED" => "optimized",
|
||||
"PROGRESSIVE" => "progressive",
|
||||
_ => "baseline",
|
||||
};
|
||||
p.insert("method".into(), json!(method));
|
||||
}
|
||||
"embedICCProfile" => {
|
||||
p.insert("embedIcc".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"progressiveScan" => {
|
||||
p.insert("scans".into(), json!(whole_in(d, &what, 3, 5)?));
|
||||
}
|
||||
_ => return raster_map(CLASS, name, d, p),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn jpeg_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")),
|
||||
("compressionMethod", text("JPEGCompressionMethodType.BASELINESTANDARD")),
|
||||
("embedICCProfile", Data::Bool(false)),
|
||||
("progressiveScan", num(3.0)),
|
||||
("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")),
|
||||
("scaleTypeValue", num(1.0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// PNG24's background, kept under `_transparent` and `_black` until [`background`] reads them
|
||||
/// together.
|
||||
fn png24_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
const CLASS: &str = "ExportForScreensOptionsPNG24";
|
||||
let what = format!("{CLASS}.{name}");
|
||||
match name {
|
||||
"transparency" => {
|
||||
p.insert("_transparent".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"backgroundBlack" => {
|
||||
p.insert("_black".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"interlaced" => {
|
||||
p.insert("interlaced".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
_ => return raster_map(CLASS, name, d, p),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The PNG24 row's `background`: transparent with `transparency`, otherwise black with
|
||||
/// `backgroundBlack` and white without it.
|
||||
fn background(p: &mut Map<String, Value>) {
|
||||
let transparent = p.remove("_transparent").and_then(|v| v.as_bool()).unwrap_or(true);
|
||||
let black = p.remove("_black").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let background = if transparent {
|
||||
"transparent"
|
||||
} else if black {
|
||||
"black"
|
||||
} else {
|
||||
"white"
|
||||
};
|
||||
p.insert("background".into(), json!(background));
|
||||
}
|
||||
|
||||
fn png24_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")),
|
||||
("backgroundBlack", Data::Bool(false)),
|
||||
("interlaced", Data::Bool(false)),
|
||||
("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")),
|
||||
("scaleTypeValue", num(1.0)),
|
||||
("transparency", Data::Bool(true)),
|
||||
]
|
||||
}
|
||||
|
||||
fn png8_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
const CLASS: &str = "ExportForScreensOptionsPNG8";
|
||||
let what = format!("{CLASS}.{name}");
|
||||
match name {
|
||||
"colorCount" => {
|
||||
p.insert("colors".into(), json!(whole_in(d, &what, 2, 256)?));
|
||||
}
|
||||
"interlaced" => {
|
||||
p.insert("interlaced".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"transparency" => {
|
||||
p.insert("transparency".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
// Matted on white, the default `matteColor`, or not matted.
|
||||
"matte" => {
|
||||
p.insert("matte".into(), json!(if boolean(d, &what)? { "white" } else { "none" }));
|
||||
}
|
||||
_ => return raster_map(CLASS, name, d, p),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
const PNG8_KEPT: &[(&str, Default)] = &[("matteColor", Default::Unset)];
|
||||
|
||||
fn png8_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")),
|
||||
("colorCount", num(128.0)),
|
||||
("interlaced", Data::Bool(false)),
|
||||
("matte", Data::Bool(true)),
|
||||
("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")),
|
||||
("scaleTypeValue", num(1.0)),
|
||||
("transparency", Data::Bool(true)),
|
||||
]
|
||||
}
|
||||
|
||||
// ---- Vector options ----
|
||||
|
||||
fn svg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("ExportForScreensOptionsWebOptimizedSVG.{name}");
|
||||
let (key, value) = match name {
|
||||
"coordinatePrecision" => ("decimals", json!(whole_in(d, &what, 1, 7)?)),
|
||||
"cssProperties" => {
|
||||
let styling = match pick(d, "SVGCSSPropertyLocation", &what)? {
|
||||
"ENTITIES" => "entities",
|
||||
"PRESENTATIONATTRIBUTES" => "presentation",
|
||||
"STYLEELEMENTS" => "css",
|
||||
_ => "style",
|
||||
};
|
||||
("styling", json!(styling))
|
||||
}
|
||||
"fontType" => ("outlineText", json!(pick(d, "SVGFontType", &what)? == "OUTLINEFONT")),
|
||||
"rasterImageLocation" => {
|
||||
if pick(d, "RasterImageLocation", &what)? == "LINK" {
|
||||
return Err(HostError::Error(format!("{what}: RasterImageLocation.LINK is not available yet")));
|
||||
}
|
||||
("images", json!("embed"))
|
||||
}
|
||||
"svgId" => {
|
||||
let ids = match pick(d, "SVGIdType", &what)? {
|
||||
"SVGIDMINIMAL" => "minimal",
|
||||
"SVGIDUNIQUE" => "unique",
|
||||
_ => "layerNames",
|
||||
};
|
||||
("objectIds", json!(ids))
|
||||
}
|
||||
"svgMinify" => ("minify", json!(boolean(d, &what)?)),
|
||||
"svgResponsive" => ("responsive", json!(boolean(d, &what)?)),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
p.insert(key.into(), value);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn svg_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("coordinatePrecision", num(3.0)),
|
||||
("cssProperties", text("SVGCSSPropertyLocation.STYLEATTRIBUTES")),
|
||||
("fontType", text("SVGFontType.SVGFONT")),
|
||||
("rasterImageLocation", text("RasterImageLocation.PRESERVE")),
|
||||
("svgId", text("SVGIdType.SVGIDREGULAR")),
|
||||
("svgMinify", Data::Bool(false)),
|
||||
("svgResponsive", Data::Bool(true)),
|
||||
]
|
||||
}
|
||||
|
||||
/// The PDF preset's name, at most 255 bytes, as the reference page limits it.
|
||||
fn pdf_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
if name != "pdfPreset" {
|
||||
return Ok(false);
|
||||
}
|
||||
let what = "ExportForScreensPDFOptions.pdfPreset";
|
||||
let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) };
|
||||
if s.len() > 255 {
|
||||
return Err(HostError::Range(format!("{what} is longer than 255 bytes")));
|
||||
}
|
||||
if !s.is_empty() {
|
||||
p.insert("preset".into(), json!(s));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn pdf_starts() -> Vec<(&'static str, Data)> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
// ---- What to export ----
|
||||
|
||||
/// `ExportForScreensItemToExport`'s properties, kept under `_artboards`, `_assets` and `_document`
|
||||
/// until [`exports`] reads them.
|
||||
fn item_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("ExportForScreensItemToExport.{name}");
|
||||
match name {
|
||||
"artboards" => {
|
||||
let r = match d {
|
||||
Data::String(s) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range(format!("{what} is too long"))),
|
||||
Data::String(s) => s.clone(),
|
||||
Data::Number(n) => {
|
||||
whole(*n).filter(|n| *n >= 1).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 1 or a range")))?;
|
||||
vectorcraft_js::number_to_string(*n)
|
||||
}
|
||||
_ => return Err(HostError::Type(format!("{what} must be a string"))),
|
||||
};
|
||||
p.insert("_artboards".into(), json!(r));
|
||||
}
|
||||
"assets" => {
|
||||
let Data::Array(ids) = d else { return Err(HostError::Type(format!("{what} must be an array of asset ids"))) };
|
||||
let ids = ids
|
||||
.iter()
|
||||
.map(|id| match id {
|
||||
Data::Number(n) => whole(*n).ok_or_else(|| HostError::Range(format!("{what} holds {n}, not an asset id"))),
|
||||
_ => Err(HostError::Type(format!("{what} must be an array of asset ids"))),
|
||||
})
|
||||
.collect::<std::result::Result<Vec<u64>, HostError>>()?;
|
||||
p.insert("_assets".into(), json!(ids));
|
||||
}
|
||||
"document" => {
|
||||
p.insert("_document".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn item_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![("artboards", text("all")), ("assets", Data::Array(Vec::new())), ("document", Data::Bool(false))]
|
||||
}
|
||||
|
||||
const JPEG: OptionClass = OptionClass { name: "ExportForScreensOptionsJPEG", map: jpeg_map, kept: &[], starts: jpeg_starts };
|
||||
const PNG24: OptionClass = OptionClass { name: "ExportForScreensOptionsPNG24", map: png24_map, kept: &[], starts: png24_starts };
|
||||
const PNG8: OptionClass = OptionClass { name: "ExportForScreensOptionsPNG8", map: png8_map, kept: PNG8_KEPT, starts: png8_starts };
|
||||
const SVG: OptionClass = OptionClass { name: "ExportForScreensOptionsWebOptimizedSVG", map: svg_map, kept: &[], starts: svg_starts };
|
||||
const PDF: OptionClass = OptionClass { name: "ExportForScreensPDFOptions", map: pdf_map, kept: &[], starts: pdf_starts };
|
||||
const ITEM: OptionClass = OptionClass { name: "ExportForScreensItemToExport", map: item_map, kept: &[], starts: item_starts };
|
||||
|
||||
/// The params of `class` for `d` (a new object's when `d` is omitted), over a new object's, so a
|
||||
/// property a record leaves out keeps its default.
|
||||
fn params(class: &OptionClass, d: Option<&Data>) -> std::result::Result<Map<String, Value>, HostError> {
|
||||
let mut p = super::options_params(class, &fresh(class))?;
|
||||
if let Some(d) = d {
|
||||
p.extend(super::options_params(class, d)?);
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// The format row `exportFormat` (`d`) asks for, with its option class.
|
||||
fn format(d: &Data) -> std::result::Result<(Map<String, Value>, &'static OptionClass), HostError> {
|
||||
let (format, quality, class) = match pick(d, "ExportForScreensType", "exportFormat")? {
|
||||
"SE_JPEG100" => ("jpg", Some(100), &JPEG),
|
||||
"SE_JPEG80" => ("jpg", Some(80), &JPEG),
|
||||
"SE_JPEG50" => ("jpg", Some(50), &JPEG),
|
||||
"SE_JPEG20" => ("jpg", Some(20), &JPEG),
|
||||
"SE_PNG24" => ("png", None, &PNG24),
|
||||
"SE_PNG8" => ("png8", None, &PNG8),
|
||||
"SE_SVG" => ("svg", None, &SVG),
|
||||
_ => ("pdf", None, &PDF),
|
||||
};
|
||||
let mut row = Map::new();
|
||||
row.insert("format".into(), json!(format));
|
||||
if let Some(q) = quality {
|
||||
row.insert("quality".into(), json!(q));
|
||||
}
|
||||
Ok((row, class))
|
||||
}
|
||||
|
||||
/// The exports `itemToExport` asks for, in order: the artboards, the assets and the whole
|
||||
/// document, each as the params that pick it.
|
||||
fn exports(d: Option<&Data>) -> std::result::Result<Vec<Map<String, Value>>, HostError> {
|
||||
if let Some(d) = d
|
||||
&& typename(d) != Some(ITEM.name)
|
||||
{
|
||||
return Err(HostError::Type("itemToExport must be an ExportForScreensItemToExport object".into()));
|
||||
}
|
||||
let mut p = params(&ITEM, d)?;
|
||||
let mut out = Vec::new();
|
||||
if let Some(Value::String(r)) = p.remove("_artboards") {
|
||||
let all = r.trim().eq_ignore_ascii_case("all");
|
||||
if !r.trim().is_empty() {
|
||||
if !all && !written_as_range(&r) {
|
||||
return Err(HostError::Range(format!("ExportForScreensItemToExport.artboards `{r}` is not a range of artboard numbers")));
|
||||
}
|
||||
out.push(Map::from_iter([("range".to_string(), json!(if all { "all" } else { r.as_str() }))]));
|
||||
}
|
||||
}
|
||||
if let Some(ids) = p.remove("_assets").filter(|v| v.as_array().is_some_and(|a| !a.is_empty())) {
|
||||
out.push(Map::from_iter([("assets".to_string(), ids)]));
|
||||
}
|
||||
if p.remove("_document").and_then(|v| v.as_bool()) == Some(true) {
|
||||
out.push(Map::from_iter([("fullDocument".to_string(), json!(true))]));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(HostError::Error(
|
||||
"exportForScreens has nothing to export: itemToExport names no artboards, no assets and not the document".into(),
|
||||
));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The path of the `Folder` (or `File`) argument `d`, or a `TypeError`.
|
||||
fn folder_path(d: &Data) -> std::result::Result<&str, HostError> {
|
||||
let wrong = || HostError::Type("exportForScreens needs a Folder".into());
|
||||
if let Some(p) = vectorcraft_js::file_ref_path(d) {
|
||||
return Ok(p);
|
||||
}
|
||||
let Data::Object(items) = d else { return Err(wrong()) };
|
||||
match items.as_slice() {
|
||||
[(k, Data::String(path))] if k == vectorcraft_js::FOLDER_REF_KEY => Ok(path),
|
||||
_ => Err(wrong()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?,
|
||||
/// fileNamePrefix?)`: `document.exportForScreens` of one format row into the folder, once for each
|
||||
/// of the artboards, the assets and the whole document that `itemToExport` names.
|
||||
fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let folder = folder_path(arg(a, 1))?;
|
||||
let (mut row, class) = format(arg(a, 2))?;
|
||||
let options = given(arg(a, 3));
|
||||
if matches!(options, Some(Data::Null)) {
|
||||
return Err(HostError::Type("the options must be an object".into()));
|
||||
}
|
||||
let mut q = params(class, options)?;
|
||||
if class.name == PNG24.name {
|
||||
background(&mut q);
|
||||
}
|
||||
if class.name == PDF.name {
|
||||
builtin_preset_name(h, &mut q);
|
||||
} else if class.name != SVG.name {
|
||||
size(&mut q)?;
|
||||
}
|
||||
row.extend(q);
|
||||
let exports = exports(given(arg(a, 4)))?;
|
||||
let prefix = match given(arg(a, 5)) {
|
||||
None => None,
|
||||
Some(Data::String(s)) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range("fileNamePrefix is too long".into())),
|
||||
Some(Data::String(s)) => Some(s.clone()),
|
||||
Some(_) => return Err(HostError::Type("fileNamePrefix must be a string".into())),
|
||||
};
|
||||
let real = h.disk.borrow().folder_target(folder).map_err(|m| refused(m, folder))?;
|
||||
let mut base = Map::new();
|
||||
base.insert("folder".into(), json!(plain(real)?));
|
||||
base.insert("folders".into(), json!("none"));
|
||||
base.insert("formats".into(), json!([Value::Object(row)]));
|
||||
if let Some(prefix) = prefix {
|
||||
base.insert("prefix".into(), json!(prefix));
|
||||
}
|
||||
// The artboards, the assets and the document are exported one after another into the folder:
|
||||
// a later export numbers a file whose name an earlier one took instead of writing over it.
|
||||
crate::cmd::fileio::sharing_screen_names(|| {
|
||||
for items in exports {
|
||||
let mut p = base.clone();
|
||||
p.extend(items);
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportForScreens", "document.exportForScreens", &Value::Object(p))))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
}
|
||||
|
||||
/// The members these add to `Document`.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![(
|
||||
"exportForScreens",
|
||||
method(l, doc_export_for_screens),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("exportFolder", "Folder"),
|
||||
("targetType", "ExportForScreensType"),
|
||||
("options", "*"),
|
||||
("itemToExport", "ExportForScreensItemToExport"),
|
||||
("fileNamePrefix", "string"),
|
||||
],
|
||||
),
|
||||
)])
|
||||
}
|
||||
|
||||
/// The classes: each `new Name()` gives a record with its `typename` and the defaults its reference
|
||||
/// page gives.
|
||||
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
[&ITEM, &JPEG, &PNG24, &PNG8, &SVG, &PDF]
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
current(&l)?.charge_call(64)?;
|
||||
Ok(fresh(c))
|
||||
});
|
||||
HostClass { name: c.name.into(), parent: None, members: Vec::new(), info: Vec::new(), index: None, construct: Some(f) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -880,7 +880,11 @@ fn options_load(h: &Host, a: &[Data]) -> Answer {
|
||||
let wanted = vectorcraft_trace::preset(name).or_else(|| h.session.borrow().trace_preset(name).map(|q| q.params.clone()));
|
||||
let wanted = wanted.ok_or_else(|| HostError::Error("TracingOptions.loadFromPreset: no built-in or saved preset has that name".into()))?;
|
||||
let same = serde_json::to_value(&wanted).ok().as_ref().and_then(Value::as_object) == Some(¶ms);
|
||||
if !(same && preset.eq_ignore_ascii_case(name)) {
|
||||
// A built-in preset answers to its name with or without brackets (`[Default]`).
|
||||
let key = |n: &str| {
|
||||
if vectorcraft_trace::preset(n).is_some() { n.trim().trim_start_matches('[').trim_end_matches(']').to_string() } else { n.to_string() }
|
||||
};
|
||||
if !(same && key(&preset).eq_ignore_ascii_case(&key(name))) {
|
||||
let mut p = Map::new();
|
||||
p.insert("preset".into(), json!(name));
|
||||
retrace(h, item, p)?;
|
||||
|
||||
@@ -127,6 +127,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written";
|
||||
pub(crate) const READ_ONLY: &str = "Script file is read-only";
|
||||
pub(crate) const OPEN_FOR_WRITING: &str = "Script file is open for writing";
|
||||
pub(crate) const NOT_EMPTY: &str = "Script folder is not empty";
|
||||
pub(crate) const NOT_FOLDER: &str = "Script folder is a file";
|
||||
pub(crate) const NAME_TAKEN: &str = "Script file name is already in use";
|
||||
pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder";
|
||||
#[cfg(not(unix))]
|
||||
@@ -720,6 +721,24 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
/// The real path of the folder `path` that an export writes its files into, as a `File`
|
||||
/// opened for writing there would reach it ([`Disk::target`]), or why it may not: a file is
|
||||
/// not a folder. A root (`/`, `E:\`) has no name of its own: its real path must be inside a
|
||||
/// folder the script may write to and the automation write roots in force.
|
||||
pub(crate) fn folder_target(&self, path: &str) -> Result<std::path::PathBuf, &'static str> {
|
||||
let p = self.checked(path)?;
|
||||
if p.file_name().is_none() {
|
||||
let real = std::fs::canonicalize(p).map_err(|_| ACCESS_DENIED)?;
|
||||
let writable = crate::file_access::check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_ok();
|
||||
return if self.writes.allows(&real) && writable { Ok(real) } else { Err(ACCESS_DENIED) };
|
||||
}
|
||||
let real = self.target(path, true)?;
|
||||
match std::fs::metadata(&real) {
|
||||
Ok(m) if !m.is_dir() => Err(NOT_FOLDER),
|
||||
_ => Ok(real),
|
||||
}
|
||||
}
|
||||
|
||||
/// The real path of the file `path` that opening it as a document reads, as a `File` reads it
|
||||
/// ([`ScriptScope::locate`]), or why it may not: it is not there, it is not a regular file, or
|
||||
/// the script may not read it.
|
||||
|
||||
@@ -1406,7 +1406,7 @@ fn note_ids(s: &mut Session) {
|
||||
/// it, for a result that cannot cross to the script.
|
||||
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<Savepoint>)> {
|
||||
raise_ids(s);
|
||||
s.script_style_trail = StyleTrail::start(s);
|
||||
s.script_style_trail = StyleTrail::start(s, dom::holds_resources(host));
|
||||
let mutating = waits_for_tool_edit(id);
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. A
|
||||
// query that fills the clipboard (`clipboard.importSvg`) takes one too, for the clipboard.
|
||||
@@ -1439,6 +1439,8 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
match r {
|
||||
Ok(v) => {
|
||||
note_ids(s);
|
||||
// A command that is not a batch, such as `edit.undo`, notes the resources it removed too.
|
||||
note_resources(s);
|
||||
let (mut objects, mut bytes) = (0, 0);
|
||||
for st in &s.docs {
|
||||
match before.iter().find(|(uid, ..)| *uid == st.uid) {
|
||||
@@ -1458,7 +1460,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
Ok((v, objects, bytes, save))
|
||||
}
|
||||
Err(e) => {
|
||||
s.script_style_trail = StyleTrail::default();
|
||||
s.script_style_trail = StyleTrail { resources_scanned: s.script_style_trail.resources_scanned, ..Default::default() };
|
||||
if let Some(save) = save
|
||||
&& !save.restore(s)
|
||||
{
|
||||
@@ -1483,7 +1485,9 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
|
||||
let bytes = args.iter().map(data_size).sum();
|
||||
host.charge_call(bytes)?;
|
||||
bump(&host.counts.vc_run);
|
||||
command(host, &id, ¶ms)
|
||||
let r = command(host, &id, ¶ms);
|
||||
dom::forget_removed(host)?;
|
||||
r
|
||||
}
|
||||
|
||||
/// Runs command `id` for the script as `vc.run` does, its call already charged: it joins the run's
|
||||
@@ -1515,6 +1519,12 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
|
||||
let mut s = session.borrow_mut();
|
||||
(s.copies, step(&mut s, host, id, params))
|
||||
};
|
||||
// The resource names a failed command's steps compared are still charged, before its error is
|
||||
// given.
|
||||
if r.is_err() {
|
||||
dom::keep_scanned(host);
|
||||
dom::charge_scanned(host)?;
|
||||
}
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(id)) {
|
||||
let nanos = started.elapsed().as_nanos();
|
||||
@@ -1565,8 +1575,11 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
|
||||
dom::after_kept_command(host);
|
||||
seen?;
|
||||
} else {
|
||||
dom::keep_scanned(host);
|
||||
session.borrow_mut().script_style_trail = StyleTrail::default();
|
||||
}
|
||||
// The resource names the command's steps compared are charged whoever ran it.
|
||||
dom::charge_scanned(host)?;
|
||||
crossed.map(|data| (data, value))
|
||||
}
|
||||
|
||||
@@ -1577,19 +1590,28 @@ pub(crate) type StyleLists =
|
||||
/// What the steps of a command a script runs did to the documents' style lists
|
||||
/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step
|
||||
/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the
|
||||
/// documents a step reverted.
|
||||
#[derive(Default)]
|
||||
/// documents a step reverted. It also holds each open document as the last step left it, and the
|
||||
/// swatches, symbols, graphic styles and brushes a step removed or renamed.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct StyleTrail {
|
||||
lists: Vec<StyleLists>,
|
||||
pub(crate) gone: std::collections::HashSet<(u64, bool, String)>,
|
||||
pub(crate) reverted: Vec<u64>,
|
||||
/// Whether the run holds resource objects, so that the steps note what they remove.
|
||||
watch_resources: bool,
|
||||
docs: Vec<(u64, Arc<crate::Document>)>,
|
||||
pub(in crate::script) resources_gone: std::collections::HashSet<(u64, dom::ResourceKind, String)>,
|
||||
/// The resource names the steps compared, charged to the run with the check that follows.
|
||||
pub(crate) resources_scanned: u64,
|
||||
}
|
||||
|
||||
impl StyleTrail {
|
||||
/// A trail that starts from the documents' style lists now.
|
||||
fn start(s: &Session) -> Self {
|
||||
/// A trail that starts from the documents' style lists now, and from the documents themselves
|
||||
/// when `watch_resources`.
|
||||
fn start(s: &Session, watch_resources: bool) -> Self {
|
||||
let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect();
|
||||
StyleTrail { lists, ..Default::default() }
|
||||
let docs = if watch_resources { s.docs.iter().map(|st| (st.uid, st.doc.clone())).collect() } else { Vec::new() };
|
||||
StyleTrail { lists, docs, watch_resources, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1623,6 +1645,32 @@ pub(crate) fn note_style_lists(s: &mut Session) {
|
||||
}
|
||||
*last = (st.uid, st.reverts, c.clone(), p.clone());
|
||||
}
|
||||
note_resources(s);
|
||||
}
|
||||
|
||||
/// After a step of a batch a script runs, and after each command it runs: notes the swatches,
|
||||
/// symbols, styles and brushes the documents no longer have, when the run holds objects for them
|
||||
/// ([`dom::after_kept_command`]). A document the trail already compared is not compared again.
|
||||
fn note_resources(s: &mut Session) {
|
||||
let trail = &mut s.script_style_trail;
|
||||
if !trail.watch_resources {
|
||||
return;
|
||||
}
|
||||
trail.docs.retain(|(uid, _)| s.docs.iter().any(|d| d.uid == *uid));
|
||||
for st in &s.docs {
|
||||
let Some(last) = trail.docs.iter_mut().find(|(uid, _)| *uid == st.uid) else {
|
||||
trail.docs.push((st.uid, st.doc.clone()));
|
||||
continue;
|
||||
};
|
||||
if !Arc::ptr_eq(&last.1, &st.doc) {
|
||||
let (gone, scanned) = dom::resources_gone(&last.1, &st.doc);
|
||||
trail.resources_scanned = trail.resources_scanned.saturating_add(scanned);
|
||||
for (kind, name) in gone {
|
||||
trail.resources_gone.insert((st.uid, kind, name));
|
||||
}
|
||||
last.1 = st.doc.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]).
|
||||
@@ -3197,6 +3245,8 @@ thread_local! {
|
||||
pub(crate) static TEST_GROWTH_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
|
||||
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the swatch, symbol, style and brush objects a run may hold, in place of 100,000.
|
||||
pub(crate) static TEST_MAX_SLOTS: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: how many times the object model worked out where the points of each subpath of a
|
||||
/// path start.
|
||||
pub(crate) static LAYOUTS_BUILT: Cell<u64> = const { Cell::new(0) };
|
||||
|
||||
Reference in new issue
Block a user