Merge main into fix/flatpak-portal-save-names

This commit is contained in:
dotCooCoo
2026-12-04 18:51:15 -08:00
100 changed files with 9147 additions and 447 deletions
+91 -17
View File
@@ -28,12 +28,19 @@ pub fn resolve_stored_radii(base: &PathData, stored: &[f64], relative: bool) ->
out
}
fn dormant_radius_scale(base: &PathData) -> f64 {
base.length().max(1e-12)
}
/// Turn stored absolute radii into fractions of each corner's maximum, or the other way.
/// Anchors without a cuttable corner use the outline's length (at least 1e-12 document units).
/// Their fractions are not capped at 1.
/// When an anchor edit straightens or bends a corner, [`edit_corner_anchors`] converts its
/// radius between these reference lengths, preserving its document length at that edit.
pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) {
if live.radii_relative() == relative {
return;
}
let was_relative = live.radii_relative();
let base = match live {
LiveShape::Rectangle { w, h, .. } => shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)),
LiveShape::Polygon { .. } | LiveShape::Star { .. } => live.polygon_outline(),
@@ -41,22 +48,22 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) {
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return,
};
let corners = path_corners(&base);
let dormant_scale = dormant_radius_scale(&base);
let radii: &mut [f64] = match live {
LiveShape::Rectangle { radii, .. } => radii,
LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } => radii,
LiveShape::Path { radii, .. } => radii,
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return,
};
for c in corners {
if let Some(r) = radii.get(c.index) {
let max = c.max_radius();
radii[c.index] = if relative {
if max > 1e-12 && !was_relative { (*r / max).clamp(0.0, 1.0) } else { *r }
} else if was_relative {
(*r).clamp(0.0, 1.0) * max
} else {
*r
};
for (index, r) in radii.iter_mut().enumerate() {
let corner = corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &corners[i]);
let max = corner.map_or(dormant_scale, Corner::max_radius);
if relative {
if max > 0.0 {
*r = if corner.is_some() { (*r / max).clamp(0.0, 1.0) } else { (*r / max).max(0.0) };
}
} else {
*r = if corner.is_some() { (*r).clamp(0.0, 1.0) } else { (*r).max(0.0) } * max;
}
}
match live {
@@ -143,7 +150,8 @@ impl<'a> LiveCorners<'a> {
}
/// The radius corner `index` is stored at: document lengths, or a fraction in 0..1 when
/// [`LiveCorners::radii_relative`].
/// [`LiveCorners::radii_relative`]. Dormant anchors use the reference length documented in
/// [`convert_radii_relative`], and their fractions can exceed 1.
pub fn radius(&self, index: usize) -> f64 {
self.radii.get(index).copied().unwrap_or(0.0)
}
@@ -206,8 +214,8 @@ impl<'a> LiveCorners<'a> {
/// Set `radius` (document units; negative: 0) and/or `kind` on the `corners` (anchor indices of
/// the uncut outline, see [`LiveCorners`]) of a path and its live shape, then cut the path again.
/// A path that isn't a live shape keeps its uncut outline as a [`LiveShape::Path`], which is a
/// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they
/// are.
/// plain path again once no radius or nondefault corner kind is stored. A straight anchor keeps
/// its stored radius. Ellipses and lines have no corners: they stay as they are.
pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corners: &BTreeSet<usize>, radius: Option<f64>, kind: Option<CornerKind>) {
fn edit(
base: &PathData,
@@ -286,13 +294,31 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corne
}
}
/// Convert relative `radii` (fractions, one per anchor of the outline) after the outline changed
/// from `before` to `after`: a corner that straightened keeps its document length as a fraction of
/// `after`'s length, and a corner that bent again takes that length back as a fraction of its new
/// maximum. Other radii are left as they are.
pub fn rebase_relative_radii(before: &PathData, after: &PathData, radii: &mut [f64]) {
let (old_corners, new_corners) = (path_corners(before), path_corners(after));
let (old_dormant_scale, new_dormant_scale) = (dormant_radius_scale(before), dormant_radius_scale(after));
for (index, r) in radii.iter_mut().enumerate() {
let old = old_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &old_corners[i]);
let new = new_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &new_corners[i]);
match (old, new) {
(Some(c), None) => *r = (*r).clamp(0.0, 1.0) * c.max_radius() / new_dormant_scale,
(None, Some(c)) => *r = (*r * old_dormant_scale / c.max_radius()).clamp(0.0, 1.0),
_ => {}
}
}
}
/// Edit the anchors of the uncut outline that `anchors` (of the path as drawn) come from, while the
/// path keeps its Live Corners: `edit` gets the outline in document space and those of its anchors,
/// and the path is cut again with the same radii and kinds. A live rectangle or polygon becomes a
/// [`LiveShape::Path`] with that outline. [`LiveCorners::sources`] before and after the edit map
/// the anchors as drawn to the corners they come from.
/// Returns `None`, leaving the path unchanged, when the path has no live shape or
/// no cut corner, or is a rectangle sheared or scaled unevenly.
/// no corner with a radius, or is a rectangle sheared or scaled unevenly.
pub fn edit_corner_anchors(
path: &mut PathData,
live: &mut Option<Box<LiveShape>>,
@@ -307,9 +333,11 @@ pub fn edit_corner_anchors(
return None;
}
}
let (mut base, moved, radii, kinds, relative) = {
let (mut base, moved, mut radii, kinds, relative) = {
let lc = LiveCorners::new(path, live.as_deref())?;
if !lc.drawn.iter().any(|r| *r > 0.0) {
// The stored radii decide, not the drawn ones: a corner the edit straightened draws no
// arc but keeps its radius, and rounds again when a later edit bends it.
if !lc.radii.iter().any(|r| *r > 0.0) {
return None;
}
let moved: BTreeSet<usize> = anchors.iter().filter_map(|(si, ai)| lc.sources.get(*si)?.get(*ai).copied()).collect();
@@ -330,7 +358,11 @@ pub fn edit_corner_anchors(
k += 1;
}
}
let before = relative.then(|| base.clone());
edit(&mut base, &on_base);
if let Some(before) = before {
rebase_relative_radii(&before, &base, &mut radii);
}
let l = LiveShape::Path { base, radii, kinds, radii_relative: relative };
*path = l.to_path();
*live = Some(Box::new(l));
@@ -423,6 +455,48 @@ mod tests {
assert!(!p.transform(Affine::translate((5.0, 0.0))), "a move needs no new cuts");
}
/// Moving the anchor of the only rounded corner into a straight line and back keeps its
/// stored radius, so the corner is rounded again.
#[test]
fn a_straightened_corner_rounds_again_when_it_bends_back() {
let pen = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false));
let (mut path, mut live) = (pen.clone(), None);
set_corners(&mut path, &mut live, &set(&[1]), Some(10.0), None);
let corner = LiveCorners::new(&path, live.as_deref()).unwrap().anchors_of(&set(&[1]));
let move_corner = |path: &mut PathData, live: &mut Option<Box<LiveShape>>, to: Point| {
let sel = LiveCorners::new(path, live.as_deref()).unwrap().anchors_of(&set(&[1]));
let sel = if sel.is_empty() { anchors(&[1]) } else { sel };
edit_corner_anchors(path, live, &sel, |base, on_base| {
for &(si, ai) in on_base {
if let Some(a) = base.anchor_mut(si, ai) {
(a.p, a.h_in, a.h_out) = (to, to, to);
}
}
})
};
assert_eq!(corner.len(), 2, "the corner is cut");
// Straight: the corner has nothing to cut.
assert!(move_corner(&mut path, &mut live, Point::new(50.0, 40.0)).is_some());
assert!(matches!(live.as_deref(), Some(LiveShape::Path { radii, .. }) if radii.get(1) == Some(&10.0)));
assert_eq!(LiveCorners::new(&path, live.as_deref()).unwrap().drawn_radius(1), 0.0, "the straight corner draws no arc");
// Bent again: the stored radius cuts it again.
assert!(move_corner(&mut path, &mut live, Point::new(100.0, 0.0)).is_some(), "the straightened corner stays live");
let c = LiveCorners::new(&path, live.as_deref()).unwrap();
assert!((c.drawn_radius(1) - 10.0).abs() < 1e-6, "the corner keeps its radius: {live:?}");
for relative in [true, false] {
assert!(move_corner(&mut path, &mut live, Point::new(50.0, 40.0)).is_some());
assert_eq!(LiveCorners::new(&path, live.as_deref()).unwrap().drawn_radius(1), 0.0);
let l = live.as_deref_mut().unwrap();
convert_radii_relative(l, relative);
assert_eq!(l.radii_relative(), relative);
path = l.to_path();
assert!(move_corner(&mut path, &mut live, Point::new(100.0, 0.0)).is_some());
let c = LiveCorners::new(&path, live.as_deref()).unwrap();
assert!((c.drawn_radius(1) - 10.0).abs() < 1e-6, "the corner keeps its radius after changing modes: {live:?}");
}
}
#[test]
fn relative_radii_scale_with_rectangle_size() {
let l = LiveShape::Rectangle {
+1 -1
View File
@@ -103,7 +103,7 @@ pub use appearance::{
};
pub use assets::ExportAsset;
pub use compound_shape::ShapeMode;
pub use corners::{LiveCorners, edit_corner_anchors};
pub use corners::{LiveCorners, edit_corner_anchors, rebase_relative_radii};
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
pub use graph::{
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
@@ -117,13 +117,17 @@ fn traces(path: &PathData, corners: &[Point; 4]) -> bool {
if (0..n).any(|i| !straight(&sp.anchors[i], &sp.anchors[(i + 1) % n])) {
return false;
}
// A last anchor on the first one only closes the path: the check above has kept its handles on that
// point, so the corners are read without it.
let m = if sp.anchors[n - 1].p == sp.anchors[0].p { n - 1 } else { n };
let points: Vec<Point> = sp
.anchors
.iter()
.take(m)
.enumerate()
.filter_map(|(i, a)| {
let prev = sp.anchors[(i + sp.anchors.len() - 1) % sp.anchors.len()].p;
let next = sp.anchors[(i + 1) % sp.anchors.len()].p;
let prev = sp.anchors[(i + m - 1) % m].p;
let next = sp.anchors[(i + 1) % m].p;
let interior = (prev.x == a.p.x && a.p.x == next.x && a.p.y > prev.y.min(next.y) && a.p.y < prev.y.max(next.y))
|| (prev.y == a.p.y && a.p.y == next.y && a.p.x > prev.x.min(next.x) && a.p.x < prev.x.max(next.x));
(!interior).then_some(a.p)
@@ -198,6 +198,30 @@ fn collinear_midpoints_do_not_add_another_guide_or_history_step() {
}
}
#[test]
fn a_closing_anchor_on_the_first_one_does_not_add_another_guide_or_history_step() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
for reverse in [false, true] {
let mut points = corners.to_vec();
if reverse {
points.reverse();
}
points.push(points[0]);
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(SubPath::polyline(&points, true));
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "reverse: {reverse}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
}
#[test]
fn handles_along_a_side_still_match_and_handles_off_it_do_not() {
let mut s = session();
+5 -3
View File
@@ -1,9 +1,10 @@
//! Artwork Cleanup (`addon.cleanup.*`), a built-in add-on: Simplify Anchors (Keep Shape), the
//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup and Rejoin Path
//! Pieces, and its text tools ([`text`]). Its panel and its submenu, Object › Plug-ins › Artwork
//! Cleanup, are the UI's.
//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup, Release All
//! Containers ([`release`]) and Rejoin Path Pieces, and its text tools ([`text`]). Its panel and
//! its submenu, Object › Plug-ins › Artwork Cleanup, are the UI's.
mod checks;
mod release;
#[cfg(test)]
mod tests;
mod text;
@@ -87,6 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
rejoin
),
];
v.extend(release::specs());
v.extend(text::specs());
v
}
@@ -0,0 +1,422 @@
//! Artwork Cleanup's Release All Containers (`addon.cleanup.releaseAll`): every group, clipping
//! mask and compound path in the selection, the objects named or the whole document, taken apart
//! at every level of nesting as one undo step, so that only the objects they held are left.
#[cfg(test)]
mod tests;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, LiveShape, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_tools::builder::is_live_paint;
use super::checks::{MAX_OBJECTS, Scope};
use super::{named, retain_targets, scope_of};
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
use crate::{EngineError, Result, Session};
/// The command.
const COMMAND: &str = "addon.cleanup.releaseAll";
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.cleanup.releaseAll",
"Release All Containers…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), ids?: [id…] (the objects, groups and layers to release in, instead of `scope`; duplicate ids are an error), groups?: bool (true: groups are ungrouped), clipGroups?: bool (true: clipping groups are ungrouped and layers stop clipping unless their clipping path or clipped artwork overlaps a locked artboard, their released clipping paths kept as plain paths), compoundPaths?: bool (true: compound paths, and paths of several subpaths, become one path per subpath); at least one of the three true; `scope` and the three are never null} take apart every container of the kinds asked for, at every level of nesting, as one undo step when one goes; layers stay; each object keeps the opacity of the groups and compound paths it was in, and a compound path's paths take its paint; objects with live effects on their appearance or fill and stroke rows, groups with fill or stroke rows of their own, objects with an opacity mask, compound shapes, Live Paint groups, graphs, dimensions, flares, Objects on Path, generated art, Shaper Groups, Image Trace objects, paths with Live Corners, blends, envelopes, repeats, intertwines and other live objects stay whole, including directly selected or named descendants; the entire clipping mask subtree of a clipping group or layer that stays is left as it is, including directly selected or named descendants; from the selection or the document, locked and hidden objects, and objects on a locked artboard, stay whole; named by `ids`, locked and hidden ones are taken apart too (their objects become locked or hidden as they were), but not those on a locked artboard; the selection keeps what it held, each object taken apart replaced by what it left, locked and hidden objects left out → {scope (\"selection\", \"document\" or \"ids\"), ids (the objects selected), groups, clipGroups, compoundPaths (how many of each were released)}",
has_doc,
release_all
)]
}
/// The kinds of container a request takes apart.
#[derive(Clone, Copy)]
struct Kinds {
groups: bool,
clips: bool,
compounds: bool,
}
impl Kinds {
/// Whether a group is taken apart: a clipping group (`clip`) with `clips`, another with `groups`.
fn takes_group(self, clip: bool) -> bool {
if clip { self.clips } else { self.groups }
}
}
/// One run over the objects: what it takes apart and what it found.
struct Release<'a> {
kinds: Kinds,
/// Locked and hidden objects are taken apart too.
named: bool,
/// The artwork on a locked artboard, which stays whole.
held: &'a HashSet<NodeId>,
/// Groups, clipping groups and layers, and compound paths released.
counts: [usize; 3],
/// Objects made from the containers taken apart.
made: usize,
/// Each container taken apart and the objects left in its place.
left: HashMap<NodeId, Vec<NodeId>>,
}
/// Whether `n` stays whole whatever is asked: a live object kept as a group or compound path
/// (a compound shape, Live Paint group, graph, dimension, flare, Objects on Path, generated art,
/// Shaper Group, Image Trace object, a clipping path's painted pieces), a path with Live Corners,
/// whose parts would lose their editable corners, one with an opacity mask or live effects
/// on its appearance or fill and stroke rows, or a group with fill or stroke rows of its own.
fn live(n: &Node) -> bool {
let x = n.extras();
matches!(&n.kind, NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. })
|| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))
|| !n.appearance.effects.is_empty()
|| n.appearance.items.iter().any(|item| !item.effects().is_empty())
|| x.mask.is_some()
|| x.shaper.is_some()
|| x.trace.is_some()
|| x.graph.is_some()
|| x.dimension.is_some()
|| x.flare.is_some()
|| x.objects_on_path.is_some()
|| x.generated.is_some()
|| x.live_paint_gaps.is_some()
|| x.clip_pieces
|| (matches!(&n.kind, NodeKind::Group { .. }) && !n.appearance.items.is_empty())
|| n.is_compound_shape()
|| is_live_paint(n)
}
/// The artwork under `n` is added to `out`.
fn candidates(n: &Node, clips: bool, out: &mut Vec<NodeId>) {
let candidate = match &n.kind {
NodeKind::Layer { .. } => false,
NodeKind::Group { .. } | NodeKind::Compound { .. } => true,
NodeKind::Path { path, .. } => clips || path.subpaths.len() > 1,
_ => clips,
};
if candidate {
out.push(n.id);
}
if let Some(children) = n.children() {
children.iter().for_each(|c| candidates(c, clips, out));
}
}
impl Release<'_> {
fn total(&self) -> usize {
self.counts.iter().sum()
}
/// Whether `n` is left as it is: locked or hidden (unless named), on a locked artboard, or live.
fn keeps(&self, n: &Node) -> bool {
(!self.named && (n.locked || !n.visible)) || self.held.contains(&n.id) || live(n)
}
/// `n` with the containers in it released, into `out`; `member` counts what a container left.
fn node(&mut self, d: &mut Document, n: Arc<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
if self.keeps(&n) {
if member {
self.made(1)?;
}
out.push(n);
return Ok(());
}
match &n.kind {
NodeKind::Group { clip, .. } if self.kinds.takes_group(*clip) => {
let clip = *clip;
self.counts[usize::from(clip)] += 1;
self.take_apart(d, n, clip, false, out)
}
NodeKind::Compound { .. } if self.kinds.compounds => {
self.counts[2] += 1;
self.take_apart(d, n, false, true, out)
}
NodeKind::Path { path, clipping: false, guide: false, .. } if self.kinds.compounds && path.subpaths.len() > 1 => {
self.counts[2] += 1;
self.split(d, (*n).clone(), out)
}
NodeKind::Group { .. } | NodeKind::Layer { .. } => self.keep(d, n, member, out),
_ => {
if member {
self.made(1)?;
}
out.push(n);
Ok(())
}
}
}
/// Group or compound path `n` replaced by its members, released in turn. Members take on the
/// container's opacity, are hidden when it was hidden and locked when it was locked; a
/// compound path's take its paint; a clipping group's clipping path becomes a plain path.
fn take_apart(&mut self, d: &mut Document, n: Arc<Node>, clip: bool, compound: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
let Some(children) = n.children() else { return Ok(()) };
let mut parts = vec![];
for (k, c) in children.iter().enumerate() {
let mut c = (**c).clone();
if clip
&& k == 0
&& let NodeKind::Path { clipping, .. } = &mut c.kind
{
*clipping = false;
}
if compound {
c.appearance = n.appearance.clone();
if n.extras().pixel_aligned {
c.extras_mut().pixel_aligned = true;
}
}
c.opacity *= n.opacity;
c.visible &= n.visible;
c.locked |= n.locked;
self.node(d, Arc::new(c), true, &mut parts)?;
}
self.left.insert(n.id, parts.iter().map(|p| p.id).collect());
out.extend(parts);
Ok(())
}
/// Path `n` of several subpaths as one path per subpath with its paint, in the same stacking
/// order; the first keeps its id.
fn split(&mut self, d: &mut Document, n: Node, out: &mut Vec<Arc<Node>>) -> Result<()> {
let Some(path) = n.path_data() else { return Ok(()) };
if self.made.saturating_add(path.subpaths.len()) > MAX_OBJECTS {
return Err(EngineError::Other("Release All Containers: too many objects to release at once".into()));
}
let mut template = n.clone();
if let NodeKind::Path { path, live, .. } = &mut template.kind {
(*path, *live) = (PathData::single(Default::default()), None);
}
let mut parts = Vec::with_capacity(path.subpaths.len());
for (k, sp) in path.subpaths.iter().enumerate() {
let mut c = if k == 0 { template.clone() } else { d.reid(&template) };
if let NodeKind::Path { path, live, .. } = &mut c.kind {
(*path, *live) = (PathData::single(sp.clone()), None);
}
parts.push(Arc::new(c));
}
self.made(parts.len())?;
self.left.insert(n.id, parts.iter().map(|p| p.id).collect());
out.extend(parts);
Ok(())
}
/// Group or layer `n` kept, with the containers in it released. A layer stops clipping when
/// clipping groups are released; the clipping path of a group or layer that still clips is
/// left as it is. Unchanged, `n` itself goes to `out`.
fn keep(&mut self, d: &mut Document, mut n: Arc<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
if member {
self.made(1)?;
}
let before = self.total();
let mut clips = n.clips();
if clips && n.is_layer() && self.kinds.clips && !n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c))) {
self.counts[1] += 1;
let n = Arc::make_mut(&mut n);
n.set_clips(false);
clips = false;
if let Some(first) = n.children_mut().and_then(|c| c.first_mut())
&& let NodeKind::Path { clipping, .. } = &mut Arc::make_mut(first).kind
{
*clipping = false;
}
}
let Some(children) = n.children() else {
out.push(n);
return Ok(());
};
let mut kept = Vec::with_capacity(children.len());
for (k, c) in children.iter().enumerate() {
if clips && k == 0 {
if member {
self.made(1)?;
}
kept.push(Arc::clone(c));
} else {
self.node(d, Arc::clone(c), member, &mut kept)?;
}
}
if self.total() != before
&& let Some(ch) = Arc::make_mut(&mut n).children_mut()
{
*ch = kept;
}
out.push(n);
Ok(())
}
fn holds_art(&self, n: &Node) -> bool {
self.held.contains(&n.id) || n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c)))
}
/// Counts the objects made, refusing a run that makes too many.
fn made(&mut self, count: usize) -> Result<()> {
self.made += count;
if self.made > MAX_OBJECTS {
return Err(EngineError::Other("Release All Containers: too many objects to release at once".into()));
}
Ok(())
}
/// `id`, or the objects left in its place when it was taken apart.
fn replaced(&self, id: NodeId, into: &mut Vec<NodeId>) {
match self.left.get(&id) {
Some(ids) => into.extend(ids),
None => into.push(id),
}
}
}
/// Whether shown artwork in `n` overlaps a locked artboard: a plain group that is not live
/// ([`live`]) by its shown members, anything else by its own bounds.
fn shows_on(locks: &LockedArtboards<'_>, n: &Node) -> bool {
if !n.visible {
return false;
}
match (&n.kind, n.children()) {
(NodeKind::Group { clip: false, .. }, Some(children)) if !live(n) => children.iter().any(|c| shows_on(locks, c)),
_ => locks.holds(n),
}
}
/// Whether `id` is in the clipping mask subtree of a clipping group or layer.
fn in_clipping_mask(d: &Document, id: NodeId) -> bool {
d.ancestry(id).is_some_and(|chain| {
chain
.windows(2)
.any(|pair| d.node(pair[0]).is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == pair[1])))
})
}
fn release_all(s: &mut Session, p: &Value) -> Result<Value> {
if !p.is_object() {
return Err(bad(COMMAND, "parameters must be an object"));
}
for key in ["groups", "clipGroups", "compoundPaths"] {
if p.get(key).is_some_and(|v| !v.is_boolean()) {
return Err(bad(COMMAND, format!("`{key}` must be true or false")));
}
}
if p.get("scope").is_some_and(|v| !matches!(v.as_str(), Some("selection" | "document"))) {
return Err(bad(COMMAND, "`scope` must be \"selection\" or \"document\""));
}
if let Some(ids) = p.get("ids").filter(|v| !v.is_null()) {
let ids = ids.as_array().ok_or_else(|| bad(COMMAND, "`ids` must be an array of non-negative integer object ids"))?;
let mut seen = HashSet::new();
for id in ids {
let id = id.as_u64().ok_or_else(|| bad(COMMAND, "`ids` must contain non-negative integer object ids"))?;
if !seen.insert(id) {
return Err(bad(COMMAND, format!("duplicate object id {id} in `ids`")));
}
}
}
let kinds = Kinds {
groups: switch_or(p, "groups", true, COMMAND)?,
clips: switch_or(p, "clipGroups", true, COMMAND)?,
compounds: switch_or(p, "compoundPaths", true, COMMAND)?,
};
if !(kinds.groups || kinds.clips || kinds.compounds) {
return Err(bad(COMMAND, "`groups`, `clipGroups` and `compoundPaths` are all false: there is nothing to release"));
}
let named = named(p);
if named && p.get("scope").is_some() {
return Err(bad(COMMAND, "give `scope` or `ids`, not both"));
}
let (roots, name) = if named {
let mut roots = checked_ids_or_selection(s, p, COMMAND)?;
retain_targets(&s.doc()?.doc, &mut roots, true, |id| *id);
(roots, "ids")
} else {
match scope_of(s, p, COMMAND)? {
(Scope::Document, name) => (s.doc()?.doc.layers.iter().map(|l| l.id).collect(), name),
(Scope::Objects(mut roots), name) => {
retain_targets(&s.doc()?.doc, &mut roots, false, |id| *id);
(roots, name)
}
}
};
let st = s.doc()?;
let (mut d, mut sel) = ((*st.doc).clone(), st.selection.clone());
// The artwork on a locked artboard, found while nothing is changed yet.
let held: HashSet<NodeId> = if d.artboards.iter().any(|a| a.locked) {
let mut found = vec![];
for n in roots.iter().filter_map(|id| d.node(*id)) {
candidates(n, kinds.clips, &mut found);
}
let locks = d.locked_artboards();
let mut held: HashSet<NodeId> = found.iter().copied().filter(|id| locks.holds_id(*id)).collect();
// A shown clipping group whose clipped artwork overlaps a locked artboard stays whole,
// wherever its clipping path lies, when clipping groups are released; the clipping groups
// the targets are in count too.
let ancestors = roots.iter().filter_map(|id| d.ancestry(*id)).flatten();
let clip_groups: HashSet<NodeId> = found
.iter()
.copied()
.chain(ancestors)
.filter(|id| kinds.clips && d.node(*id).is_some_and(|n| matches!(&n.kind, NodeKind::Group { clip: true, .. })))
.collect();
// Pattern editing mode's art is on no artboard.
let pattern_layer = d.pattern_edit.as_ref().map(|e| e.layer);
for id in clip_groups {
let shown = d.ancestry(id).is_some_and(|chain| chain.iter().all(|a| Some(*a) != pattern_layer && d.node(*a).is_some_and(|n| n.visible)));
if shown
&& let Some(n) = d.node(id)
&& n.children().is_some_and(|c| c.iter().skip(1).any(|c| shows_on(&locks, c)))
{
held.insert(id);
}
}
held
} else {
HashSet::new()
};
let mut run = Release { kinds, named, held: &held, counts: [0; 3], made: 0, left: HashMap::new() };
let mut items = vec![];
for id in roots {
// Direct targets inside a live object or clipping mask stay whole.
let protected =
d.ancestry(id).is_some_and(|chain| chain.iter().take(chain.len().saturating_sub(1)).filter_map(|id| d.node(*id)).any(|n| run.keeps(n)));
if in_clipping_mask(&d, id) || protected {
continue;
}
let Some(n) = d.node_arc(id).cloned() else { continue };
let before = run.total();
let mut out = vec![];
run.node(&mut d, n, false, &mut out)?;
if run.total() != before {
items.push((id, out.into_iter().map(Arc::unwrap_or_clone).collect()));
}
}
let [groups, clips, compounds] = run.counts;
// With nothing to release, the document, the selection and the undo history stay as they are.
if run.total() == 0 {
let ids: Vec<u64> = sel.objects.iter().map(|i| i.0).collect();
return Ok(json!({ "scope": name, "ids": ids, "groups": 0, "clipGroups": 0, "compoundPaths": 0 }));
}
d.insert_beside(items, true)?;
let mut ids = vec![];
for id in sel.objects.iter() {
run.replaced(*id, &mut ids);
}
// Locked and hidden objects, and those in locked or hidden groups, are not selected.
{
let editable = d.editable();
ids.retain(|id| editable(*id));
}
let kept: HashSet<NodeId> = ids.iter().copied().collect();
let removed: Vec<NodeId> = sel.objects.iter().copied().filter(|id| run.left.contains_key(id) || !kept.contains(id)).collect();
sel.remove_all(removed);
let mut seen = HashSet::new();
sel.objects = ids.into_iter().filter(|id| seen.insert(*id)).collect();
sel.prune(&d);
let ids: Vec<u64> = sel.objects.iter().map(|i| i.0).collect();
s.edit("Release All Containers", |doc, selection| {
*doc = d;
*selection = sel;
Ok(())
})?;
Ok(json!({ "scope": name, "ids": ids, "groups": groups, "clipGroups": clips, "compoundPaths": compounds }))
}
@@ -0,0 +1,860 @@
//! Release All Containers: every level taken apart as one undo step, the kinds asked for only,
//! the selection, the document and named objects, clipping layers, what stays whole, and refusals.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, LiveShape, Node, NodeId, NodeKind};
use crate::Session;
const C: &str = "addon.cleanup.releaseAll";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64, y: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap())
}
fn node(s: &Session, id: NodeId) -> Option<Node> {
s.doc().unwrap().doc.node(id).cloned()
}
fn change(s: &mut Session, id: NodeId, f: impl FnOnce(&mut Node)) {
s.edit("t", |d, _| {
f(d.node_mut(id).unwrap());
Ok(())
})
.unwrap();
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.select(|_, sel| sel.set(ids.iter().copied())).unwrap();
}
fn selected(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().selection.objects.to_vec()
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// The objects directly in layer `k`.
fn layer(s: &Session, k: usize) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[k].children().unwrap().iter().map(|n| n.id).collect()
}
fn group(s: &mut Session, ids: &[NodeId]) -> NodeId {
select(s, ids);
id_of(&s.execute("object.group", &json!({})).unwrap())
}
fn compound(s: &mut Session, ids: &[NodeId]) -> NodeId {
select(s, ids);
id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap())
}
/// A clipping group of `ids`, the last of them the clipping path.
fn clip_group(s: &mut Session, ids: &[NodeId]) -> NodeId {
select(s, ids);
id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap())
}
fn counts(r: &Value) -> (u64, u64, u64) {
(r["groups"].as_u64().unwrap(), r["clipGroups"].as_u64().unwrap(), r["compoundPaths"].as_u64().unwrap())
}
fn plain(s: &Session, id: NodeId) -> bool {
matches!(node(s, id).unwrap().kind, NodeKind::Path { clipping: false, ref path, .. } if path.subpaths.len() == 1)
}
fn red() -> Appearance {
Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0)
}
#[test]
fn release_all_takes_apart_every_level_as_one_step() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let p = rect(&mut s, 70.0, 10.0);
let q = rect(&mut s, 75.0, 15.0);
let holes = compound(&mut s, &[p, q]);
change(&mut s, holes, |n| n.appearance = red().into());
let inner = group(&mut s, &[b, holes]);
change(&mut s, inner, |n| n.opacity = 0.5);
let clipped = rect(&mut s, 110.0, 10.0);
let clip = rect(&mut s, 105.0, 5.0);
let masked = clip_group(&mut s, &[clipped, clip]);
let outer = group(&mut s, &[a, inner, masked]);
select(&mut s, &[outer]);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(counts(&r), (2, 1, 1), "{r}");
assert_eq!(r["scope"], "selection");
assert_eq!(undo_steps(&s), steps + 1, "one undo step");
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Release All Containers");
assert_eq!(layer(&s, 0), [a, b, p, q, clip, clipped], "only paths are left, in their stacking order");
assert!([a, b, p, q, clip, clipped].iter().all(|id| plain(&s, *id)), "the clipping path is a plain path");
assert!(node(&s, outer).is_none() && node(&s, inner).is_none() && node(&s, holes).is_none() && node(&s, masked).is_none());
assert_eq!((node(&s, b).unwrap().opacity, node(&s, p).unwrap().opacity), (0.5, 0.5), "members keep their groups' opacity");
assert_eq!(*node(&s, q).unwrap().appearance, red(), "a compound path's paths take its paint");
assert_eq!(selected(&s), [a, b, p, q, clip, clipped], "what the selected group left is selected");
assert_eq!(r["ids"], json!([a.0, b.0, p.0, q.0, clip.0, clipped.0]));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer(&s, 0), [outer]);
}
#[test]
fn release_all_counts_each_object_left_once() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let c = rect(&mut s, 70.0, 10.0);
let p = rect(&mut s, 100.0, 10.0);
let second = node(&s, p).unwrap().path_data().unwrap().subpaths[0].clone();
change(&mut s, p, |n| {
if let NodeKind::Path { path, .. } = &mut n.kind {
path.subpaths.push(second);
}
});
let inner = group(&mut s, &[a, b, c, p]);
change(&mut s, inner, |n| n.set_clips(true));
let middle = group(&mut s, &[inner]);
let outer = group(&mut s, &[middle]);
let held = std::collections::HashSet::new();
for clips in [true, false] {
let mut d = (*s.doc().unwrap().doc).clone();
let n = d.node_arc(outer).unwrap().clone();
let mut run = super::Release {
kinds: super::Kinds { groups: true, clips, compounds: true },
named: false,
held: &held,
counts: [0; 3],
made: 0,
left: std::collections::HashMap::new(),
};
let mut out = vec![];
run.node(&mut d, n, false, &mut out).unwrap();
if clips {
assert_eq!(out.len(), 5);
assert_eq!(run.made, out.len(), "each path is counted once");
} else {
assert_eq!(out.len(), 1);
let children = out[0].children().unwrap();
assert_eq!(children.len(), 5);
assert_eq!(run.made, out.len() + children.len(), "the kept group and its paths are counted once");
}
}
}
#[test]
fn release_all_takes_only_the_kinds_asked_for() {
let mut s = session();
let p = rect(&mut s, 10.0, 10.0);
let q = rect(&mut s, 15.0, 15.0);
let holes = compound(&mut s, &[p, q]);
let clipped = rect(&mut s, 110.0, 10.0);
let e = rect(&mut s, 105.0, 5.0);
let f = rect(&mut s, 108.0, 8.0);
let clip = compound(&mut s, &[e, f]);
let masked = clip_group(&mut s, &[clipped, clip]);
let outer = group(&mut s, &[holes, masked]);
// Without groups, the group stays and what is inside it is still released, but for the
// clipping path of the clipping group that stays.
select(&mut s, &[outer]);
let r = s.execute(C, &json!({"groups": false, "clipGroups": false})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "{r}");
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(p), Some(outer));
assert!(d.node(holes).is_none() && d.node(clip).is_some() && d.node(masked).is_some());
assert_eq!(selected(&s), [outer]);
// Without compound paths, the groups go and the compound path stays.
let r = s.execute(C, &json!({"compoundPaths": false})).unwrap();
assert_eq!(counts(&r), (1, 1, 0), "{r}");
assert_eq!(layer(&s, 0), [p, q, clip, clipped]);
assert!(matches!(node(&s, clip).unwrap().kind, NodeKind::Compound { .. }));
// Then only compound paths: the clipping path's paths, unpainted as it was.
select(&mut s, &[clip]);
let r = s.execute(C, &json!({"groups": false, "clipGroups": false})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "{r}");
assert_eq!(layer(&s, 0), [p, q, e, f, clipped]);
}
#[test]
fn release_all_splits_paths_of_several_subpaths() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let second = node(&s, b).unwrap().path_data().unwrap().subpaths[0].clone();
change(&mut s, a, |n| {
if let NodeKind::Path { path, .. } = &mut n.kind {
path.subpaths.push(second);
}
});
s.edit("t", |d, _| Ok(d.remove_many(&[b])?)).unwrap();
select(&mut s, &[a]);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "{r}");
let left = layer(&s, 0);
assert_eq!(left.len(), 2);
assert_eq!(left[0], a, "the first subpath keeps the path's id");
assert!(left.iter().all(|id| plain(&s, *id)));
assert_eq!(selected(&s), left);
assert_eq!(node(&s, left[1]).unwrap().appearance, node(&s, a).unwrap().appearance, "each part keeps the path's paint");
}
#[test]
fn release_all_keeps_a_path_of_several_subpaths_with_live_corners_whole() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let plain_path = rect(&mut s, 80.0, 10.0);
let second = node(&s, b).unwrap().path_data().unwrap().subpaths[0].clone();
for id in [a, plain_path] {
let second = second.clone();
change(&mut s, id, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
path.subpaths.push(second);
*live = None;
}
});
}
change(&mut s, a, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
let base = path.clone();
*live = Some(Box::new(LiveShape::Path { base, radii: vec![4.0], kinds: vec![], radii_relative: false }));
}
});
s.edit("t", |d, _| Ok(d.remove_many(&[b])?)).unwrap();
select(&mut s, &[a, plain_path]);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "only the plain path is split: {r}");
let kept = node(&s, a).unwrap();
assert!(matches!(kept.kind, NodeKind::Path { live: Some(_), ref path, .. } if path.subpaths.len() == 2), "Live Corners stay");
assert_eq!(layer(&s, 0).len(), 3);
}
#[test]
fn release_all_runs_on_the_document_while_nothing_is_selected() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let c = rect(&mut s, 70.0, 10.0);
let e = rect(&mut s, 100.0, 10.0);
let plain_group = group(&mut s, &[a]);
let locked = group(&mut s, &[b]);
change(&mut s, locked, |n| n.locked = true);
let hidden = group(&mut s, &[c]);
change(&mut s, hidden, |n| n.visible = false);
// A second layer that clips its art by its first path.
let second = id_of(&s.execute("layer.new", &json!({})).unwrap());
let mask = rect(&mut s, 0.0, 100.0);
let art = rect(&mut s, 10.0, 110.0);
let art_group = group(&mut s, &[art]);
s.edit("t", |d, _| {
let layer = d.node_mut(second).unwrap();
layer.set_clips(true);
if let Some(NodeKind::Path { clipping, .. }) = layer.children_mut().unwrap().first_mut().map(|c| &mut std::sync::Arc::make_mut(c).kind) {
*clipping = true;
}
Ok(())
})
.unwrap();
select(&mut s, &[]);
assert!(s.execute(C, &json!({"scope": "selection"})).is_err(), "nothing selected");
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(r["scope"], "document");
assert_eq!(counts(&r), (2, 1, 0), "{r}");
assert_eq!(undo_steps(&s), steps + 1);
assert_eq!(layer(&s, 0), [a, locked, hidden, e], "locked and hidden groups stay whole");
assert!(node(&s, plain_group).is_none() && node(&s, art_group).is_none());
let d = &s.doc().unwrap().doc;
assert!(!d.node(second).unwrap().clips(), "the layer stays and stops clipping");
assert!(plain(&s, mask), "its clipping path is a plain path");
assert_eq!(layer(&s, 1), [mask, art]);
assert!(selected(&s).is_empty(), "nothing was selected");
// Asked for the document with a selection, the selection keeps what it held.
let g = group(&mut s, &[e]);
select(&mut s, &[g]);
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{r}");
assert_eq!(selected(&s), [e]);
}
#[test]
fn release_all_takes_named_locked_and_hidden_containers() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let locked = group(&mut s, &[a]);
change(&mut s, locked, |n| n.locked = true);
let hidden = group(&mut s, &[b]);
change(&mut s, hidden, |n| n.visible = false);
select(&mut s, &[locked, hidden]);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "from the selection, they stay whole");
let r = s.execute(C, &json!({"ids": [locked.0, hidden.0]})).unwrap();
assert_eq!(r["scope"], "ids");
assert_eq!(counts(&r), (2, 0, 0), "{r}");
assert_eq!(undo_steps(&s), steps + 1);
let (na, nb) = (node(&s, a).unwrap(), node(&s, b).unwrap());
assert!(na.locked && na.visible && !nb.visible && !nb.locked, "their objects become locked or hidden as they were");
assert!(selected(&s).is_empty(), "locked and hidden objects are not selected");
// On a locked artboard, a named group stays whole.
let c = rect(&mut s, 10.0, 200.0);
let on_board = group(&mut s, &[c]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let r = s.execute(C, &json!({"ids": [on_board.0]})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
assert!(node(&s, on_board).is_some());
// Nor does one inside a named layer.
let layer_id = s.doc().unwrap().doc.layers[0].id;
let r = s.execute(C, &json!({"ids": [layer_id.0]})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
}
#[test]
fn release_all_leaves_masked_groups_whole_and_changes_nothing_without_a_container() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 15.0, 15.0);
let held = group(&mut s, &[a, b]);
let m = rect(&mut s, 0.0, 0.0);
s.execute("transparency.makeOpacityMask", &json!({"ids": [held.0, m.0]})).unwrap();
let masked = layer(&s, 0)[0];
assert!(node(&s, masked).unwrap().extras().mask.is_some());
let c = rect(&mut s, 100.0, 10.0);
select(&mut s, &[masked, c]);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "no step when nothing is released");
assert_eq!(r["ids"], json!([masked.0, c.0]), "the selection stays");
assert_eq!(layer(&s, 0), [masked, c]);
// A compound shape is a group that stays whole too.
let e = rect(&mut s, 200.0, 10.0);
let f = rect(&mut s, 210.0, 15.0);
select(&mut s, &[e, f]);
s.execute("object.compoundShape.make", &json!({})).unwrap();
let shape = selected(&s)[0];
assert!(node(&s, shape).unwrap().is_compound_shape());
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
assert!(node(&s, shape).unwrap().is_compound_shape());
}
#[test]
fn release_all_leaves_a_picked_clipping_path_of_a_clipping_group_that_stays() {
let mut s = session();
let clipped = rect(&mut s, 10.0, 10.0);
let e = rect(&mut s, 5.0, 5.0);
let f = rect(&mut s, 8.0, 8.0);
let clip = compound(&mut s, &[e, f]);
let masked = clip_group(&mut s, &[clipped, clip]);
let steps = undo_steps(&s);
for p in [json!({"ids": [clip.0]}), json!({"ids": [clip.0], "clipGroups": false})] {
let r = s.execute(C, &p).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "{p}");
}
select(&mut s, &[clip]);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(clip), Some(masked));
assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Compound { .. }));
}
#[test]
fn release_all_keeps_a_directly_named_descendant_of_a_live_object() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let inner = group(&mut s, &[a]);
let sources = group(&mut s, &[inner]);
change(&mut s, sources, |n| n.name = Some("Live Paint Sources".into()));
let live = group(&mut s, &[sources]);
change(&mut s, live, |n| n.name = Some("Live Paint Group".into()));
change(&mut s, sources, |n| n.visible = false);
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, live).unwrap()));
let steps = undo_steps(&s);
for id in [sources, inner] {
let r = s.execute(C, &json!({"ids": [id.0]})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, live).unwrap()));
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(sources));
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(inner));
}
}
#[test]
fn release_all_keeps_appearance_effects_and_directly_targeted_descendants() {
for item in [None, Some(0), Some(1)] {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 15.0, 15.0);
let inner = compound(&mut s, &[a, b]);
let c = rect(&mut s, 20.0, 20.0);
select(&mut s, &[inner, c]);
let applied = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
assert_eq!(applied["grouped"], true);
let live = selected(&s)[0];
assert!(matches!(node(&s, live).unwrap().kind, NodeKind::Group { clip: false, .. }));
assert!(!node(&s, live).unwrap().is_compound_shape());
assert_eq!(node(&s, live).unwrap().appearance.effects[0].id, "pathfinder.add");
if let Some(item) = item {
change(&mut s, live, |n| {
let effects = n.appearance.effects.clone();
*n.appearance = red();
*n.appearance.effects_mut(Some(item)).unwrap() = effects;
});
}
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for (target, params) in [
(live, json!({})),
(live, json!({"scope": "document"})),
(live, json!({"ids": [live.0]})),
(inner, json!({})),
(inner, json!({"ids": [inner.0]})),
] {
select(&mut s, &[target]);
let r = s.execute(C, &params).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{item:?}: {params}: {r}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), [target]);
assert_eq!(undo_steps(&s), steps);
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(live));
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(inner));
}
}
}
#[test]
fn release_all_keeps_a_layer_mask_over_locked_artboard_artwork() {
for named in [false, true] {
let mut s = session();
let mask = rect(&mut s, 0.0, 0.0);
let art = rect(&mut s, 10.0, 10.0);
let outside = rect(&mut s, 500.0, 10.0);
let g = group(&mut s, &[outside]);
let layer_id = s.doc().unwrap().doc.layers[0].id;
change(&mut s, layer_id, |n| n.set_clips(true));
change(&mut s, mask, |n| {
if let NodeKind::Path { clipping, .. } = &mut n.kind {
*clipping = true;
}
});
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let p = if named { json!({"ids": [layer_id.0]}) } else { json!({"scope": "document"}) };
let r = s.execute(C, &p).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{p}: {r}");
assert!(node(&s, layer_id).unwrap().clips());
assert!(matches!(node(&s, mask).unwrap().kind, NodeKind::Path { clipping: true, .. }));
assert_eq!(layer(&s, 0), [mask, art, outside]);
assert!(node(&s, g).is_none());
}
}
#[test]
fn release_all_keeps_a_layer_mask_that_alone_overlaps_a_locked_artboard() {
for named in [false, true] {
let mut s = session();
let mask = rect(&mut s, 0.0, 0.0);
let outside = rect(&mut s, 500.0, 10.0);
let g = group(&mut s, &[outside]);
let layer_id = s.doc().unwrap().doc.layers[0].id;
change(&mut s, layer_id, |n| n.set_clips(true));
change(&mut s, mask, |n| {
if let NodeKind::Path { clipping, .. } = &mut n.kind {
*clipping = true;
}
});
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let original_mask = s.doc().unwrap().doc.node_arc(mask).unwrap().clone();
let steps = undo_steps(&s);
let p = if named { json!({"ids": [layer_id.0]}) } else { json!({"scope": "document"}) };
let r = s.execute(C, &p).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{p}: {r}");
assert_eq!(undo_steps(&s), steps + 1);
assert!(node(&s, layer_id).unwrap().clips());
assert!(matches!(node(&s, mask).unwrap().kind, NodeKind::Path { clipping: true, .. }));
assert!(std::sync::Arc::ptr_eq(&original_mask, s.doc().unwrap().doc.node_arc(mask).unwrap()));
assert_eq!(layer(&s, 0), [mask, outside]);
assert!(node(&s, g).is_none());
}
}
#[test]
fn release_all_keeps_a_clipping_group_whose_clipped_art_overlaps_a_locked_artboard() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(g));
assert!(node(&s, g).unwrap().clips());
}
#[test]
fn release_all_keeps_a_named_group_in_a_clipping_group_over_a_locked_artboard() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let other = rect(&mut s, 40.0, 10.0);
let inner = group(&mut s, &[art, other]);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [inner.0]})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(inner));
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(g));
}
#[test]
fn release_all_takes_apart_a_named_hidden_clipping_group_with_visible_art() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
change(&mut s, g, |n| n.visible = false);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [g.0]})).unwrap();
assert_eq!(counts(&r), (0, 1, 0), "{r}");
assert!(node(&s, g).is_none());
assert!(!node(&s, art).unwrap().visible);
}
#[test]
fn release_all_takes_apart_a_clipping_group_in_a_named_hidden_group() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
let other = rect(&mut s, 40.0, 10.0);
let outer = group(&mut s, &[g, other]);
change(&mut s, outer, |n| n.visible = false);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [outer.0]})).unwrap();
assert_eq!(counts(&r), (1, 1, 0), "{r}");
assert!(node(&s, g).is_none());
}
#[test]
fn release_all_ignores_hidden_clipped_art_over_a_locked_artboard() {
let mut s = session();
let hidden = rect(&mut s, 10.0, 10.0);
let shown = rect(&mut s, 600.0, 10.0);
let inner = group(&mut s, &[hidden, shown]);
change(&mut s, hidden, |n| n.visible = false);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 1, 0), "{r}");
assert!(node(&s, g).is_none());
assert!(!node(&s, hidden).unwrap().visible);
}
#[test]
fn release_all_keeps_a_clipping_group_whose_group_stroke_reaches_a_locked_artboard() {
let mut s = session();
let a = rect(&mut s, 600.0, 10.0);
let b = rect(&mut s, 640.0, 10.0);
let inner = group(&mut s, &[a, b]);
change(&mut s, inner, |n| n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 500.0).into());
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(g));
}
#[test]
fn release_all_ungroups_off_artboard_groups_in_a_kept_clipping_group() {
let mut s = session();
let a = rect(&mut s, 600.0, 10.0);
let b = rect(&mut s, 640.0, 10.0);
let inner = group(&mut s, &[a, b]);
let on = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, on, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document", "clipGroups": false})).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{r}");
assert!(node(&s, inner).is_none());
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g));
}
#[test]
fn release_all_takes_apart_pattern_editing_art_over_a_locked_artboard() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
let layer = d.layers[0].id;
d.pattern_edit = Some(vectorcraft_doc::PatternEdit { pattern: "Checks".into(), layer, original: None });
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 1, 0), "{r}");
assert!(node(&s, g).is_none());
}
#[test]
fn release_all_keeps_a_group_with_its_own_fill_or_stroke() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let g = group(&mut s, &[a, b]);
change(&mut s, g, |n| n.appearance = red().into());
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g));
assert_eq!(*node(&s, g).unwrap().appearance, red());
}
#[test]
fn release_all_reuses_unchanged_siblings_when_rebuilding_a_layer() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let g = group(&mut s, &[b]);
let original = s.doc().unwrap().doc.node_arc(a).unwrap().clone();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0));
assert!(node(&s, g).is_none());
assert!(std::sync::Arc::ptr_eq(&original, s.doc().unwrap().doc.node_arc(a).unwrap()));
}
#[test]
fn release_all_keeps_selection_details_for_untouched_artwork() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let c = rect(&mut s, 70.0, 10.0);
let g = group(&mut s, &[c]);
s.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap();
let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap();
s.select(|_, sel| {
sel.set([a, b, g]);
sel.anchors.insert(a, [(0, 0), (0, 2)].into_iter().collect());
sel.anchors.insert(b, [(0, 0), (0, 1)].into_iter().collect());
sel.segments.insert(b, [(0, 0)].into_iter().collect());
sel.guides.push(guide);
sel.key_anchor = Some((a, (0, 0)));
})
.unwrap();
let before = s.doc().unwrap().selection.clone();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0));
let after = &s.doc().unwrap().selection;
assert_eq!(after.objects, [a, b, c]);
assert_eq!(after.anchors, before.anchors);
assert_eq!(after.segments, before.segments);
assert_eq!(after.guides, before.guides);
assert_eq!(after.key_anchor, before.key_anchor);
assert!(!after.objects.contains(&g));
change(&mut s, c, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
path.subpaths.push(path.subpaths[0].clone());
*live = None;
}
});
s.select(|_, sel| {
sel.anchors.insert(c, [(0, 0), (0, 1)].into_iter().collect());
sel.segments.insert(c, [(0, 0)].into_iter().collect());
})
.unwrap();
let r = s.execute(C, &json!({"ids": [c.0]})).unwrap();
assert_eq!(counts(&r), (0, 0, 1));
let after = &s.doc().unwrap().selection;
assert_eq!(after.anchors, before.anchors);
assert_eq!(after.segments, before.segments);
assert_eq!(after.guides, before.guides);
}
#[test]
fn release_all_keeps_a_directly_named_blend_key() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let key = group(&mut s, &[a, b]);
let c = rect(&mut s, 100.0, 10.0);
select(&mut s, &[key, c]);
let blend = id_of(&s.execute("object.blend.make", &json!({})).unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(key), Some(blend));
let before = s.doc().unwrap().doc.clone();
let selection = selected(&s);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({"ids": [key.0]})).unwrap();
assert_eq!(counts(&r), (0, 0, 0));
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), selection);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn release_all_keeps_a_direct_target_inside_a_compound_clipping_mask() {
for clipping_layer in [false, true] {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let a = rect(&mut s, 5.0, 5.0);
let b = rect(&mut s, 8.0, 8.0);
change(&mut s, a, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
path.subpaths.push(path.subpaths[0].clone());
*live = None;
}
});
let mask = compound(&mut s, &[a, b]);
let container = if clipping_layer {
let id = s.doc().unwrap().doc.layers[0].id;
change(&mut s, id, |n| {
n.children_mut().unwrap().swap(0, 1);
n.set_clips(true);
});
id
} else {
clip_group(&mut s, &[art, mask])
};
assert_eq!(node(&s, container).unwrap().children().unwrap()[0].id, mask);
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for named in [false, true] {
select(&mut s, &[a]);
let p = if named { json!({"ids": [a.0]}) } else { json!({"clipGroups": false}) };
let r = s.execute(C, &p).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{p}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), [a]);
assert_eq!(undo_steps(&s), steps);
}
}
}
#[test]
fn release_all_rejects_null_options_without_editing_artwork() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let g = group(&mut s, &[a]);
for selection in [vec![], vec![g]] {
select(&mut s, &selection);
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for key in ["scope", "groups", "clipGroups", "compoundPaths"] {
let mut p = json!({});
p[key] = Value::Null;
let error = s.execute(C, &p).unwrap_err();
assert!(matches!(error, crate::EngineError::BadParams { ref cmd, .. } if cmd == C), "{p}: {error}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), selection);
assert_eq!(undo_steps(&s), steps);
}
}
}
#[test]
fn release_all_rejects_duplicate_ids_before_traversal() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let g = group(&mut s, &[a]);
let b = rect(&mut s, 50.0, 10.0);
select(&mut s, &[g]);
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for ids in [vec![g.0, g.0], vec![b.0, b.0], vec![g.0, a.0, a.0]] {
let error = s.execute(C, &json!({"ids": ids})).unwrap_err();
assert!(matches!(error, crate::EngineError::BadParams { ref cmd, ref msg } if cmd == C && msg.contains("duplicate")), "{error}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), [g]);
assert_eq!(undo_steps(&s), steps);
}
}
#[test]
fn release_all_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let g = group(&mut s, &[a]);
select(&mut s, &[g]);
let steps = undo_steps(&s);
for bad in [
json!({"groups": false, "clipGroups": false, "compoundPaths": false}),
json!({"groups": "yes"}),
json!({"compoundPaths": 1}),
json!({"scope": "layer"}),
json!({"scope": "document", "ids": [g.0]}),
json!({"ids": [999_999]}),
] {
assert!(s.execute(C, &bad).is_err(), "{bad}");
}
assert_eq!(undo_steps(&s), steps);
assert!(node(&s, g).is_some());
}
+44 -9
View File
@@ -99,12 +99,19 @@ fn family_names(d: &Document) -> Result<BTreeSet<String>> {
note(family);
}
}
let mut graphs = Vec::new();
let (mut graphs, mut dimensions) = (Vec::new(), Vec::new());
view.visit_stored(|node, _| {
// A dimension's options name the family its label is redrawn in.
if let Some(dimension) = &node.extras().dimension {
dimensions.push(dimension.options.font_family.clone());
}
if node.extras().graph.is_some() {
graphs.push(node.id);
}
});
for mut family in dimensions {
note(&mut family);
}
for id in graphs {
if let Some(node) = view.stored_node_mut(id) {
graph_families(node, &mut note);
@@ -112,6 +119,9 @@ fn family_names(d: &Document) -> Result<BTreeSet<String>> {
}
fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) {
graph_families(node, note);
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) {
note(&mut dimension.options.font_family);
}
if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) {
brush_graphs(Arc::make_mut(&mut mask.art), note);
}
@@ -145,9 +155,15 @@ pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)
visit(&mut font.family);
}
}
// A live dimension makes its label again from its options.
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_deref_mut()) {
visit(&mut dimension.options.font_family);
// A dimension redraws its label from its own options, so they follow the label's family.
// A spelling that already names the same font, or one too long for the options, is kept.
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) {
let family = &mut dimension.options.font_family;
let mut renamed = family.clone();
visit(&mut renamed);
if !CompositeFont::same_name(&renamed, family) && renamed.len() <= ALIAS_BYTES_MAX {
*family = renamed;
}
}
graph_families(node, visit);
}
@@ -170,12 +186,22 @@ impl CompositeImport {
}
}
/// The longest family name in bytes that a dimension's options keep (`DimensionOptions::validate`).
const ALIAS_BYTES_MAX: usize = 256;
fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result<String> {
let db = FontDb::global();
let mut number = 2_u64;
loop {
let suffix = format!(" {number}");
let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect();
let bytes = ALIAS_BYTES_MAX.saturating_sub(suffix.len());
let mut stem = String::new();
for c in base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())) {
if stem.len() + c.len_utf8() > bytes {
break;
}
stem.push(c);
}
let name = format!("{}{suffix}", stem.trim_end());
if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str())
&& !reserved.contains(&name.to_lowercase())
@@ -189,7 +215,13 @@ fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result
/// Plan used incoming definitions before changing either document or the font database.
/// Keep existing meanings even for an uninstalled family that destination art still names.
pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<String>, target: &Document, cmd: &str) -> Result<CompositeImport> {
pub(super) fn plan_import(
source: Vec<CompositeFont>,
source_families: BTreeSet<String>,
dimension_families: BTreeSet<String>,
target: &Document,
cmd: &str,
) -> Result<CompositeImport> {
if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX {
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
@@ -230,12 +262,15 @@ pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<
let mut names = BTreeMap::new();
let mut combined = target.composite_fonts.to_vec();
for font in source {
let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent);
let dimension = dimension_families.contains(&font.name.to_lowercase());
let equal = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
// A dimension keeps its own spelling of a reused name of the same font, so only an alias
// under another name has to fit the bytes its options keep.
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equal);
let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name));
if needs_alias {
// A repeated import reuses its already-installed equal alias.
reused = target.composite_fonts.iter().find(equivalent);
reused = target.composite_fonts.iter().find(|other| equal(other) && (!dimension || other.name.len() <= ALIAS_BYTES_MAX));
}
let name = match reused {
Some(other) => other.name.clone(),
+3 -3
View File
@@ -117,8 +117,8 @@ pub use save::{
};
pub(crate) use screens::{
PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS,
check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings,
with_export_preset as with_screen_export_preset,
check_settings as check_screen_settings, export as export_screens, safe_file_name, sharing_names as sharing_screen_names,
store_settings as store_screen_settings, with_export_preset as with_screen_export_preset,
};
pub use screens::{
PRESET_FILE_EXTS as SCREEN_EXPORT_PRESET_EXTS, PRESET_FILE_FORMAT as SCREEN_EXPORT_PRESET_FORMAT, PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS,
@@ -184,7 +184,7 @@ pub use formats::{
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions,
open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions,
readable_format, readable_format_for_name, titled_for_export, writable_format,
readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format,
};
#[cfg(test)]
+5
View File
@@ -28,6 +28,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
// file, format and saved state share their data with the open ones until a step changes them.
let start = s.docs.clone();
let active = s.active;
let style_trail = s.script_in_run.then(|| s.script_style_trail.clone());
// A rollback puts back the swatch renames recorded before the batch, including any its steps pushed out of the record.
let swatch_renames = s.swatch_renames.clone();
let opens = s.plugin_events_mark();
@@ -46,6 +47,10 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
Err(e) => {
s.swatch_renames = swatch_renames;
roll_back(s, start, &stash);
if let Some(mut trail) = style_trail {
trail.resources_scanned = s.script_style_trail.resources_scanned;
s.script_style_trail = trail;
}
// The documents the steps opened are closed again: plug-ins are not told of them.
s.forget_plugin_opens_since(opens);
s.notify_text_tool("batch.rollBack");
File diff suppressed because one or more lines are too long
+6 -4
View File
@@ -113,14 +113,16 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> {
UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str()))
}
/// Formats VectorCraft opens but doesn't write, with what to export instead.
const READ_ONLY_HINTS: &[(&str, &str)] = &[("dwg", "DWG files open but can't be written: export DXF instead, which CAD apps open")];
/// Formats VectorCraft opens but doesn't write (by id or extension), with what to export instead.
const READ_ONLY_HINTS: &[(&[&str], &str)] =
&[(&["dwg", "dws", "dwt"], "DWG files open but can't be written: export DXF instead, which CAD apps open")];
/// What to write instead of the format an id or extension (any case, leading dot allowed) names,
/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG).
/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG,
/// also a `.dws` or `.dwt` file).
pub fn write_hint(id_or_ext: &str) -> Option<&'static str> {
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(id, _)| *id == k).map(|(_, hint)| *hint))
unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(ids, _)| ids.contains(&k.as_str())).map(|(_, hint)| *hint))
}
impl Unsupported {
+1
View File
@@ -352,6 +352,7 @@ impl RasterOptions {
interlaced: self.interlaced.unwrap_or(false),
quality: self.quality()?.unwrap_or(90).min(100),
webp_lossless: self.lossless.unwrap_or(true),
webp_embed_icc: embed_icc,
jpeg: JpegOptions {
color_model,
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
+3 -2
View File
@@ -74,8 +74,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator<Item = String>, key: im
/// Write an export's files for the destination `path` → `{path, bytes, files?, linked?, …extra}`
/// (`files`: every file when there are several; `linked`: the images it links to); with no path
/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. Every path is
/// checked against the file access in force before the first file is written, so a refused path
/// writes none of them.
/// checked against the file access in force before the first file is written, so a path that
/// check refuses writes none of them. A write that fails after that check leaves the files
/// written before it.
pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result<Value> {
let files = enc.named(doc, path.unwrap_or(name));
let (main, linked) = files.split_at(enc.files.len());
+34 -6
View File
@@ -159,7 +159,7 @@ const EMBED_ICC: FormatOption = FormatOption {
name: "embedIcc",
ty: "boolean",
default: "true",
description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk)",
description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk); WebP: the sRGB profile in an ICCP chunk",
};
const IMAGE_MAP: FormatOption = FormatOption {
@@ -470,7 +470,22 @@ pub const FORMATS: &[Format] = &[
read: true,
write: true,
raster: true,
options: &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, LOSSLESS, WEBP_QUALITY],
options: &[
ARTBOARD,
ARTBOARDS,
RANGE,
USE_ARTBOARDS,
RECT,
PPI,
SCALE,
WIDTH,
HEIGHT,
BACKGROUND,
ANTI_ALIAS,
LOSSLESS,
WEBP_QUALITY,
EMBED_ICC,
],
},
Format {
id: "tiff",
@@ -562,10 +577,19 @@ pub const FORMATS: &[Format] = &[
// composite, the layers combined, or the preview with a note. Exports don't write them.
reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true),
// DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF
// reader with the DXF import options. Exports don't write them.
reader("dwg", "DWG", &["dwg"], "image/vnd.dwg", false),
// reader with the DXF import options; `.dws` drawing standards files are DWG drawings too.
// Exports don't write them.
reader("dwg", "DWG", &["dwg", "dws"], "image/vnd.dwg", false),
// `.dwt` drawing templates, DWG drawings read as `dwg` is; a template opens as a new untitled
// document. Exports don't write them.
reader("dwt", "DWG Template", &["dwt"], "image/vnd.dwg", false),
];
/// Is `id` a format read as a DWG drawing: `dwg` (also `.dws` files) or a `dwt` template?
pub fn reads_as_dwg(id: &str) -> bool {
matches!(id, "dwg" | "dwt")
}
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
pub const OPEN_EXTS: &[&str] = &[
"vectorcraft",
@@ -626,6 +650,8 @@ pub const OPEN_EXTS: &[&str] = &[
"cmx",
"pcraft",
"dwg",
"dws",
"dwt",
];
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
@@ -634,10 +660,10 @@ pub const OPEN_EXTS: &[&str] = &[
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft`
/// documents or DWG drawings either.
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either.
pub const UNASSOCIATED_EXTS: &[&str] = &[
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg",
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
];
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
@@ -729,6 +755,8 @@ pub const PLACE_EXTS: &[&str] = &[
"cmx",
"pcraft",
"dwg",
"dws",
"dwt",
"txt",
"rtf",
"docx",
+14 -11
View File
@@ -47,12 +47,14 @@ impl Loaded {
/// PDF, an EPS or `.ai` without ruler units, a raster image, a metafile, an Affinity file or
/// what an importer plug-in reads, as the reference app opens such files (#5820). A native
/// document (also one that an SVG, PDF, `.ai` or EPS file carries, `restored`), an SVG (the
/// units of its root's size, pixels when it gives none), a DXF or DWG drawing (the unit it was
/// read in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows
/// change, not its art.
/// units of its root's size, pixels when it gives none), a DXF or DWG drawing (also a DWG
/// template; the unit it was read in) and a `.ai` or EPS with ruler units keep theirs. Only the
/// units the document shows change, not its art.
pub(crate) fn with_unit_prefs(mut self, prefs: &Prefs) -> Self {
let records_units =
self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf" | "dwg");
let records_units = self.restored
|| self.doc.units_from_file
|| matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf")
|| super::reads_as_dwg(self.format.id);
if !records_units {
self.doc.units = crate::units::pref_unit(&prefs.units_general);
}
@@ -126,7 +128,8 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
return format("dxf");
}
if vectorcraft_cad::is_dwg(bytes) {
return format("dwg");
// A template keeps its meaning from the extension.
return by_name.filter(|f| f.id == "dwt").or_else(|| format("dwg"));
}
if let Some(kind) = vectorcraft_metafile::sniff(bytes) {
return format(kind.id());
@@ -563,8 +566,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
}
read
}
// A DWG drawing is read as the DXF craft-dwg converts it to.
"dxf" | "dwg" => {
// A DWG drawing (or template) is read as the DXF craft-dwg converts it to.
"dxf" | "dwg" | "dwt" => {
let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?;
(doc, warnings, false)
}
@@ -1021,9 +1024,9 @@ fn open_loaded(
.cloned()
.collect();
let source_path = path.clone().filter(|_| !losses.is_empty());
// A template (saved by Save as Template, or an .ait, .vctemplate or .cdt file) opens as a new
// untitled document.
let template = as_template || doc.template || matches!(format.id, "ait" | "template" | "cdt");
// A template (saved by Save as Template, or an .ait, .vctemplate, .cdt or .dwt file) opens as a
// new untitled document.
let template = as_template || doc.template || matches!(format.id, "ait" | "template" | "cdt" | "dwt");
if template {
doc.template = false;
doc.title = s.next_untitled();
+44 -1
View File
@@ -282,7 +282,11 @@ impl Row {
// The resolution is stored in the file too.
ScreenSize::Ppi(ppi) => o["ppi"] = json!(ppi),
size => {
o["scale"] = json!(size.scale_for(C, region)?);
let scale = size.scale_for(C, region)?;
if !scale.is_finite() || !(0.01..=64.0).contains(&scale) {
return Err(bad(C, "the effective raster scale must be between 0.01 and 64 pixels per point"));
}
o["scale"] = json!(scale);
if let Some(m) = o.as_object_mut() {
m.remove("ppi");
}
@@ -638,6 +642,25 @@ fn fold(name: &str) -> String {
.collect()
}
thread_local! {
/// The [`fold`]ed names the exports run by [`sharing_names`] on this thread have taken so far.
static SHARED_NAMES: std::cell::RefCell<Option<HashSet<String>>> = const { std::cell::RefCell::new(None) };
}
/// `f`, with every `document.exportForScreens` it runs on this thread naming its files around
/// the names the ones before it took, so a later export does not write over an earlier one's file
/// (it numbers its own: `-2`, `-3`…).
pub(crate) fn sharing_names<T>(f: impl FnOnce() -> T) -> T {
let outer = SHARED_NAMES.with(|n| n.borrow_mut().replace(HashSet::new()));
let r = f();
SHARED_NAMES.with(|n| *n.borrow_mut() = outer);
r
}
/// The key the names taken by an earlier export are held under in [`Output::taken`]: no file of
/// this export has it.
const EARLIER_EXPORT: &str = "\0earlier export";
/// The file names (and bytes) an export wrote, or the files it returns.
#[derive(Default)]
struct Output {
@@ -1194,6 +1217,11 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
let ungrown = (grown && o.assets.is_none() && o.layers.is_none() && o.selection.is_none()).then_some(original);
let crop = rows.iter().any(|r| r.format.id != "pdf");
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
for row in rows.iter().filter(|row| row.format.raster) {
for item in &items {
row.options_for(item.region, item.artboard)?;
}
}
// Before the folder is made or any row is written, with the artboards each file holds.
let single: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1);
let st = s.doc()?;
@@ -1348,6 +1376,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
create_dir(dir)?;
}
let mut out = Output::default();
// The names earlier exports of a [`sharing_names`] run took into the same files.
if !o.zip {
SHARED_NAMES.with(|n| {
for name in n.borrow().iter().flatten() {
out.taken.insert(name.clone(), EARLIER_EXPORT.to_string());
}
});
}
// The notes on the options, then the encoders' notes for every file, each once.
let mut notes: Vec<Note> = Vec::new();
for text in unused {
@@ -1426,6 +1462,13 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
files += 1;
}
}
if !o.zip {
SHARED_NAMES.with(|n| {
if let Some(shared) = n.borrow_mut().as_mut() {
shared.extend(out.taken.keys().cloned());
}
});
}
// A cancel that came while the last file was encoded returns no files. A folder export
// without a ZIP has written every file by now, so it returns them.
if o.zip || folder.is_none() {
@@ -140,3 +140,69 @@ fn dwg_is_read_only_and_detected_by_content() {
assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg")));
assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg"));
}
/// A `.dwt` drawing template opens as a new untitled document and a `.dws` standards file as the
/// drawing it is, each read as a `.dwg` with the same content is; a DXF named `.dwt` stays a DXF.
#[test]
fn a_dwt_template_opens_untitled_and_a_dws_opens_as_its_drawing() {
let dir = std::env::temp_dir().join(format!("vc-dwt-open-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let dwg = plan_dwg();
let mut s = Session::new();
open(&mut s, "plan.dwg", &dwg, json!({})).unwrap();
let (want_layers, want_leaves) = (layer_names(&s), leaves(&s).len());
let template = dir.join("plan.dwt");
std::fs::write(&template, &dwg).unwrap();
let r = s.execute("document.open", &json!({"path": template.to_string_lossy()})).unwrap();
assert_eq!(r["format"], "dwt");
assert!(r["title"].as_str().is_some_and(|t| t.starts_with("Untitled")), "a template opens untitled: {}", r["title"]);
let st = s.doc().unwrap();
assert!(st.path.is_none());
assert_eq!(st.doc.units, vectorcraft_doc::Unit::Millimeters, "the drawing's unit");
assert_eq!((layer_names(&s), leaves(&s).len()), (want_layers.clone(), want_leaves));
let standards = dir.join("plan.dws");
std::fs::write(&standards, &dwg).unwrap();
let r = s.execute("document.open", &json!({"path": standards.to_string_lossy()})).unwrap();
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("dwg"), Some("plan.dws")));
assert_eq!((layer_names(&s), leaves(&s).len()), (want_layers, want_leaves));
assert_eq!(detect("plan.dwt", &plan()).map(|f| f.id), Some("dxf"), "the content tells");
let _ = std::fs::remove_dir_all(&dir);
}
/// File › Place reads a `.dwt` or `.dws` drawing as it reads a `.dwg`: fitted to the artboard with
/// the same `dxf` options, in one undo step.
#[test]
fn a_dwt_or_dws_drawing_places_as_a_dwg_does() {
let dwg = plan_dwg();
let place = |name: &str| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("file.place", &json!({"name": name, "dataBase64": b64(&dwg), "dxf": {"fit": true, "center": false}})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{name}: one undo step");
let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
(r["format"].as_str().map(str::to_string), [b.x0, b.y0, b.x1, b.y1])
};
let (format, want) = place("plan.dwg");
assert_eq!(format.as_deref(), Some("dwg"));
assert_eq!(place("plan.dws"), (Some("dwg".to_string()), want));
assert_eq!(place("plan.dwt"), (Some("dwt".to_string()), want));
}
#[test]
fn dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf() {
let f = format("dwt").unwrap();
assert!(f.read && !f.write);
assert_eq!(readable_format("dws").map(|f| f.id), Some("dwg"));
for ext in ["dws", "dwt"] {
assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext), "{ext}");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let e = s.execute("document.export", &json!({"format": ext})).unwrap_err().to_string();
assert!(e.contains("export DXF instead"), "{ext}: {e}");
}
}
@@ -229,6 +229,31 @@ fn png_says_it_is_srgb_unless_embed_icc_is_false() {
assert!(f["options"].get("embedIcc").is_some(), "png lists embedIcc");
}
/// WebP, lossless or lossy, holds the sRGB profile in an `ICCP` chunk unless `embedIcc` is false,
/// in Export As and in Export for Screens' `settings.webp`, without a note on an unused option.
#[test]
fn webp_embeds_the_srgb_profile_unless_embed_icc_is_false() {
let mut s = session(40.0, 30.0, 1);
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap();
let has_iccp = |file: &[u8]| file.windows(4).any(|w| w == b"ICCP");
for lossless in [true, false] {
let on = s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap();
assert!(has_iccp(&b64(&on)), "lossless {lossless}");
let off = s.execute("document.export", &json!({"format": "webp", "lossless": lossless, "embedIcc": false})).unwrap();
assert!(!has_iccp(&b64(&off)), "lossless {lossless}");
assert_eq!(off["warnings"], json!([]), "lossless {lossless}: embedIcc is a WebP option");
}
let screens = |s: &mut Session, settings: Value| {
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp"}], "settings": settings})).unwrap();
b64(&r["files"][0])
};
assert!(has_iccp(&screens(&mut s, json!({}))));
assert!(!has_iccp(&screens(&mut s, json!({"webp": {"embedIcc": false}}))));
let r = s.execute("document.formats", &json!({})).unwrap();
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "webp").unwrap();
assert!(f["options"].get("embedIcc").is_some(), "webp lists embedIcc");
}
#[test]
fn formats_list_the_raster_options() {
let mut s = Session::new();
+7 -6
View File
@@ -95,13 +95,13 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() {
(b64(&r), r["warnings"].clone())
};
let (lossless, warnings) = export(&mut s, json!({}));
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
assert_eq!(webp_chunks(&lossless), [*b"VP8X", *b"ICCP", *b"VP8L"], "lossless with the profile by default");
assert_eq!(warnings, json!([]));
// Quality doesn't change a lossless file.
assert_eq!(export(&mut s, json!({"lossless": true, "quality": 10})).0, lossless);
let (lossy, warnings) = export(&mut s, json!({"lossless": false}));
assert_eq!(webp_chunks(&lossy), [*b"VP8 "], "opaque art is a plain lossy file");
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"VP8 "], "opaque art has no alpha chunk");
assert_eq!(warnings, json!([]), "no note: the file is lossy");
assert_eq!(export(&mut s, json!({"lossless": false, "quality": 90})).0, lossy, "quality 90 by default");
// At quality 90 each channel stays within 4 levels of the exact pixels on average.
@@ -114,10 +114,11 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() {
// Lower quality, smaller file.
let low = export(&mut s, json!({"lossless": false, "quality": 10})).0;
let high = export(&mut s, json!({"lossless": false, "quality": 95})).0;
assert_eq!(webp_chunks(&low), [*b"VP8 "]);
assert_eq!(webp_chunks(&low), [*b"VP8X", *b"ICCP", *b"VP8 "]);
assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len());
for q in [0, 100] {
assert_eq!(webp_chunks(&export(&mut s, json!({"lossless": false, "quality": q})).0), [*b"VP8 "], "quality {q}");
let file = export(&mut s, json!({"lossless": false, "quality": q, "embedIcc": false})).0;
assert_eq!(webp_chunks(&file), [*b"VP8 "], "quality {q}: a plain lossy file without the profile");
}
}
@@ -130,7 +131,7 @@ fn lossy_webp_keeps_translucent_pixels() {
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let file = |s: &mut Session, lossless: bool| b64(&s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap());
let (lossless, lossy) = (file(&mut s, true), file(&mut s, false));
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ALPH", *b"VP8 "]);
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"ALPH", *b"VP8 "]);
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
assert_eq!((lw, lh), (w, h));
let at = |px: &[u8], x: u32, y: u32| -> [u8; 4] {
@@ -161,7 +162,7 @@ fn webp_quality_out_of_its_range_is_refused() {
assert!(s.execute("document.export", &json!({"format": "webp", "quality": 101})).is_err());
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp", "lossless": false, "quality": 100}]})).unwrap();
let file = b64(&r["files"][0]);
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ICCP", *b"VP8 "]);
}
#[test]
+1 -1
View File
@@ -314,7 +314,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once no corner stores a radius or a corner kind other than round (a corner that an anchor move straightens draws no arc but keeps its radius and the path stays live); sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+7 -2
View File
@@ -598,14 +598,19 @@ fn round_strokes(n: &mut Node) -> bool {
/// Snap path object `n`'s horizontal and vertical straight segments ([`snap_segments`]). A path
/// with Live Corners snaps the outline its corners are cut from. Another live shape is moved and
/// scaled as a whole instead, from its path's bounds to the bounds of the snapped path, so that it
/// stays a live shape. Returns whether it changed.
/// stays a live shape. Relative radii of corners the snap straightens or bends are converted as an
/// anchor edit converts them ([`vectorcraft_doc::rebase_relative_radii`]). Returns whether it changed.
fn snap_path_node(n: &mut Node, half: bool, sc: Scaling) -> bool {
let NodeKind::Path { path, live, .. } = &mut n.kind else { return false };
let Some(shape) = live.as_deref_mut() else { return snap_segments(path, half) };
if let LiveShape::Path { base, .. } = shape {
if let LiveShape::Path { base, radii, radii_relative, .. } = shape {
let before = radii_relative.then(|| base.clone());
if !snap_segments(base, half) {
return false;
}
if let Some(before) = before {
vectorcraft_doc::rebase_relative_radii(&before, base, radii);
}
*path = shape.to_path();
return true;
}
+18 -2
View File
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Anchors",
[],
None,
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with rounded Live Corners, each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target; refused while an object of a symbol instance's art is selected",
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with Live Corners that store a radius (rounded, or straightened by an earlier move), each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target, and a straightened corner that bends again rounds again; refused while an object of a symbol instance's art is selected",
has_selection,
move_anchors
),
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Anchor Point",
[],
None,
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with rounded Live Corners, the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y)",
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
has_doc,
move_anchor
),
@@ -266,6 +266,22 @@ fn snap_undoes(s: &Session, ids: impl IntoIterator<Item = NodeId>, apply: impl F
let (Some(NodeKind::Path { path, live, .. }), Some(anchors)) = (st.doc.node(id).map(|n| &n.kind), st.selection.anchors.get(&id)) else {
continue;
};
// Relative radii of corners the edit bent and the snap straightened again are converted
// twice, and can come back off by rounding: an outline back where it was, with the same
// kinds and those radii, counts as no change.
if let Some(vectorcraft_doc::LiveShape::Path { base, radii, kinds, radii_relative: true }) = live.as_deref() {
if let Some(NodeKind::Path { path: after_path, live: after, .. }) = doc.node_mut(id).map(|n| &mut n.kind)
&& let Some(vectorcraft_doc::LiveShape::Path { base: b, radii: r, kinds: k, radii_relative: true }) = after.as_deref()
&& b == base
&& k == kinds
&& r.len() == radii.len()
&& r.iter().zip(radii).all(|(x, y)| (x - y).abs() <= 1e-12 * x.abs().max(y.abs()).max(1.0))
{
after.clone_from(live);
after_path.clone_from(path);
}
continue;
}
// A live path keeps its variant through an anchor edit, so only a rectangle or polygon
// needs the comparison below.
if !matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Rectangle { .. } | vectorcraft_doc::LiveShape::Polygon { .. })) {
+2 -2
View File
@@ -357,7 +357,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
let (natural, warnings) = (s.frame, s.warnings.clone());
return Ok(Loaded { name, format, art: Art::Document(s, link.clone(), !crop), natural, warnings, link: Some(link), board: None });
}
let anchored = matches!(format.id, "dxf" | "dwg") && (opts.dxf.fit || !opts.dxf.center);
let anchored = (format.id == "dxf" || fileio::reads_as_dwg(format.id)) && (opts.dxf.fit || !opts.dxf.center);
let (mut doc, warnings) = {
// Of the open options, only a DXF or DWG drawing's apply (the colour mode stays the file's).
let o = fileio::LoadOptions { dxf: opts.dxf, ..Default::default() };
@@ -380,7 +380,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
let board = doc.artboards.first().map(|a| a.rect).filter(|_| anchored);
let layers = std::mem::take(&mut doc.layers);
let symbols = doc.symbol_boxes();
let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "dwg" | "hpgl") {
let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "hpgl") || fileio::reads_as_dwg(format.id) {
// An SVG with `crop: "crop"` asked for is framed and clipped by its viewBox (its artboard),
// as a PDF by its page: art drawn on a shared canvas keeps its place and scale (#788). By
// default, as Illustrator places one, it is its art's bounds.
+14 -8
View File
@@ -545,16 +545,22 @@ fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, bru
/// Discover the incoming resource frontier and its composite-font users before planning
/// names or changing either document. Resource order and the no-composite fast path stay shared.
fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (Used, Vec<Brush>, BTreeSet<String>) {
fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (Used, Vec<Brush>, BTreeSet<String>, BTreeSet<String>) {
let mut used = Used::default();
let mut families = BTreeSet::new();
let mut note_family = |name: &mut String| {
families.insert(name.to_lowercase());
let mut dimension_families = BTreeSet::new();
let mut note_families = |node: &mut Node| {
if let Some(dimension) = &node.extras().dimension {
dimension_families.insert(dimension.options.font_family.to_lowercase());
}
node_families(node, &mut |name| {
families.insert(name.to_lowercase());
});
};
for n in nodes.iter_mut() {
refs(n, &mut |r| used.note(r));
if composites {
each_mut(n, &mut |node| node_families(node, &mut note_family));
each_mut(n, &mut note_families);
}
}
let src_brushes = vectorcraft_brush::library(src);
@@ -585,18 +591,18 @@ fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (U
for mut a in art {
refs(&mut a, &mut |r| used.note(r));
if composites {
each_mut(&mut a, &mut |node| node_families(node, &mut note_family));
each_mut(&mut a, &mut note_families);
}
}
}
(used, src_brushes, families)
(used, src_brushes, families, dimension_families)
}
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
/// `nodes` at the names they got.
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> {
let composites = !src.composite_fonts.is_empty() || !dst.composite_fonts.is_empty();
let (used, mut src_brushes, families) = collect_resources(src, nodes, composites);
let (used, mut src_brushes, families, dimension_families) = collect_resources(src, nodes, composites);
let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::<Vec<_>>();
// A family the source does not define as a composite font, which the destination defines as
// one, would draw in the destination's composite font after placement.
@@ -604,7 +610,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd:
.iter()
.any(|family| CompositeFont::named(&src.composite_fonts, family).is_none() && CompositeFont::named(&dst.composite_fonts, family).is_some());
// All representability/validation errors precede incoming or destination mutation.
let plan = if fonts.is_empty() && !undefined_clash { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
let plan = if fonts.is_empty() && !undefined_clash { None } else { Some(plan_import(fonts, families, dimension_families, dst, cmd)?) };
let staged;
let mut aliased = false;
let src = if let Some(plan) = &plan {
@@ -24,6 +24,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.cleanup.fix",
"addon.cleanup.joinText",
"addon.cleanup.rejoin",
"addon.cleanup.releaseAll",
"addon.cleanup.removeBreaks",
"addon.cleanup.replaceFonts",
"addon.cleanup.resetTextTransform",
+1
View File
@@ -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, &params);
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 {
+79 -10
View File
@@ -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));
+20 -5
View File
@@ -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
}
+12 -4
View File
@@ -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),
+119 -19
View File
@@ -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, &params))?;
let result = if KEEP_PATHS.contains(&id) {
keeping_paint(h, || keeping_paths(h, item, || edit_item(h, item, id, &params)))?
} else {
keeping_paint(h, || edit_item(h, item, id, &params))?
};
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
@@ -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) => {
@@ -998,9 +1067,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 {
@@ -1116,7 +1191,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<_, _>>()?;
@@ -1186,7 +1261,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(())
}
@@ -1249,7 +1324,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)
}
@@ -1263,14 +1338,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 };
@@ -1291,7 +1389,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)
}
@@ -1489,9 +1587,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 ----
@@ -1769,11 +1868,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
+24 -3
View File
@@ -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()
}
+5 -1
View File
@@ -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(&params);
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)?;
+19
View File
@@ -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.
+58 -8
View File
@@ -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, &params)
let r = command(host, &id, &params);
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) };
+2
View File
@@ -189,6 +189,7 @@ mod script_dom_defaults;
mod script_dom_images;
mod script_dom_paths;
mod script_dom_prefs;
mod script_dom_resources;
mod script_dom_tracing;
mod script_dom_transform;
mod script_engines;
@@ -201,6 +202,7 @@ mod script_print;
mod script_raster_capture;
mod script_run;
mod script_save_open;
mod script_screens;
mod script_scriptui;
mod script_styles;
mod script_tags;
@@ -526,6 +526,7 @@ fn ids_null_takes_the_selection_in_every_command_that_falls_back_to_it() {
("addon.arrange.sort", json!({"by": "area", "apply": "x"}), both),
("addon.cleanup.simplify", json!({}), rect),
("addon.cleanup.deepUngroup", json!({}), rect),
("addon.cleanup.releaseAll", json!({}), rect),
("addon.cleanup.rejoin", json!({}), rect),
("addon.color.nearestSwatch", json!({}), rect),
("addon.color.randomFill", json!({"seed": 1}), rect),
+39
View File
@@ -329,6 +329,45 @@ fn a_path_with_live_corners_snaps_its_inner_edges() {
assert!(pts.iter().all(|p| (p.1 - 20.3).abs() > 1e-6), "{pts:?}");
}
/// With relative radii, a move that bends a straightened corner and that the snap takes back
/// leaves the path, its stored radius and the undo history as they were, and the corner rounds at
/// its radius when a later move bends it.
#[test]
fn a_snap_that_takes_back_a_move_keeps_a_straightened_corners_relative_radius() {
let mut s = new_doc();
let id = path(&mut s, "M10 10 L40 20 L70 10 L70 40 L10 40 Z", 2.0);
s.execute("object.setLiveShape", &json!({"id": id, "corners": [1], "radius": 4})).unwrap();
// The corner's two anchors as drawn are 1 and 2: straighten it.
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 2]], "mode": "add"})).unwrap();
s.execute("path.moveAnchors", &json!({"dx": 0.0, "dy": -10.0})).unwrap();
s.execute("object.setLiveShape", &json!({"id": id, "relativeRadii": true})).unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [id]})).unwrap();
let live = |s: &Session| {
let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone();
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("no Live Corners") };
(path.clone(), live.clone())
};
let (path_before, live_before) = live(&s);
assert_eq!(points(&s, id), [(10.0, 10.0), (40.0, 10.0), (70.0, 10.0), (70.0, 40.0), (10.0, 40.0)]);
let undo = undo_len(&s);
// The straight corner and the anchor after it: the move bends the corner, the snap undoes it.
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 2]], "mode": "add"})).unwrap();
s.execute("path.moveAnchors", &json!({"dx": 0.0, "dy": 0.3})).unwrap();
let (path_after, live_after) = live(&s);
assert_eq!(path_after, path_before);
assert_eq!(live_after, live_before, "the stored radius is unchanged");
assert_eq!(undo_len(&s), undo, "no undo step for a move the snap took back");
// Bend it again: it rounds at 4 points.
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1]], "mode": "add"})).unwrap();
s.execute("path.moveAnchors", &json!({"dx": 0.0, "dy": 10.0})).unwrap();
let (path, live) = live(&s);
let c = vectorcraft_doc::LiveCorners::new(&path, Some(&*live)).unwrap();
assert!((c.drawn_radius(1) - 4.0).abs() < 1e-6, "{live:?}");
}
/// `path.setAnchors` and `object.setLiveShape` snap a pixel-aligned path again after they replace
/// its geometry.
#[test]
+31 -7
View File
@@ -741,8 +741,9 @@ fn assigning_the_reported_opacity_changes_nothing() {
let (mut s, a, _) = doc();
s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0 / 3.0})).unwrap();
let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s));
let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;");
assert_eq!(out, vec![json!(33.3333)]);
let r = run(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;").unwrap();
assert_eq!(r["log"], json!([33.3333]));
assert_eq!(r["slowestCommands"], json!([]), "no command runs for the opacity the item has");
assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before);
assert_eq!(undo_steps(&s), steps);
assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command");
@@ -842,8 +843,14 @@ fn a_layer_opacity_close_to_the_current_one_is_set() {
fn selection_assignment_is_atomic_across_invalid_items() {
let (mut s, a, b) = doc();
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];");
assert!(e.contains("Cannot select PathItem"), "{e}");
// The script catches the error and reads the selection before the run ends.
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems, e = '';\
try { d.selection = [p[0], p[1]]; } catch (x) { e = String(x); } vc.log(e); vc.log(d.selection.length);",
);
assert!(out[0].as_str().is_some_and(|e| e.contains("Cannot select PathItem")), "{out:?}");
assert_eq!(out[1], json!(0));
assert!(s.active().unwrap().selection.objects.is_empty());
// In either order, the refused assignment leaves nothing selected while the script runs.
let out = log(
@@ -875,6 +882,9 @@ fn selection_assignment_is_atomic_across_invalid_items() {
);
assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]);
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
// A list with an item repeated thousands of times selects it once.
log(&mut s, "var d = app.activeDocument, p = d.pageItems, l = []; for (var i = 0; i < 5000; i++) l.push(p[0], p[1]); d.selection = l;");
assert_eq!(s.active().unwrap().selection.objects, vec![b, a]);
// An item of another document cannot be selected here.
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let e = failure(&mut s, "app.activeDocument.selection = app.documents[1].pageItems[0];");
@@ -1828,7 +1838,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
] {
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
}
assert!(failure(&mut s, "app.activeDocument.swatches = 1;").contains("Document.swatches is not available yet"));
assert!(failure(&mut s, "app.activeDocument.gradients = 1;").contains("Document.gradients is not available yet"));
// A deleted item or an earlier run's document is stale first.
let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;");
assert!(e.contains("Stale page item"), "{e}");
@@ -3208,7 +3218,7 @@ fn select_tool_makes_the_named_tool_current_when_the_run_ends() {
#[test]
fn unsupported_members_say_so() {
let (mut s, _, _) = doc();
assert!(failure(&mut s, "app.activeDocument.swatches;").contains("Document.swatches is not available yet"));
assert!(failure(&mut s, "app.activeDocument.gradients;").contains("Document.gradients is not available yet"));
}
fn layer_names(s: &Session) -> Vec<String> {
@@ -4899,6 +4909,20 @@ fn a_stale_containers_list_throws_its_stale_error_for_any_index() {
}
}
/// A stale `layers` or `artboards` collection's `index(n)` throws the stale error for every
/// number, a negative or fractional one included, as the art collections do.
#[test]
fn stale_layers_and_artboards_throw_their_stale_error_for_any_index() {
let (mut s, ..) = doc();
run(&mut s, "#targetengine keep\nvar d = app.activeDocument, L = d.layers, A = d.artboards;").unwrap();
for list in ["L", "A"] {
for n in ["-1", "1.5", "0"] {
let e = failure(&mut s, &format!("#targetengine keep\n{list}.index({n});"));
assert!(e.contains("Stale document"), "{list}.index({n}): {e}");
}
}
}
/// `removeAll()` on a clip group releases its mask, so an object added to the group afterwards is
/// not its clipping path; the run's one undo step puts everything back.
#[test]
@@ -5388,7 +5412,7 @@ fn page_items_report_their_available_members_as_their_own() {
vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\
Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\
app.hasOwnProperty('activeDocument')]);\
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('swatches'),\
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('gradients'),\
p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);",
);
+317 -4
View File
@@ -1160,17 +1160,174 @@ fn compound_path_members_read_the_paint_they_are_given() {
assert_eq!(out[2], json!([true, true]), "the compound path holds the fill rule");
}
#[test]
fn paths_in_a_group_in_a_compound_shape_read_and_set_the_compound_shapes_paint() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [group, b.0]})).unwrap();
let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
let before = node(&s, a).appearance.clone();
let out = log(
&mut s,
"var p = null, all = app.activeDocument.pathItems; for (var i = 0; i < all.length; i++) if (all[i].geometricBounds[0] < 50) p = all[i];\
vc.log(p.parent.parent.typename); var c = new RGBColor(); c.red = 200; p.fillColor = c; p.strokeWidth = 4; vc.log([p.fillColor.red, p.strokeWidth]);",
);
assert_ne!(out[0], json!("Layer"), "the path is inside a group inside the compound shape");
assert_eq!(rounded(&out[1]), json!([200, 4]));
let Paint::Solid { color: Color::Rgb { r, .. }, .. } = node(&s, shape).appearance.fill_paint() else {
panic!("the compound shape has an RGB fill")
};
assert!((r - 200.0 / 255.0).abs() < 1e-3, "the compound shape takes the fill, got {r}");
assert_eq!(node(&s, a).appearance, before, "the nested path's own paint is left as it was");
}
#[test]
fn closed_set_on_an_empty_path_holds_until_it_has_points() {
let (mut s, _, _) = doc();
let out = log(
&mut s,
"var p = app.activeDocument.pathItems.add(); vc.log(p.closed); p.closed = true; vc.log(p.closed);\
p.setEntirePath([[0, 300], [40, 300], [40, 240]]); vc.log(p.closed);\
var q = app.activeDocument.pathItems.add(); q.closed = true; q.closed = false; q.setEntirePath([[0, 0], [1, 1]]); vc.log(q.closed);",
);
assert_eq!(out, vec![json!(false), json!(true), json!(true), json!(false)]);
let out = log(
&mut s,
"var p = app.activeDocument.pathItems.add(); p.closed = true; p.pathPoints.add(); vc.log(p.closed);\
p.closed = false; p.pathPoints.removeAll(); vc.log(p.closed);",
);
assert_eq!(out, vec![json!(true), json!(false)], "pathPoints.add keeps the state, and an opened path does not reopen closed");
let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap());
s.execute("object.lock", &json!({"ids": [id.0]})).unwrap();
let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints.length); p.closed = false; vc.log(p.closed);");
assert_eq!(out, vec![json!(0), json!(false)], "an unchanged assignment on a locked empty path is allowed");
}
#[test]
fn a_spot_color_reads_as_a_spot_color_and_keeps_its_link() {
let (mut s, a) = doc_with_paints();
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Ink", "tint": 40})).unwrap();
let before = node(&s, a).appearance.fill_paint();
let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.tint]);");
assert_eq!(rounded(&out[0]), json!(["SpotColor", 40]));
assert!(failure(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;").contains("SpotColor is not available yet"));
let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint]);");
assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 40]));
let steps = undo_steps(&s);
log(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;");
assert_eq!(undo_steps(&s), steps, "assigning the spot color the fill has records no step");
assert_eq!(node(&s, a).appearance.fill_paint(), before, "the fill stays linked to its swatch");
}
#[test]
fn a_spot_color_paints_its_spot_at_its_tint() {
let (mut s, a) = doc_with_paints();
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink'); c.tint = 50;\
p.fillColor = c; p.strokeColor = c; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint, p.strokeColor.tint]);",
);
assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 50, 50]));
let n = node(&s, a);
for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] {
match paint {
Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - 0.5).abs() < 1e-6, "{name} at {tint}"),
p => panic!("the paint is {p:?}"),
}
}
}
#[test]
fn a_spot_color_left_without_a_tint_paints_at_its_default() {
let (mut s, a) = doc_with_paints();
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink');\
p.fillColor = c; vc.log([p.fillColor.spot.name, p.fillColor.tint]);\
p.strokeColor = {typename: 'SpotColor', spot: d.spots.getByName('Ink')}; vc.log([p.strokeColor.spot.name, p.strokeColor.tint]);",
);
assert_eq!(rounded(&Value::Array(out)), json!([["Ink", 100], ["Ink", 0]]), "new SpotColor() starts at 100, a color without a tint is 0");
let n = node(&s, a);
for (paint, want) in [(n.appearance.fill_paint(), 1.0), (n.appearance.stroke_paint(), 0.0)] {
match paint {
Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - want).abs() < 1e-6, "{name} at {tint}"),
p => panic!("the paint is {p:?}"),
}
}
}
#[test]
fn a_global_process_link_read_as_a_spot_color_is_not_assigned() {
let (mut s, a) = doc_with_paints();
s.execute("swatch.new", &json!({"name": "Leaf", "color": "#3a9a40", "global": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Moss", "color": "#405a20", "global": true})).unwrap();
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Leaf", "tint": 60})).unwrap();
let b = rect(&mut s, 30.0, 30.0, 10.0, 10.0);
s.execute("paint.setFill", &json!({"ids": [b.0], "swatch": "Moss", "tint": 60})).unwrap();
let c = rect(&mut s, 60.0, 60.0, 10.0, 10.0);
s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap();
let paints = |s: &Session| [a, b, c].map(|id| node(s, id).appearance.fill_paint());
let before = paints(&s);
let steps = undo_steps(&s);
let out = log(
&mut s,
"var q = app.activeDocument.pathItems; vc.log([q[2].fillColor.typename, q[2].fillColor.spot === undefined, q[1].fillColor.typename, q[0].fillColor.typename]);",
);
// `pathItems` lists c (unlinked), b (Moss), a (Leaf) and the document's first rectangle.
assert_eq!(out, vec![json!(["SpotColor", true, "SpotColor", "RGBColor"])]);
for script in [
"var q = app.activeDocument.pathItems; q[2].fillColor = q[2].fillColor;",
"var q = app.activeDocument.pathItems; q[1].fillColor = q[2].fillColor;",
"var q = app.activeDocument.pathItems; q[0].fillColor = q[2].fillColor;",
] {
let e = failure(&mut s, script);
assert!(e.contains("global process swatch cannot be assigned yet"), "{script}: {e}");
assert_eq!(paints(&s), before, "{script}");
assert_eq!(undo_steps(&s), steps, "{script}");
}
}
#[test]
fn a_path_painted_with_registration_reads_and_takes_its_spot() {
let (mut s, a) = doc_with_paints();
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('[Registration]'); c.tint = 100;\
p.strokeColor = c; vc.log([p.strokeColor.typename, p.strokeColor.spot.name, p.strokeColor.tint]);",
);
assert_eq!(rounded(&out[0]), json!(["SpotColor", "[Registration]", 100]));
assert!(node(&s, a).appearance.stroke_paint().is_registration(), "the stroke is linked to Registration");
}
#[test]
fn a_spot_color_without_a_spot_of_the_document_is_refused() {
let (mut s, _) = doc_with_paints();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let layers = |s: &Session| s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect::<Vec<_>>();
let before = layers(&s);
let steps = undo_steps(&s);
for (source, part) in [
("app.documents[0].pathItems[0].fillColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"),
("var c = new SpotColor(); c.spot = 5; app.documents[0].pathItems[0].fillColor = c;", "SpotColor.spot must be a Spot"),
// `app.documents` lists the active document, the new one, first: the document with `Ink` is
// `documents[1]`.
("var a = app.documents[1], c = new SpotColor(); c.spot = a.swatches.getByName('Ink'); a.pathItems[0].fillColor = c;", "must be a Spot"),
(
"var a = app.documents[1], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); c.tint = 101; a.pathItems[0].fillColor = c;",
"SpotColor.tint",
),
(
"var a = app.documents[1], b = app.documents[0], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); b.pathItems[0].fillColor = c;",
"Cross-document",
),
] {
let e = failure(&mut s, source);
assert!(e.contains(part), "{source}: {e}");
}
assert_eq!(layers(&s), before);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn filled_true_on_a_filled_path_runs_no_command() {
let (mut s, _, _) = doc();
@@ -1349,6 +1506,145 @@ fn looking_for_changed_points_after_each_command_is_charged() {
assert_eq!(r.unwrap_or_else(|e| panic!("{e}"))["log"], json!([2]));
}
#[test]
fn paint_and_point_edits_keep_the_list_of_paths() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
for i in 0..50 {
rect(&mut s, f64::from(i % 10) * 10.0, f64::from(i / 10) * 10.0, 5.0, 5.0);
}
s.execute("select.none", &json!({})).unwrap();
let start = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get());
log(
&mut s,
"var ps = app.activeDocument.pathItems;\
for (var i = 0; i < ps.length; i++) { var c = new RGBColor(); c.red = i; ps[i].fillColor = c; ps[i].strokeWidth = 2;\
ps[i].fillOverprint = true; var q = ps[i].pathPoints[0]; q.anchor = [q.anchor[0] + 1, q.anchor[1]]; }",
);
let built = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get()) - start;
assert_eq!(built, 1, "the paths are listed once for 50 paint and point edits");
let out = log(&mut s, "var ps = app.activeDocument.pathItems; var n = ps.length; ps.rectangle(0, 0, 1, 1); vc.log([n, ps.length]);");
assert_eq!(out, vec![json!([50, 51])], "a new path is listed");
}
#[test]
fn an_edit_that_regenerates_shaper_art_lists_the_paths_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap();
for x in [0.0, 50.0] {
rect(&mut s, x, 50.0, 100.0, 100.0);
}
s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let sources = vectorcraft_doc::shaper::SOURCES;
let out = log(
&mut s,
&format!(
"var ps = app.activeDocument.pathItems, n = ps.length, src = null;\
for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src = ps[i];\
var q = src.pathPoints[0]; q.anchor = [q.anchor[0] + 200, q.anchor[1]]; src.fillColor = new GrayColor(); vc.log(ps.length);"
),
);
let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);");
assert_eq!(out, fresh, "the list after the edit matches a fresh run's");
}
#[test]
fn an_edit_that_drops_a_shaper_path_lists_the_paths_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap();
for x in [0.0, 50.0] {
rect(&mut s, x, 50.0, 100.0, 100.0);
}
s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let sources = vectorcraft_doc::shaper::SOURCES;
let before = log(&mut s, "vc.log(app.activeDocument.pathItems.length);");
// The paths are listed again after the first edit. The second edit takes the generated fill
// away, and a regeneration that makes no path makes no new id.
let out = log(
&mut s,
&format!(
"var ps = app.activeDocument.pathItems, n = ps.length, src = [];\
for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src.push(ps[i]);\
for (var i = 0; i < src.length; i++) {{ src[i].fillColor = new NoColor(); var m = ps.length; }} vc.log(ps.length);"
),
);
let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);");
assert_ne!(before, fresh, "the edit changes how many paths the document has");
assert_eq!(out, fresh, "the list after the edit matches a fresh run's");
}
#[test]
fn a_closed_setting_on_an_empty_path_ends_once_a_command_gives_it_points() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap());
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems[0]; p.closed = true;\
vc.run('path.setAnchors', {{id: {}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\
p.pathPoints.removeAll(); vc.log(p.closed);",
id.0
),
);
assert_eq!(out, vec![json!(false)], "the open points the command gave end the setting");
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems[0]; p.closed = true;\
vc.run('path.setAnchors', {{id: {0}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\
vc.run('path.setAnchors', {{id: {0}, subpaths: []}}); vc.log(p.closed);",
id.0
),
);
assert_eq!(out, vec![json!(false)], "clearing the points through a command does not restore the setting");
}
#[test]
fn a_kept_batch_ends_the_empty_path_closed_setting_even_when_it_removes_its_points() {
for fail in [false, true] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap();
let failure = if fail { ", {command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}" } else { "" };
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems[0]; p.closed = true; var failed = false;\
try {{ vc.run('command.batch', {{commands: [\
{{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\
{{command: 'path.setAnchors', params: {{id: {id}, subpaths: []}}}}{failure}]}}); }} catch (e) {{ failed = true; }}\
vc.log(failed); vc.log(p.pathPoints.length); vc.log(p.closed);"
),
);
assert_eq!(out, vec![json!(fail), json!(0), json!(fail)]);
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_failed_dataset_row_keeps_the_empty_path_closed_setting() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap();
s.execute("dataset.new", &json!({"name": "Row"})).unwrap();
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems[0]; p.closed = true;\
var r = vc.run('action.batch', {{source: 'datasets', commands: [\
{{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\
{{command: 'swatch.edit', params: {{name: 'No such swatch', color: '#000000'}}}}]}});\
vc.log(r.failed); vc.log(p.pathPoints.length); vc.log(p.closed);"
),
);
assert_eq!(out, vec![json!(1), json!(0), json!(true)]);
}
#[test]
fn point_edits_are_written_before_the_next_other_member_reads() {
let (mut s, a, _) = doc();
@@ -2049,7 +2345,7 @@ fn bad_color_components_throw_and_change_nothing() {
("app.activeDocument.pathItems[0].fillColor = {typename: 'Foo'};", "color object"),
("app.activeDocument.pathItems[0].fillColor = 5;", "color object"),
("app.activeDocument.pathItems[0].fillColor = new GradientColor();", "not available yet"),
("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "not available yet"),
("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"),
] {
let e = failure(&mut s, source);
assert!(e.contains(part), "{source}: {e}");
@@ -2500,6 +2796,23 @@ fn path_changes_refuse_paths_on_a_locked_artboard() {
assert_ne!(art(&s), before);
}
/// An empty path in a group on a locked artboard refuses `closed = true`, and keeps allowing an
/// assignment of the value it has.
#[test]
fn closing_an_empty_path_refuses_one_on_a_locked_artboard() {
let (mut s, a, _) = doc();
let empty = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap());
s.execute("object.group", &json!({"ids": [a.0, empty.0]})).unwrap();
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
let pick = "var d = app.activeDocument, p; for (var i = 0; i < d.pathItems.length; i++) { if (d.pathItems[i].pathPoints.length == 0) p = d.pathItems[i]; }";
log(&mut s, &format!("{pick} p.closed = false;"));
let e = failure(&mut s, &format!("{pick} p.closed = true;"));
assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", empty.0)), "{e}");
assert_eq!(log(&mut s, &format!("{pick} vc.log(p.closed);")), vec![json!(false)]);
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
assert_eq!(log(&mut s, &format!("{pick} p.closed = true; vc.log(p.closed);")), vec![json!(true)]);
}
fn is_guide(s: &Session, id: NodeId) -> bool {
matches!(node(s, id).kind, NodeKind::Path { guide: true, .. })
}
@@ -0,0 +1,842 @@
//! The script object model's swatches, color groups, spots, symbols, graphic styles and brushes.
use serde_json::{Value, json};
use crate::*;
fn run(s: &mut Session, source: &str) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
r["log"].as_array().cloned().unwrap_or_default()
}
/// The message of the run's failure.
fn failure(s: &mut Session, source: &str) -> String {
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
}
/// A 400 × 300 pt RGB document with one rectangle.
fn doc() -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
s.execute("select.none", &json!({})).unwrap();
(s, a)
}
fn undo_steps(s: &Session) -> usize {
s.active().unwrap().history.undo.len()
}
fn swatch_names(s: &mut Session) -> Vec<String> {
let l = s.execute("swatch.list", &json!({})).unwrap();
l["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap().to_string()).collect()
}
/// The document's resources, to show that a failed call changed nothing.
fn resources(s: &Session) -> String {
let d = &s.active().unwrap().doc;
format!("{:?}{:?}{:?}{:?}{:?}", *d.swatches, *d.swatch_groups, *d.graphic_styles, d.symbols, d.layers)
}
#[test]
fn swatches_are_live_and_keep_reserved_entries() {
let (mut s, _) = doc();
let names = swatch_names(&mut s);
let out = log(
&mut s,
"var w = app.activeDocument.swatches; vc.log(w.length); vc.log(w.typename); vc.log(w.parent.typename);\
vc.log(w[0].name); vc.log(w[1].name); vc.log(w[1].typename); vc.log(w[w.length] === undefined);\
vc.log(w.getByName('Black').color.typename); try { w.getSelected(); } catch (e) { vc.log(e.message); }",
);
assert_eq!(
out,
vec![
json!(names.len()),
json!("Swatches"),
json!("Document"),
json!(names[0]),
json!("[Registration]"),
json!("Swatch"),
json!(true),
json!("RGBColor"),
json!("Swatches.getSelected is not available yet")
]
);
let out = log(
&mut s,
"var w = app.activeDocument.swatches, n = w.add(); n.name = 'Script Ink';\
var c = new RGBColor(); c.red = 10; c.green = 20; c.blue = 30; n.color = c;\
vc.log(w.getByName('Script Ink').color.green); vc.log(n.name);",
);
assert_eq!(out, vec![json!(20), json!("Script Ink")]);
assert!(swatch_names(&mut s).contains(&"Script Ink".to_string()));
let steps = undo_steps(&s);
log(&mut s, "app.activeDocument.swatches.removeAll();");
assert_eq!(undo_steps(&s), steps + 1);
let left = swatch_names(&mut s);
assert_eq!(left, vec![names[0].clone(), "[Registration]".to_string()]);
for script in ["app.activeDocument.swatches[1].name = 'R';", "app.activeDocument.swatches[0].remove();"] {
assert!(failure(&mut s, script).contains("is built in"), "{script}");
}
let steps = undo_steps(&s);
log(&mut s, "app.activeDocument.swatches.removeAll();");
assert_eq!(undo_steps(&s), steps, "a removeAll with nothing to remove records no step");
}
#[test]
fn swatches_add_saves_a_gradient_fill_as_a_gradient() {
let (mut s, _) = doc();
let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
s.execute("paint.setFill", &json!({"gradient": ramp})).unwrap();
let out = log(&mut s, "vc.log(app.activeDocument.swatches.add().color.typename);");
assert_eq!(out, vec![json!("GradientColor")]);
}
#[test]
fn resource_objects_go_stale_after_remove_and_follow_renames() {
let (mut s, _) = doc();
let out = log(
&mut s,
"var w = app.activeDocument.swatches.getByName('Black'); w.name = 'Ink'; vc.log(w.name);\
var again = app.activeDocument.swatches.getByName('Ink'); vc.log(again.name);",
);
assert_eq!(out, vec![json!("Ink"), json!("Ink")]);
let cases = [
("var w = app.activeDocument.swatches.getByName('Ink'); w.remove(); w.name;", "Stale Swatch"),
("var w = app.activeDocument.swatches.getByName('White'); w.remove(); w.typename;", "Stale Swatch"),
("var w = app.activeDocument.swatches.getByName('White'); vc.run('swatch.delete', {name: 'White'}); w.color;", "Stale Swatch"),
(
"var g = app.activeDocument.graphicStyles.getByName('Default Graphic Style'); vc.run('graphicStyle.rename', {name: g.name, to: 'X'}); g.name;",
"Stale GraphicStyle",
),
("var w = app.activeDocument.swatches.getByName('Red'); w.remove(); app.activeDocument.swatches.add().name = 'Red'; w.name;", "Stale Swatch"),
(
"var w = app.activeDocument.swatches.getByName('Lime'); vc.run('swatch.delete', {name: 'Lime'}); vc.run('swatch.new', {name: 'Lime', color: '#00ff00'}); w.name;",
"Stale Swatch",
),
(
"var w = app.activeDocument.swatches.getByName('Yellow'); vc.run('command.batch', {commands: [\
{command: 'swatch.delete', params: {name: 'Yellow'}}, {command: 'swatch.new', params: {name: 'Yellow', color: '#ffff00'}}]}); w.name;",
"Stale Swatch",
),
(
"var g = app.activeDocument.graphicStyles.getByName('Default Graphic Style'); vc.run('command.batch', {commands: [\
{command: 'graphicStyle.rename', params: {name: g.name, to: 'X'}}, {command: 'graphicStyle.rename', params: {name: 'X', to: g.name}}]}); g.name;",
"Stale GraphicStyle",
),
];
for (script, message) in cases {
let e = failure(&mut s, script);
assert!(e.contains(message), "{script}: {e}");
}
}
#[test]
fn a_spot_object_goes_stale_when_a_batch_makes_its_swatch_process_and_back() {
let (mut s, _) = doc();
s.execute("swatch.new", &json!({"name": "Ink", "color": "#204080", "spot": true})).unwrap();
let toggle = "vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'Ink', spot: false}},\
{command: 'swatch.edit', params: {name: 'Ink', spot: true}}]});";
let e = failure(&mut s, &format!("var p = app.activeDocument.spots.getByName('Ink'); {toggle} p.name;"));
assert!(e.contains("Stale Spot"), "{e}");
let out = log(&mut s, &format!("var w = app.activeDocument.swatches.getByName('Ink'); {toggle} vc.log(w.name);"));
assert_eq!(out, vec![json!("Ink")], "the swatch object stays live");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn action_steps_finalize_resource_removals_before_the_next_step() {
let (mut s, _) = doc();
s.execute("dataset.new", &json!({"name": "Row"})).unwrap();
let actions = json!([{"set": "Set", "name": "Replace", "steps": [
{"command": "action.batch", "params": {"source": "datasets", "commands": [
{"command": "swatch.delete", "params": {"name": "Yellow"}},
{"command": "swatch.new", "params": {"name": "Yellow", "color": "#ffff00"}}
]}},
{"command": "select.none"}
]}]);
let source = "var w = app.activeDocument.swatches.getByName('Yellow'); app.doScript('Replace', 'Set');\
try { vc.log(w.name); } catch (e) { vc.log(e.message); }\
vc.log(app.activeDocument.swatches.getByName('Yellow').name);";
let r = s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions})).unwrap();
let out = r["log"].as_array().unwrap();
assert!(out[0].as_str().unwrap().contains("Stale Swatch"), "{r}");
assert_eq!(out[1], json!("Yellow"));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_failed_dataset_row_keeps_restored_resource_handles_live() {
for change in ["{command: 'swatch.delete', params: {name: 'Yellow'}}", "{command: 'swatch.edit', params: {name: 'Yellow', newName: 'Ink'}}"] {
let (mut s, _) = doc();
s.execute("dataset.new", &json!({"name": "Row"})).unwrap();
let out = log(
&mut s,
&format!(
"var w = app.activeDocument.swatches.getByName('Yellow');\
var r = vc.run('action.batch', {{source: 'datasets', commands: [{change},\
{{command: 'swatch.edit', params: {{name: 'No such swatch', color: '#000000'}}}}]}});\
vc.log(r.failed); vc.log(w.name);"
),
);
assert_eq!(out, vec![json!(1), json!("Yellow")], "{change}");
}
}
#[test]
fn listing_spots_is_charged_for_every_swatch_it_looks_at() {
let (mut s, _) = doc();
for i in 0..300 {
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
}
let source = "var d = app.activeDocument; for (var i = 0; i < 100; i++) d.spots.length;";
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
let r = run(&mut s, source);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = r.map(|r| panic!("100 listings of 300 process swatches ran: {r}")).unwrap_err().to_string();
assert!(e.contains("passed more data"), "{e}");
}
#[test]
fn a_batch_that_fails_is_charged_for_the_swatches_its_steps_compared() {
let (mut s, _) = doc();
for i in 0..1000 {
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
}
let source = "var d = app.activeDocument, w = d.swatches.getByName('P0'); for (var i = 0; i < 30; i++) {\
try { vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'P1', color: i % 2 ? '#112233' : '#445566'}},\
{command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}]}); } catch (e) {} }";
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
let r = run(&mut s, source);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = r.map(|r| panic!("30 failed batches over 1000 swatches ran: {r}")).unwrap_err().to_string();
assert!(e.contains("passed more data"), "{e}");
let source = "var w = app.activeDocument.swatches.getByName('P0');\
vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'P1', color: '#112233'}},\
{command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}]});";
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(3000)));
let r = run(&mut s, source);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = r.map(|r| panic!("a failed batch over 1000 swatches ran: {r}")).unwrap_err().to_string();
assert!(e.contains("passed more data"), "the scan budget error takes precedence over the missing swatch: {e}");
}
#[test]
fn the_artwork_symbol_class_leaves_the_built_in_symbol() {
let (mut s, _) = doc();
// A `.js` file runs as ECMAScript 2015, which has the built-in `Symbol`.
let dir = std::env::temp_dir().join(format!("vc-script-symbol-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("t.js");
std::fs::write(
&path,
"var d = app.activeDocument, m = d.symbols.add(d.pathItems[0]);\
vc.log(typeof Symbol()); vc.log(typeof Symbol.iterator); vc.log(m.typename); vc.log(d.symbols.getByName(m.name).typename);",
)
.unwrap();
let r = s.execute("script.run", &json!({"path": path.to_string_lossy()}));
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(r.unwrap()["log"], json!(["symbol", "symbol", "Symbol", "Symbol"]));
}
#[test]
fn hostile_names_and_values_are_refused_without_change() {
let (mut s, _) = doc();
let before = resources(&s);
let steps = undo_steps(&s);
let long = "x".repeat(1025);
let cases = [
("app.activeDocument.swatches.getByName('Black').name = 'a\\u0007b';".to_string(), "control characters"),
("app.activeDocument.swatches.getByName('Black').name = ' ';".to_string(), "cannot be empty"),
(format!("app.activeDocument.swatches.getByName('Black').name = '{long}';"), "longer than 1024 bytes"),
("app.activeDocument.swatches.getByName('Black').name = 7;".to_string(), "must be a string"),
("app.activeDocument.swatches.getByName('Black').name = 'White';".to_string(), "already exists"),
("var d = app.activeDocument, p = d.spots.add(); p.name = 'Black';".to_string(), "a swatch or color group named Black already exists"),
(
"var d = app.activeDocument; d.swatchGroups.add().name = 'Mine'; d.swatches.getByName('White').name = 'Mine';".to_string(),
"a swatch or color group named Mine already exists",
),
("app.activeDocument.swatches.getByName('Black').color = new NoColor();".to_string(), "cannot be NoColor"),
("app.activeDocument.swatches.getByName('Black').color = {typename: 'RGBColor', red: 300};".to_string(), "from 0 to 255"),
("app.activeDocument.swatches.getByName('nope');".to_string(), "Not found"),
("app.activeDocument.swatches.index({});".to_string(), "name or an index"),
("app.activeDocument.symbols.add(app.activeDocument);".to_string(), "not a page item"),
("app.activeDocument.symbols.add(app.activeDocument.pageItems[0], 'SymbolRegistrationPoint.NOPE');".to_string(), "SymbolRegistrationPoint"),
("app.activeDocument.symbolItems.add(app.activeDocument.swatches[2]);".to_string(), "not a Symbol"),
("app.activeDocument.graphicStyles[0].applyTo([app.activeDocument.pageItems[0]]);".to_string(), "one page item"),
];
for (script, message) in &cases {
let e = failure(&mut s, script);
assert!(e.contains(message), "{script}: {e}");
}
assert_eq!(resources(&s), before);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn spots_keep_their_kind_and_their_color_space() {
let (mut s, _) = doc();
let out = log(
&mut s,
"var d = app.activeDocument, p = d.spots.add(); p.name = 'Pea'; p.colorType = ColorModel.SPOT;\
var c = new RGBColor(); c.red = 90; c.green = 200; c.blue = 30; p.color = c;\
vc.log(d.spots.length); vc.log(p.typename); vc.log(p.colorType); vc.log(p.spotKind); vc.log(p.getInternalColor());\
var w = d.swatches.getByName('Pea').color; vc.log(w.typename); vc.log(w.spot.name); vc.log(w.tint);",
);
assert_eq!(
out,
vec![
json!(2),
json!("Spot"),
json!("ColorModel.SPOT"),
json!("SpotColorKind.SPOTRGB"),
json!([90, 200, 30]),
json!("SpotColor"),
json!("Pea"),
json!(100)
]
);
let before = resources(&s);
for (script, message) in [
("var p = app.activeDocument.spots.getByName('Pea'); p.color = new GrayColor();", "must be an RGBColor, a CMYKColor or a LabColor"),
("app.activeDocument.spots.getByName('Pea').colorType = ColorModel.PROCESS;", "stays a spot color"),
("app.activeDocument.spots.getByName('Pea').colorType = 3;", "ColorModel value"),
] {
let e = failure(&mut s, script);
assert!(e.contains(message), "{script}: {e}");
}
assert_eq!(resources(&s), before);
log(&mut s, "var p = app.activeDocument.spots.getByName('Pea'); var l = new LabColor(); l.l = 50; p.color = l;");
assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots.getByName('Pea').spotKind);"), vec![json!("SpotColorKind.SPOTLAB")]);
log(&mut s, "app.activeDocument.spots.removeAll();");
assert!(!swatch_names(&mut s).contains(&"Pea".to_string()));
}
#[test]
fn a_spot_takes_a_cmyk_color_in_an_rgb_document() {
let (mut s, _) = doc();
let out = log(
&mut s,
"var p = app.activeDocument.spots.add(); p.name = 'Pea'; var c = new CMYKColor(); c.cyan = 35; c.yellow = 50; p.color = c;\
var q = app.activeDocument.spots.getByName('Pea'); vc.log(q.color.typename); vc.log([q.color.cyan, q.color.yellow]); vc.log(q.spotKind);",
);
assert_eq!(out, vec![json!("CMYKColor"), json!([35, 50]), json!("SpotColorKind.SPOTCMYK")]);
let d = &s.active().unwrap().doc;
let cmyk =
matches!(d.swatch("Pea").map(|w| &w.paint), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. }));
assert!(cmyk, "the spot keeps its CMYK color in the RGB document");
let steps = undo_steps(&s);
log(&mut s, "var p = app.activeDocument.spots.getByName('Pea'); p.color = p.color;");
assert_eq!(undo_steps(&s), steps, "assigning the color the spot has records no step");
}
#[test]
fn a_spot_keeps_an_rgb_color_in_a_cmyk_document() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 80, "m": 40, "y": 0, "k": 0}, "spot": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Leaf", "color": {"c": 60, "m": 0, "y": 90, "k": 10}})).unwrap();
let rgb = |s: &Session, name: &str| {
matches!(
s.active().unwrap().doc.swatch(name).map(|w| &w.paint),
Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. })
)
};
let assign = |what: &str| format!("var c = new RGBColor(); c.red = 200; c.green = 60; c.blue = 20; {what}.color = c;");
for (what, name) in [("app.activeDocument.spots.getByName('Pea')", "Pea"), ("app.activeDocument.swatches.getByName('Ink')", "Ink")] {
if name == "Pea" {
log(&mut s, "app.activeDocument.spots.add().name = 'Pea';");
}
let out = log(&mut s, &format!("{} var q = app.activeDocument.spots.getByName('{name}').color; vc.log([q.typename, q.red]);", assign(what)));
assert_eq!(out, vec![json!(["RGBColor", 200])], "{what}");
assert!(rgb(&s, name), "{name} keeps its RGB color in the CMYK document");
let kind = log(&mut s, &format!("vc.log(app.activeDocument.spots.getByName('{name}').spotKind);"));
assert_eq!(kind, vec![json!("SpotColorKind.SPOTRGB")], "{name}");
let steps = undo_steps(&s);
log(&mut s, &assign(what));
assert_eq!(undo_steps(&s), steps, "assigning {name} the color it has records no step");
}
let what = "app.activeDocument.swatches.getByName('Leaf')";
let paint = |s: &Session| s.active().unwrap().doc.swatch("Leaf").map(|w| w.paint.clone());
let before = paint(&s);
let steps = undo_steps(&s);
log(&mut s, &assign(what));
assert!(!rgb(&s, "Leaf"), "a process swatch stores the RGB color as CMYK in the CMYK document");
assert_ne!(paint(&s), before, "the first assignment changes Leaf");
assert!(
matches!(paint(&s), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. })),
"Leaf holds a CMYK color"
);
assert_eq!(undo_steps(&s), steps + 1, "the first assignment records one step");
let steps = undo_steps(&s);
log(&mut s, &assign(what));
assert_eq!(undo_steps(&s), steps, "assigning Leaf the RGB color it was given records no step");
}
#[test]
fn a_process_swatch_that_kept_an_rgb_color_takes_it_back_without_a_step() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
s.execute("swatch.new", &json!({"name": "Sky", "color": "#3080c0", "keepModel": true})).unwrap();
let paint = |s: &Session| s.active().unwrap().doc.swatch("Sky").map(|w| w.paint.clone());
let rgb = matches!(paint(&s), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }));
assert!(rgb, "the process swatch holds an RGB color in the CMYK document");
let before = paint(&s);
let steps = undo_steps(&s);
log(&mut s, "var w = app.activeDocument.swatches.getByName('Sky'); w.color = w.color;");
assert_eq!(paint(&s), before, "the swatch keeps its RGB color");
assert_eq!(undo_steps(&s), steps, "assigning the swatch its own color records no step");
}
#[test]
fn spots_list_registration_and_keep_it() {
let (mut s, _) = doc();
let out = log(
&mut s,
"var d = app.activeDocument, r = d.spots.getByName('[Registration]'); vc.log(r.typename); vc.log(r.colorType);\
vc.log(d.spots[0].name); vc.log(d.spots.length); r.colorType = ColorModel.REGISTRATION;\
vc.log(d.swatches.getByName('[Registration]').color.spot.name);",
);
assert_eq!(out, vec![json!("Spot"), json!("ColorModel.REGISTRATION"), json!("[Registration]"), json!(1), json!("[Registration]")]);
let before = resources(&s);
let steps = undo_steps(&s);
for script in [
"app.activeDocument.spots.getByName('[Registration]').name = 'R';",
"app.activeDocument.spots.getByName('[Registration]').remove();",
"app.activeDocument.spots.getByName('[Registration]').color = new CMYKColor();",
"app.activeDocument.spots.getByName('[Registration]').colorType = ColorModel.SPOT;",
] {
assert!(failure(&mut s, script).contains("is built in"), "{script}");
}
log(&mut s, "app.activeDocument.spots.removeAll();");
assert_eq!(resources(&s), before);
assert_eq!(undo_steps(&s), steps, "removeAll with only Registration left records no step");
assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots.length);"), vec![json!(1)]);
}
#[test]
fn a_tint_of_a_spot_reads_as_that_spot_at_the_tint() {
let (mut s, _) = doc();
s.execute("swatch.new", &json!({"name": "Ink", "color": "#204080", "spot": true})).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
let tint = s.execute("swatch.new", &json!({"tint": 40})).unwrap()["name"].as_str().unwrap().to_string();
let out = log(
&mut s,
&format!("var c = app.activeDocument.swatches.getByName('{tint}').color; vc.log(c.typename); vc.log(c.spot.name); vc.log(c.tint);"),
);
assert_eq!(out, vec![json!("SpotColor"), json!("Ink"), json!(40)]);
}
#[test]
fn spots_add_converts_the_fill_to_the_document_color_space() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000", "keepModel": true})).unwrap();
let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. });
assert!(rgb, "the current fill is RGB in a CMYK document");
let out = log(&mut s, "var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename);");
assert_eq!(out, vec![json!("SpotColorKind.SPOTCMYK"), json!("CMYKColor")]);
}
#[test]
fn spots_add_converts_a_cmyk_or_gray_fill_in_an_rgb_document() {
for fill in [json!({"c": 0, "m": 100, "y": 100, "k": 0}), json!({"gray": 40})] {
let (mut s, _) = doc();
s.execute("paint.setFill", &json!({"color": fill})).unwrap();
let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. });
assert!(!rgb, "the current fill {fill} is not RGB in an RGB document");
let out = log(
&mut s,
"var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename); p.color = p.color; vc.log(p.name == '');",
);
assert_eq!(out, vec![json!("SpotColorKind.SPOTRGB"), json!("RGBColor"), json!(false)], "{fill}");
}
}
#[test]
fn color_groups_hold_solid_swatches_only() {
let (mut s, _) = doc();
s.execute(
"swatch.new",
&json!({"name": "Ramp", "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
)
.unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, g = d.swatchGroups.add(); g.name = 'Script Group';\
g.addSwatch(d.swatches.getByName('Black')); g.addSwatch(d.swatches.getByName('Black'));\
var all = g.getAllSwatches(); vc.log(all.length); vc.log(all[0].name); vc.log(d.swatchGroups.getByName('Script Group').typename);",
);
assert_eq!(out, vec![json!(1), json!("Black"), json!("SwatchGroup")]);
let before = resources(&s);
for (script, message) in [
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches.getByName('Ramp'));", "solid colors only"),
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches[0]);", "is built in"),
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSpot(d.swatches.getByName('Black'));", "not a Spot"),
] {
let e = failure(&mut s, script);
assert!(e.contains(message), "{script}: {e}");
}
assert_eq!(resources(&s), before);
let out = log(
&mut s,
"var d = app.activeDocument, g = d.swatchGroups.getByName('Script Group'), b = g.getAllSwatches()[0];\
g.removeAll(); vc.log(g.getAllSwatches().length); try { b.name; } catch (e) { vc.log(String(e.message)); }\
g.remove(); try { g.name; } catch (e) { vc.log(String(e.message)); }",
);
assert_eq!(out, vec![json!(0), json!("Stale Swatch"), json!("Stale SwatchGroup")]);
}
#[test]
fn symbols_add_keeps_the_source_and_instances_follow_their_symbol() {
let (mut s, a) = doc();
let out = log(
&mut s,
"var d = app.activeDocument, n = d.pageItems.length, sym = d.symbols.add(d.pageItems[0], SymbolRegistrationPoint.SYMBOLTOPLEFTPOINT);\
vc.log(d.pageItems.length === n); vc.log(sym.typename); vc.log(d.symbols.length);\
sym.name = 'Mark'; var copy = sym.duplicate(); vc.log(copy.name);\
var inst = d.symbolItems.add(sym); vc.log(inst.typename); vc.log(inst.symbol.name); vc.log(d.symbolItems.length);\
inst.symbol = copy; vc.log(inst.symbol.name); vc.log(d.selection.length === 0);",
);
assert_eq!(
out,
vec![
json!(true),
json!("Symbol"),
json!(1),
json!("Mark copy"),
json!("SymbolItem"),
json!("Mark"),
json!(1),
json!("Mark copy"),
json!(true)
]
);
assert!(s.active().unwrap().doc.node(a).is_some(), "the source art stays");
let l = s.execute("symbol.list", &json!({})).unwrap();
assert_eq!(l["symbols"][0]["registration"], json!(0));
let steps = undo_steps(&s);
log(&mut s, "var d = app.activeDocument; d.symbolItems.removeAll(); vc.log(d.symbols.length);");
assert_eq!(undo_steps(&s), steps + 1);
let out = log(
&mut s,
"var d = app.activeDocument, sym = d.symbols[0]; d.symbols.removeAll(); vc.log(d.symbols.length); try { sym.name; } catch (e) { vc.log(String(e.message)); }",
);
assert_eq!(out, vec![json!(0), json!("Stale Symbol")]);
}
#[test]
fn resources_refuse_objects_of_another_document() {
let (mut s, _) = doc();
log(&mut s, "var d = app.activeDocument; d.symbols.add(d.pageItems[0]);");
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let before = resources(&s);
// `app.documents` lists the active document, the new one, first: the document with the symbol
// is `documents[1]`.
for script in [
"var a = app.documents[1], b = app.documents[0]; b.symbolItems.add(a.symbols[0]);",
"var a = app.documents[1], b = app.documents[0]; a.graphicStyles[0].applyTo(b.pageItems[0]);",
"var a = app.documents[1], b = app.documents[0]; b.swatchGroups.add().addSwatch(a.swatches.getByName('Black'));",
"var a = app.documents[1], b = app.documents[0]; a.symbols.add(b.pageItems[0]);",
] {
let e = failure(&mut s, script);
assert!(e.contains("Cross-document"), "{script}: {e}");
}
assert_eq!(resources(&s), before);
}
#[test]
fn graphic_styles_apply_replaces_and_merge_adds() {
let (mut s, a) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Red"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let b = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
s.execute("select.none", &json!({})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, g = d.graphicStyles.getByName('Red'); vc.log(g.typename); vc.log(d.graphicStyles.typename);\
g.applyTo(d.pageItems[0]);",
);
assert_eq!(out, vec![json!("GraphicStyle"), json!("GraphicStyles")]);
let id = s.active().unwrap().doc.graphic_style("Red").unwrap().id;
let n = s.active().unwrap().doc.node(b).unwrap().clone();
assert_eq!(n.extras().graphic_style, Some(id));
let fills = n.appearance.items.len();
log(&mut s, "var d = app.activeDocument; d.graphicStyles.getByName('Red').mergeTo(d.pageItems[0]);");
let n = s.active().unwrap().doc.node(b).unwrap().clone();
assert!(n.appearance.items.len() > fills, "merge adds the style's rows");
assert_eq!(n.extras().graphic_style, None);
let before = resources(&s);
for script in [
"app.activeDocument.graphicStyles.getByName('Default Graphic Style').name = 'Plain';",
"app.activeDocument.graphicStyles.getByName('Default Graphic Style').remove();",
] {
let e = failure(&mut s, script);
assert!(e.contains("is built in"), "{script}: {e}");
}
assert_eq!(resources(&s), before);
log(&mut s, "app.activeDocument.graphicStyles.removeAll();");
let left: Vec<String> = s.active().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect();
assert_eq!(left, vec![crate::doc::DEFAULT_GRAPHIC_STYLE.to_string()]);
}
#[test]
fn brushes_apply_to_paths_only_and_once() {
let (mut s, a) = doc();
s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let first = s.execute("brush.list", &json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string();
let out = log(
&mut s,
"var b = app.activeDocument.brushes; vc.log(b.typename); vc.log(b[0].typename); vc.log(b[0].name); vc.log(b.removeAll === undefined);",
);
assert_eq!(out, vec![json!("Brushes"), json!("Brush"), json!(first), json!(true)]);
let before = resources(&s);
let e = failure(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pageItems[0]);");
assert!(e.contains("PathItem only"), "{e}");
assert_eq!(resources(&s), before);
log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);");
let st = s.active().unwrap().doc.node(a).unwrap().appearance.stroke().cloned().unwrap();
assert_eq!(st.brush.as_deref(), Some(first.as_str()));
let steps = undo_steps(&s);
log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);");
assert_eq!(undo_steps(&s), steps, "applying the brush a path already draws runs no command");
}
#[test]
fn brushes_refuse_guides_clipping_paths_and_compound_members() {
let (mut s, a) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("view.guides.make", &json!({})).unwrap();
let (m1, m2) = (rect(&mut s, 100.0, 20.0, 30.0, 40.0), rect(&mut s, 150.0, 20.0, 30.0, 40.0));
s.execute("select.set", &json!({"ids": [m1.0, m2.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let (c1, c2) = (rect(&mut s, 200.0, 20.0, 30.0, 40.0), rect(&mut s, 210.0, 30.0, 10.0, 10.0));
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let pick = |test: &str| {
format!(
"var d = app.activeDocument, p = null; for (var i = 0; i < d.pathItems.length; i++) {{ var q = d.pathItems[i]; if ({test}) p = q; }}\
d.brushes[0].applyTo(p);"
)
};
for test in ["q.guides", "q.clipping", "q.parent.typename == 'CompoundPathItem'"] {
let before = resources(&s);
let steps = undo_steps(&s);
let e = failure(&mut s, &pick(test));
assert!(e.contains("does not apply to a guide"), "{test}: {e}");
assert_eq!((resources(&s), undo_steps(&s)), (before, steps), "{test}");
}
}
#[test]
fn several_resource_edits_are_one_undo_step_and_a_failure_puts_them_back() {
let (mut s, _) = doc();
let steps = undo_steps(&s);
log(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'One'; d.spots.add().name = 'Two'; d.swatchGroups.add().name = 'Three';");
assert_eq!(undo_steps(&s), steps + 1);
let before = resources(&s);
let e = failure(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'Four'; d.swatches.removeAll(); throw new Error('stop');");
assert!(e.contains("stop"), "{e}");
assert_eq!(resources(&s), before);
}
#[test]
fn a_swatch_that_undo_removed_stays_stale_when_a_new_swatch_takes_its_name() {
for make in ["vc.run('swatch.new', {name: n, color: '#ff0000'}); vc.log(true);", "vc.log(d.swatches.add().name == n);"] {
let (mut s, _) = doc();
let out = log(
&mut s,
&format!(
"var d = app.activeDocument, k = d.swatches.length, w = d.swatches.add(), n = w.name; app.undo();\
vc.log(d.swatches.length == k); {make}\
try {{ vc.log(w.name); }} catch (e) {{ vc.log(e.message); }}"
),
);
assert_eq!(out[..2], [json!(true), json!(true)], "{make}: undo removes the swatch, and the new one takes its name");
assert!(out[2].as_str().is_some_and(|m| m.contains("Stale Swatch")), "{make}: {out:?}");
}
}
#[test]
fn swatch_objects_made_before_a_revert_are_stale() {
let (mut s, _) = doc();
let path = std::env::temp_dir().join(format!("vc-resources-revert-{}.vectorcraft", std::process::id()));
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, w = d.swatches.getByName('Black');\
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
try { vc.log(w.name); } catch (e) { vc.log(e.message); }\
var again = app.activeDocument.swatches.getByName('Black'); vc.log(again.name); vc.log(again === w);",
);
let _ = std::fs::remove_file(&path);
assert!(out[0].as_str().is_some_and(|m| m.contains("Stale Swatch")), "{out:?}");
assert_eq!(out[1..], [json!("Black"), json!(false)], "a swatch object made after the revert names the reverted swatch");
}
#[test]
fn brushes_refuse_paths_in_a_compound_shape_at_any_depth() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
let (m1, m2, m3) = (rect(&mut s, 10.0, 20.0, 30.0, 40.0), rect(&mut s, 30.0, 30.0, 30.0, 40.0), rect(&mut s, 50.0, 40.0, 30.0, 40.0));
s.execute("select.set", &json!({"ids": [m1.0, m2.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g, m3.0]})).unwrap();
s.execute("object.compoundShape.make", &json!({"mode": "add"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let before = resources(&s);
let steps = undo_steps(&s);
let out = log(
&mut s,
"var d = app.activeDocument, n = d.pathItems.length, e = [];\
for (var i = 0; i < n; i++) { try { d.brushes[0].applyTo(d.pathItems[i]); e.push('applied'); }\
catch (x) { e.push(x.message.indexOf('compound shape') >= 0); } }\
vc.log(n); vc.log(e);",
);
assert_eq!(out, vec![json!(3), json!([true, true, true])], "the grouped members and the direct member are refused");
assert_eq!((resources(&s), undo_steps(&s)), (before, steps));
}
#[test]
fn reading_every_swatch_by_index_lists_the_swatches_once() {
let (mut s, _) = doc();
for i in 0..1000 {
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
}
let source =
"var w = app.activeDocument.swatches, n = w.length, read = 0; for (var i = 0; i < n; i++) if (w[i]) read++; vc.log(read == n && n > 1000);";
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(200_000)));
let r = run(&mut s, source);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let r = r.unwrap_or_else(|e| panic!("reading 1000 swatches by index: {e}"));
assert_eq!(r["log"], json!([true]));
let source = "var w = app.activeDocument.swatches, n = w.length; for (var i = 0; i < n; i++) { w[i]; app.activeDocument.swatches.add(); }";
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(200_000)));
let r = run(&mut s, source);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = r.map(|r| panic!("reading after each change listed the swatches once: {r}")).unwrap_err().to_string();
assert!(e.contains("passed more data"), "a read after a change lists the swatches again and is charged: {e}");
}
#[test]
fn remove_all_is_charged_for_the_records_it_looks_at() {
let (mut s, _) = doc();
for i in 0..1000 {
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
}
let source = "var d = app.activeDocument; for (var i = 0; i < 100; i++) d.spots.removeAll();";
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
let r = run(&mut s, source);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = r.map(|r| panic!("100 removeAll() calls over 1000 process swatches ran: {r}")).unwrap_err().to_string();
assert!(e.contains("passed more data"), "{e}");
let colors: Vec<String> = (0..500).map(|i| format!("#{:06x}", i * 31)).collect();
s.execute("swatch.newGroup", &json!({"name": "Many", "colors": colors})).unwrap();
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(3000)));
let r = run(&mut s, "app.activeDocument.swatchGroups.removeAll();");
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = r.map(|r| panic!("removing a group of 500 swatches ran: {r}")).unwrap_err().to_string();
assert!(e.contains("passed more data"), "the group's swatches are charged: {e}");
}
#[test]
fn a_new_resource_past_the_object_limit_is_not_kept() {
let (mut s, a) = doc();
let before = resources(&s);
let steps = undo_steps(&s);
crate::script::TEST_MAX_SLOTS.with(|m| m.set(Some(1)));
let out = run(
&mut s,
"var d = app.activeDocument, p = d.pathItems[0], k = d.swatches[0], out = [];\
var calls = [function () { d.swatches.add(); }, function () { d.spots.add(); }, function () { d.swatchGroups.add(); },\
function () { d.symbols.add(p); }];\
for (var i = 0; i < calls.length; i++) { try { calls[i](); out.push('made'); } catch (e) { out.push(e.message.indexOf('at most 1 ') >= 0); } }\
vc.log(out);",
);
crate::script::TEST_MAX_SLOTS.with(|m| m.set(None));
assert_eq!(out.unwrap()["log"], json!([[true, true, true, true]]));
assert_eq!((resources(&s), undo_steps(&s)), (before, steps), "no new resource is kept");
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "keepArt": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
crate::script::TEST_MAX_SLOTS.with(|m| m.set(Some(1)));
let out = run(
&mut s,
"var d = app.activeDocument, m = d.symbols.getByName('Mark');\
try { m.duplicate(); vc.log('made'); } catch (e) { vc.log(e.message.indexOf('at most 1 ') >= 0); } vc.log(d.symbols.length);",
);
crate::script::TEST_MAX_SLOTS.with(|m| m.set(None));
assert_eq!(out.unwrap()["log"], json!([true, 1]), "the duplicate is not kept");
}
#[test]
fn a_placed_symbol_instance_with_a_large_id_keeps_its_id() {
let (mut s, a) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "keepArt": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let big = (1u64 << 53) + 1;
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
let out = log(&mut s, "var d = app.activeDocument, i = d.symbolItems.add(d.symbols.getByName('Mark')); i.name = 'big'; vc.log(i.name);");
assert_eq!(out, vec![json!("big")]);
assert_eq!(s.active().unwrap().doc.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big"));
}
#[test]
fn editing_swatch_colors_is_charged_for_the_swatches_each_change_compares() {
let (mut s, _) = doc();
for i in 0..1000 {
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
}
let source = "var w = app.activeDocument.swatches.getByName('P0'), a = new RGBColor(), b = new RGBColor(); b.red = 200;\
for (var i = 0; i < 30; i++) w.color = i % 2 ? a : b;";
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
let r = run(&mut s, source);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = r.map(|r| panic!("30 swatch color edits over 1000 swatches ran: {r}")).unwrap_err().to_string();
assert!(e.contains("passed more data"), "{e}");
}
#[test]
fn a_swatch_color_converts_through_the_profiles_of_its_own_document() {
use vectorcraft_color::{Color, cms};
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
s.execute("edit.assignProfile", &json!({"cmyk": cms::FOGRA51_CMYK})).unwrap();
let rgb = Color::rgb(51.0 / 255.0, 128.0 / 255.0, 204.0 / 255.0);
let own = {
let c = crate::cmd::colormgmt::doc_cms(&s.active().unwrap().doc);
c.convert(&rgb, cms::Model::Cmyk, c.settings().intent)
};
let working = {
let c = cms::working();
c.convert(&rgb, cms::Model::Cmyk, c.settings().intent)
};
assert_ne!(own, working, "the assigned profile converts the color differently");
s.execute("swatch.new", &json!({"name": "Sky", "color": serde_json::to_value(working).unwrap()})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
log(
&mut s,
"var w = null; for (var i = 0; i < app.documents.length; i++) { try { w = app.documents[i].swatches.getByName('Sky'); } catch (e) {} }\
var c = new RGBColor(); c.red = 51; c.green = 128; c.blue = 204; w.color = c;",
);
let sky = s.documents().iter().find_map(|st| st.doc.swatch("Sky").map(|w| w.paint.clone()));
let Some(vectorcraft_color::Paint::Solid { color, .. }) = sky else { panic!("Sky is a solid color: {sky:?}") };
assert_ne!(color, working, "the swatch takes the color its own document's profile gives");
assert_eq!(color, own);
}
@@ -1526,3 +1526,28 @@ fn retraced_plugin_is_the_same_object_as_its_collection_handle() {
assert_eq!(out, vec![json!(true); 5]);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn loading_the_same_preset_in_bracket_form_does_not_trace_again() {
let base = folder("retrace-bracket-preset");
// Silhouettes then [Default] leaves the tracing with the stored name `[Default]`.
for (first, second) in [("Default", "[Default]"), ("Silhouettes', '[Default]", "Default"), ("Silhouettes", "[silhouettes]")] {
let (mut s, _) = session(&base, false);
let out = log(
&mut s,
&base,
&format!(
"var o = app.activeDocument.rasterItems[0].trace().tracing.tracingOptions, names = ['{first}'];\
for (var i = 0; i < names.length; i++) o.loadFromPreset(names[i]); vc.log(o.preset);"
),
);
assert_eq!(out, [json!(first.rsplit('\'').next().unwrap())], "{first}");
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
let steps = undo_steps(&s);
let out = log(&mut s, &base, &format!("vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.loadFromPreset('{second}'));"));
assert_eq!(out, [json!(true)], "{first} then {second}");
assert!(vectorcraft_format::save(&s.active().unwrap().doc, false) == before, "{first} then {second}: the document changed");
assert_eq!(undo_steps(&s), steps, "{first} then {second}");
}
let _ = std::fs::remove_dir_all(base);
}
+127 -56
View File
@@ -10,6 +10,34 @@ use crate::*;
const DENIED: &str = "Script file access denied";
#[test]
fn file_wrappers_report_encoder_warnings_without_changing_their_return_values() {
for method in ["exportFile", "saveAs", "exportForScreens"] {
let base = folder(&format!("encoder-warnings-{method}"));
let mut s = session(&base);
s.execute("file.new", &json!({"width": 80, "height": 40})).unwrap();
crate::tests_menucmds::place_undecodable_png(&mut s);
let format = if method == "saveAs" { "pdf" } else { "png" };
let expected = s.execute("document.export", &json!({"format": format})).unwrap()["warnings"].clone();
let warnings = expected.as_array().unwrap();
assert!(!warnings.is_empty(), "the fixture must produce an encoder warning");
let dir = data_folder(&mut s, &base);
let path = quoted(&dir.join("output.png"));
let call = match method {
"exportFile" => format!("d.exportFile(new File({path}), ExportType.PNG24)"),
"saveAs" => format!("d.saveAs(new File({}))", quoted(&dir.join("output.pdf"))),
_ => format!("d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG24)", quoted(&dir.join("screens"))),
};
let report =
run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument; var answer = {call}; vc.log(answer === undefined);")).unwrap();
assert_eq!(report["log"], json!([true]), "{method}: {report}");
let lines = report["console"]["lines"].as_array().unwrap();
for warning in warnings.iter().filter_map(Value::as_str) {
assert!(lines.iter().filter_map(Value::as_str).any(|line| line.contains(warning)), "{method}: {warning}: {lines:?}");
}
}
}
#[cfg(unix)]
#[test]
fn save_as_uses_the_scripts_extension_before_following_a_link() {
@@ -221,7 +249,6 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
assert!(dir.join("e.JPG").is_file() && !dir.join("e.JPG.jpg").exists(), "a name that ends with the extension keeps it");
assert!(std::fs::read(dir.join("f.svgz")).unwrap().starts_with(&[0x1f, 0x8b]));
assert_eq!(s.documents().len(), 2);
let _ = std::fs::remove_dir_all(base);
}
#[test]
@@ -380,7 +407,7 @@ fn save_as_uses_the_link_name_extension_for_the_encoder() {
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg"))));
assert!(std::fs::read_to_string(&target).unwrap().contains("<svg"));
assert_eq!(s.active().unwrap().format, "svg");
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -403,7 +430,7 @@ fn save_as_template_preserves_the_document_file_and_saved_state() {
assert_eq!(out, json!([[true, true], [true, false]]));
assert!(dir.join("clean.vctemplate").is_file());
assert!(dir.join("dirty.vctemplate").is_file());
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[cfg(unix)]
@@ -419,7 +446,7 @@ fn open_uses_the_requested_symlink_filename() {
let out = logged(&mut s, &base, &format!("Folder.userData; var d = app.open(new File({})); vc.log([d.name, d.fullName.name]);", quoted(&link)));
assert_eq!(out, json!([["drawing.svg", "drawing.svg"]]));
assert_eq!(s.active().unwrap().format, "svg");
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// Without options, a save or export writes what an untouched new options object of its class gives.
@@ -456,7 +483,6 @@ fn omitted_options_are_a_new_options_objects_defaults() {
let pdf = std::fs::read(dir.join(name)).unwrap();
assert!(pdf.starts_with(b"%PDF-1.4"), "{name}: PDFCompatibility.ACROBAT5 is PDF 1.4, {:?}", String::from_utf8_lossy(&pdf[..8]));
}
let _ = std::fs::remove_dir_all(base);
}
/// White, the default `matteColor` of `ExportOptionsPNG24` and `ExportOptionsJPEG`, is accepted, and
@@ -531,7 +557,7 @@ fn script_file_commands_refuse_non_utf8_resolved_paths() {
let target = dir.join(std::ffi::OsString::from_vec(b"target-\xff.vectorcraft".to_vec()));
// A file system that refuses such a name has nothing to refuse.
if std::fs::write(&target, &bytes).is_err() {
let _ = std::fs::remove_dir_all(base);
drop(base);
return;
}
let link = dir.join("alias.vectorcraft");
@@ -553,7 +579,7 @@ fn script_file_commands_refuse_non_utf8_resolved_paths() {
assert_eq!(std::fs::read(&target).unwrap(), bytes);
assert_eq!(std::fs::read(&lossy).unwrap(), bytes);
}
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// Every enumeration an option keeps its default in is defined: the default member is accepted, and
@@ -578,7 +604,6 @@ fn kept_enum_options_accept_their_default_member() {
("PDFSaveOptions", "pDFChangesAllowed", "PDFChangesAllowedEnum.CHANGE128ANYCHANGES", "PDFChangesAllowedEnum.CHANGE40NONE"),
("PDFSaveOptions", "pDFXStandard", "PDFXStandard.PDFXNONE", "PDFXStandard.PDFX42007"),
("PDFSaveOptions", "trimMarkWeight", "PDFTrimMarkWeight.TRIMMARKWEIGHT0125", "PDFTrimMarkWeight.TRIMMARKWEIGHT05"),
("ExportOptionsSVG", "cssProperties", "SVGCSSPropertyLocation.STYLEATTRIBUTES", "SVGCSSPropertyLocation.ENTITIES"),
("ExportOptionsSVG", "documentEncoding", "SVGDocumentEncoding.ASCII", "SVGDocumentEncoding.UTF8"),
("ExportOptionsSVG", "DTD", "SVGDTDVersion.SVG1_1", "SVGDTDVersion.SVGTINY1_2"),
("ExportOptionsSVG", "fontSubsetting", "SVGFontSubsetting.ALLGLYPHS", "SVGFontSubsetting.GLYPHSUSED"),
@@ -597,7 +622,7 @@ fn kept_enum_options_accept_their_default_member() {
let e = failure(&mut s, &base, &format!("Folder.userData; {}", call(other, format!("no{i}"))));
assert!(e.contains("is not available yet"), "{class}.{key} = {other}: {e}");
}
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// A raster export at 100% has one pixel per point, whatever the document's raster effects
@@ -624,7 +649,6 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() {
let image = image::open(dir.join(name)).unwrap();
assert_eq!((image.width(), image.height()), (200, 100), "{name}");
}
let _ = std::fs::remove_dir_all(base);
}
/// The value of the DXF header variable `name` (the group after its name).
@@ -757,7 +781,6 @@ fn a_pdf_preset_keeps_its_settings_unless_an_option_changes() {
let pdf = std::fs::read(dir.join(name)).unwrap();
assert!(pdf.starts_with(version), "{name}: {:?}", String::from_utf8_lossy(&pdf[..8]));
}
let _ = std::fs::remove_dir_all(base);
}
/// A save that writes several files, such as an EPS with a file per artboard, writes none of them
@@ -792,7 +815,6 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() {
let e = failure(&mut s, &base, &save);
assert!(e.contains("not a file"), "{e}");
assert!(!central.exists(), "the central file is not written when a folder is where an artboard's file goes");
let _ = std::fs::remove_dir_all(base);
}
/// An export that writes several files writes none of them when a folder is where one of them goes.
@@ -863,7 +885,6 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() {
#[allow(clippy::permissions_set_readonly_false)]
perms.set_readonly(false);
std::fs::set_permissions(&refused, perms).unwrap();
let _ = std::fs::remove_dir_all(base);
}
/// Every path goes through the script's file grants, as a `File` opened for reading or writing.
@@ -897,8 +918,8 @@ fn save_as_export_file_and_open_refuse_paths_outside_the_grants() {
}
let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({kept}));"));
assert!(e.contains("Script file is read-only"), "{e}");
let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&dir)));
assert!(e.contains("Script file") && !e.contains("ran"), "a folder is not saved over: {e}");
let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir)));
assert!(e.contains("Script file is not a regular file"), "a folder is not saved over: {e}");
assert_eq!(std::fs::read_to_string(dir.join("kept.svg")).unwrap(), "kept");
assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), "{}");
assert!(!base.join("outside/x.svg").exists() && !base.join("outside/x.svg.png").exists());
@@ -909,7 +930,6 @@ fn save_as_export_file_and_open_refuse_paths_outside_the_grants() {
#[allow(clippy::permissions_set_readonly_false)]
perms.set_readonly(false);
std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap();
let _ = std::fs::remove_dir_all(base);
}
/// The file of an open document is not written or read through a script method unless the
@@ -927,7 +947,6 @@ fn an_open_documents_file_is_not_saved_over_without_a_grant() {
let e = failure(&mut s, &base, &format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&path)));
assert!(e.contains(DENIED), "{e}");
assert_eq!(std::fs::read(&path).unwrap(), before);
let _ = std::fs::remove_dir_all(base);
}
/// A save or export to a file a `File` object holds open for writing throws, so the object's bytes
@@ -953,7 +972,6 @@ fn a_file_open_for_writing_is_not_saved_over() {
assert_eq!(std::fs::read_to_string(dir.join(name)).unwrap(), "pending", "{name}: the File's own bytes");
assert_eq!(s.active().unwrap().path, None, "{name}: the document's file is unchanged");
}
let _ = std::fs::remove_dir_all(base);
}
/// A file `open` reads besides the one it names, here an SVG's linked image, is read only where
@@ -994,7 +1012,6 @@ fn open_reads_linked_files_only_where_the_script_may() {
std::fs::copy(dir.join("page.svg"), dir.join("copy.svg")).unwrap();
s.execute("document.open", &json!({"path": dir.join("copy.svg").to_string_lossy()})).unwrap();
assert!(ims(&s).is_empty() && kinds(&s).iter().any(|k| k.starts_with("Path")), "{:?}", kinds(&s));
let _ = std::fs::remove_dir_all(base);
}
/// A file an open document links to is read by `open` only where the script may read, too.
@@ -1053,7 +1070,6 @@ fn an_svg_export_writes_nothing_when_one_of_its_files_is_refused() {
#[allow(clippy::permissions_set_readonly_false)]
perms.set_readonly(false);
std::fs::set_permissions(&image, perms).unwrap();
let _ = std::fs::remove_dir_all(base);
}
/// An export does not write a file it writes besides the one named, here an SVG's image, while a
@@ -1085,7 +1101,6 @@ fn an_svg_export_does_not_write_an_image_a_file_holds_open() {
assert!(log[0].as_str().unwrap().contains(DENIED), "{log}");
assert!(!svg.exists(), "the SVG is not written when its image may not be");
assert_eq!(std::fs::read_to_string(&image).unwrap(), "pending", "the File's own bytes");
let _ = std::fs::remove_dir_all(base);
}
/// A link inside a granted folder that leads out of it is followed and refused.
@@ -1108,7 +1123,6 @@ fn a_link_out_of_the_granted_folder_is_refused() {
assert!(e.contains(DENIED), "{e}");
assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1, "nothing is written outside");
assert_eq!(s.documents().len(), 1);
let _ = std::fs::remove_dir_all(base);
}
/// Without options, `saveAs` takes the format from the path the script names, not from the file a
@@ -1126,7 +1140,6 @@ fn save_as_takes_the_format_of_the_named_path_through_a_link() {
let written = std::fs::read(dir.join("target.pdf")).unwrap();
assert!(!written.starts_with(b"%PDF"), "the named .svg path writes SVG, not PDF");
assert!(String::from_utf8_lossy(&written).contains("<svg"), "an SVG file");
let _ = std::fs::remove_dir_all(base);
}
/// Bad arguments throw before anything is written or opened.
@@ -1252,7 +1265,6 @@ fn bad_arguments_are_refused_with_an_error() {
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written");
assert_eq!(s.documents().len(), 1);
assert_eq!(s.active().unwrap().path, None);
let _ = std::fs::remove_dir_all(base);
}
/// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a
@@ -1289,7 +1301,6 @@ fn a_forged_file_is_refused() {
assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1);
assert_eq!(s.documents().len(), 1, "nothing is opened");
assert_eq!(s.active().unwrap().path, None);
let _ = std::fs::remove_dir_all(base);
}
/// A document from an earlier run is stale, and saving it throws.
@@ -1303,7 +1314,6 @@ fn a_stale_document_is_not_saved() {
let e = failure(&mut s, &base, &format!("#targetengine keep\nFolder.userData; held.saveAs(new File({}));", quoted(&dir.join("x.svg"))));
assert!(e.contains("Stale document"), "{e}");
assert!(!dir.join("x.svg").exists());
let _ = std::fs::remove_dir_all(base);
}
/// `open` applies the page and crop box of its options to a PDF.
@@ -1312,9 +1322,13 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
let base = folder("pdf");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap();
// Page 2 is 200 × 400 pt with a 180 × 380 pt crop box, unlike page 1's 100 × 100 pt.
let mut second = vectorcraft_testkit::pdf::PdfPage::new(200.0, 400.0, "0 0 1 rg 20 30 40 50 re f");
second.crop = Some([10.0, 10.0, 190.0, 390.0]);
let pages = [vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"), second];
let pdf = dir.join("two.pdf");
s.execute("file.saveAs", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap();
std::fs::write(&pdf, vectorcraft_testkit::pdf::pdf(&pages, None)).unwrap();
let size = |s: &Session| s.active().map(|st| st.doc.artboards.iter().map(|a| (a.rect.width(), a.rect.height())).collect::<Vec<_>>());
let out = logged(
&mut s,
&base,
@@ -1325,6 +1339,9 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
),
);
assert_eq!(out, json!(["DocumentColorSpace.CMYK"]));
assert_eq!(size(&s), Some(vec![(200.0, 400.0)]), "page 2 on its media box");
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 2}});", quoted(&pdf)));
assert_eq!(size(&s), Some(vec![(180.0, 380.0)]), "page 2 on its crop box, the default");
let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 3}});", quoted(&pdf)));
assert!(!e.is_empty(), "a page the file does not have");
assert_eq!(s.documents().len(), 2);
@@ -1334,7 +1351,65 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
logged(&mut s, &base, &undefined);
assert_eq!(s.documents().len(), 3);
assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages");
let _ = std::fs::remove_dir_all(base);
}
/// An SVG export to a name that ends with `.svgz` writes a compressed file at that name, without
/// options and with `compressed` false; a name without the suffix stays a plain SVG. `cssProperties`
/// picks how the style properties are written.
#[test]
fn export_file_keeps_an_svgz_name_compressed_and_applies_css_properties() {
let base = folder("svgz");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let d = quoted(&dir);
logged(
&mut s,
&base,
&format!(
"Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 20, 20);\n\
vc.run('shape.rectangle', {{x: 2, y: 2, width: 10, height: 10}});\n\
d.exportFile(new File(dir + '/logo.svgz'), ExportType.SVG);\n\
var o = new ExportOptionsSVG(); o.compressed = false;\n\
d.exportFile(new File(dir + '/plain.SVGZ'), ExportType.SVG, o);\n\
d.exportFile(new File(dir + '/page'), ExportType.SVG);\n\
var a = new ExportOptionsSVG(); a.cssProperties = SVGCSSPropertyLocation.PRESENTATIONATTRIBUTES;\n\
d.exportFile(new File(dir + '/attributes'), ExportType.SVG, a);"
),
);
for name in ["logo.svgz", "plain.SVGZ"] {
assert!(std::fs::read(dir.join(name)).unwrap().starts_with(&[0x1f, 0x8b]), "{name}");
assert!(!dir.join(format!("{name}.svg")).exists(), "{name}");
}
let page = std::fs::read_to_string(dir.join("page.svg")).unwrap();
assert!(page.contains("style=\"fill:"), "a new options object's cssProperties is STYLEATTRIBUTES: {page}");
let attributes = std::fs::read_to_string(dir.join("attributes.svg")).unwrap();
assert!(attributes.contains(" fill=\"") && !attributes.contains("style=\"fill:"), "{attributes}");
}
/// A path whose real path has no UTF-8 form, through a link to a folder of such a name, is refused
/// before anything is written there.
#[cfg(target_os = "linux")]
#[test]
fn a_real_path_that_is_not_unicode_is_refused() {
use std::os::unix::ffi::OsStrExt;
let base = folder("not-unicode");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let odd = dir.join(std::ffi::OsStr::from_bytes(b"odd-\xff"));
std::fs::create_dir_all(&odd).unwrap();
std::os::unix::fs::symlink(&odd, dir.join("link")).unwrap();
let link = quoted(&dir.join("link"));
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
for call in [
format!("app.activeDocument.exportFile(new File({link} + '/out.png'), ExportType.PNG24)"),
format!("app.activeDocument.saveAs(new File({link} + '/out.svg'))"),
format!("app.activeDocument.exportForScreens(new Folder({link}), ExportForScreensType.SE_PNG24)"),
] {
let e = failure(&mut s, &base, &format!("Folder.userData; {call};"));
assert!(e.contains("Script file path is not valid UTF-8"), "{call}: {e}");
}
assert_eq!(std::fs::read_dir(&odd).unwrap().count(), 0, "nothing is written in the folder");
}
#[test]
@@ -1356,7 +1431,7 @@ fn crop_only_options_apply_to_an_editable_pdf() {
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pDFCropToBox: PDFBoxType.PDFMEDIABOX}});", quoted(&pdf)));
let cropped = s.active().unwrap().doc.artboards[0].rect;
assert!(cropped.width() > original.width() && cropped.height() > original.height());
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1388,7 +1463,7 @@ fn explicit_crop_box_opens_the_bleed_outside_an_editable_files_trim_box() {
assert_eq!((default.width(), default.height()), (trim.width(), trim.height()), "{extension}");
assert!(crop.width() > trim.width() && crop.height() > trim.height(), "{extension}");
}
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1404,7 +1479,7 @@ fn script_document_open_rejects_files_over_the_read_limit() {
let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file)));
assert!(e.contains(crate::cmd::fileio::SCRIPT_OPEN_TOO_LARGE), "{e}");
assert_eq!(s.documents().len(), count);
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1432,7 +1507,7 @@ fn pdf_open_options_reject_other_detected_formats() {
s.execute("file.saveCopy", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap();
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 1}});", quoted(&pdf)));
assert_eq!(s.documents().len(), count + 1);
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1451,7 +1526,7 @@ fn script_document_open_treats_null_pdf_options_as_omitted() {
assert_eq!(s.active().unwrap().doc.artboards.len(), 1);
}
}
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1484,7 +1559,7 @@ fn explicit_null_options_do_not_save_export_open_or_close() {
assert_ne!(std::fs::read(&file).unwrap(), original);
logged(&mut s, &base, "Folder.userData; app.activeDocument.close(undefined);");
assert!(s.documents().is_empty());
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// `fullName` and `path` name the document's file and folder once it has one, `saved` follows its
@@ -1531,7 +1606,6 @@ fn full_name_path_saved_and_close_follow_the_documents_file() {
assert!(s.documents().is_empty());
let e = failure(&mut s, &base, "app.documents.add(); app.activeDocument.close('DONOTSAVECHANGES');");
assert!(e.contains("SaveOptions"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// A document whose file was saved under a relative name is in the working folder the file was
@@ -1599,7 +1673,6 @@ fn a_document_without_unsaved_changes_closes_with_any_save_options() {
),
);
assert_eq!(out, json!([[true, true, 2], 1, 0]));
let _ = std::fs::remove_dir_all(base);
}
/// `close(SaveOptions.SAVECHANGES)` saves in the format the document was last saved in, not the
@@ -1615,10 +1688,14 @@ fn closing_with_save_changes_keeps_the_documents_format() {
&base,
&format!(
"Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());\n\
vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);"
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());"
),
);
logged(
&mut s,
&base,
"Folder.userData; var d = app.activeDocument; vc.run('shape.rectangle', {x: 20, y: 20, width: 5, height: 5}); d.close(SaveOptions.SAVECHANGES);",
);
let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default();
assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format");
let pdf = vectorcraft_pdf::import(&bytes).unwrap();
@@ -1630,7 +1707,6 @@ fn closing_with_save_changes_keeps_the_documents_format() {
assert!(sizes.iter().any(|&s| near(s, (5.0, 5.0))), "the file holds the rectangle drawn after the first save: {sizes:?}");
assert!(sizes.iter().any(|&s| near(s, (50.0, 20.0))), "and the first one: {sizes:?}");
assert!(s.documents().is_empty());
let _ = std::fs::remove_dir_all(base);
}
/// `close(SaveOptions.SAVECHANGES)` on a document whose last save named some of its artboards
@@ -1661,7 +1737,7 @@ fn closing_with_save_changes_refuses_a_save_of_some_artboards() {
}
assert_eq!(drawn, 0, "the file is left as the first save wrote it");
assert!(s.active().unwrap().is_dirty(), "the change is still unsaved");
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1705,7 +1781,7 @@ fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() {
assert!(e.contains("some of its artboards"), "{e}");
assert_eq!(s.documents().len(), 1);
assert_eq!(std::fs::read(dir.join("grown.pdf")).unwrap(), before);
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// The artboard check of `close(SaveOptions.SAVECHANGES)` follows the file the save writes: a PDF
@@ -1741,7 +1817,7 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() {
);
assert!(s.documents().is_empty(), "the .ai file keeps every artboard, so it closes");
assert_ne!(std::fs::read(&ai).unwrap(), before, "and the change is saved");
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// A native file and a `.ai` file saved without separate artboard files, and an SVG file that
@@ -1777,7 +1853,7 @@ fn closing_with_save_changes_saves_files_that_keep_every_artboard() {
s.execute("document.open", &json!({"path": file.to_string_lossy()})).unwrap();
assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "{name} keeps both artboards");
}
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1814,7 +1890,7 @@ fn closing_with_save_changes_keeps_all_eps_artboards_for_subset_ranges() {
assert!(s.active().unwrap().doc.node_count() > nodes, "{range}");
logged(&mut s, &base, "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);");
}
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1853,7 +1929,7 @@ fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() {
logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);");
}
}
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1873,7 +1949,7 @@ fn document_path_reflection_describes_folders_and_unsaved_strings() {
),
);
assert_eq!(out, json!([["Folder|string", true], ["Folder|string", "Folder"], [true, dir.to_string_lossy()]]));
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// Setting `Document.saved` records the document's saved state without saving it: `true` lets
@@ -1902,7 +1978,6 @@ fn setting_saved_records_the_saved_state() {
assert_eq!(out[5][1], json!(1), "a document set as unsaved stays open");
assert!(out[6].as_str().unwrap().contains("true or false"), "{}", out[6]);
assert!(s.active().unwrap().is_dirty(), "the state stays after the run");
let _ = std::fs::remove_dir_all(base);
}
/// The warnings of a save go to the console after the method's name.
@@ -1915,7 +1990,7 @@ fn save_as_writes_its_warnings_to_the_console() {
let r = run(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("two.svg")))).unwrap();
let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default();
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ")), "{lines:?}");
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// A point change that waits to be written counts as an unsaved change for `saved` and `close`.
@@ -1939,7 +2014,7 @@ fn waiting_point_changes_count_as_unsaved_changes() {
assert_eq!(out[0], json!(false), "a waiting point change is unsaved");
assert!(out[1][0].as_str().unwrap().contains("unsaved changes"), "{}", out[1]);
assert_eq!(out[1][1], json!(1), "close() keeps the document open");
let _ = std::fs::remove_dir_all(base);
drop(base);
}
#[test]
@@ -1957,7 +2032,7 @@ fn unchanged_saved_assignments_do_not_record_commands() {
assert_eq!(out, json!([true, false, true]));
let changes: Vec<_> = s.journal.iter().filter(|(id, _)| id == "document.setSaved").map(|(_, p)| p["saved"].clone()).collect();
assert_eq!(changes, [json!(false), json!(true)]);
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// With automation read roots that leave out the document's file, `fullName` and `path` throw
@@ -1994,7 +2069,6 @@ fn full_name_and_path_leave_out_a_file_outside_the_read_roots() {
assert!(e.contains(DENIED) && !e.contains("outside"), "SAVECHANGES does not write a file the script may not: {e}");
assert_eq!(std::fs::read(&file).unwrap(), before, "the file is left as it was");
assert_eq!(s.documents().len(), 1, "the document stays open");
let _ = std::fs::remove_dir_all(base);
}
#[test]
@@ -2023,7 +2097,7 @@ fn implicit_multifile_save_redacts_preflight_refusals_before_writing() {
let explicit =
crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({"path": path.to_string_lossy()}))).unwrap_err().to_string();
assert!(explicit.contains(path.to_string_lossy().as_ref()), "{explicit}");
let _ = std::fs::remove_dir_all(base);
drop(base);
}
/// A `pDFPreset` in square brackets names the built-in preset of the name inside them, and a name
@@ -2058,7 +2132,6 @@ fn a_bracketed_pdf_preset_names_the_built_in_preset() {
);
assert!(e.contains("unknown PDF preset"), "{bad}: {e}");
}
let _ = std::fs::remove_dir_all(base);
}
/// A number given as `artboardRange` is read as `String(number)` reads it.
@@ -2081,7 +2154,6 @@ fn a_number_artboard_range_names_that_artboard() {
assert_eq!(pdf.artboards.len(), 1, "one page");
let r = pdf.artboards[0].rect;
assert!((r.width() - 60.0).abs() < 0.01 && (r.height() - 80.0).abs() < 0.01, "the second artboard: {r:?}");
let _ = std::fs::remove_dir_all(base);
}
/// With `saveMultipleArtboards`, a `.ai` or EPS save also writes a file for each artboard of
@@ -2143,5 +2215,4 @@ fn save_multiple_artboards_writes_a_file_per_artboard() {
assert!(e.contains("range"), "{bad}: {e}");
}
assert!(!dir.join("aioff/b.ai").exists(), "a bad range writes nothing");
let _ = std::fs::remove_dir_all(base);
}
+482
View File
@@ -0,0 +1,482 @@
//! Exporting for screens from a script: `Document.exportForScreens`, `ExportForScreensItemToExport`,
//! the option classes and the file grants the folder goes through.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::*;
const DENIED: &str = "Script file access denied";
#[test]
fn screen_width_and_height_reject_effective_scales_outside_the_encoder_range() {
for mode in ["SCALEBYWIDTH", "SCALEBYHEIGHT"] {
for pixels in [65.0, 0.001] {
let base = vectorcraft_testkit::TempDir::new("screen-size-limit");
std::fs::create_dir_all(base.join("main")).unwrap();
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let output = dir.join("scaled");
let source = format!(
"Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 1, 1); \
var o = new ExportForScreensOptionsPNG24(); \
o.scaleType = ExportForScreensScaleType.{mode}; o.scaleTypeValue = {pixels}; \
d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG24, o);",
quoted(&output)
);
let error = failure(&mut s, &base, &source);
assert!(error.contains("scale"), "{mode}: {pixels}: {error}");
assert!(!output.exists(), "{mode}: {pixels}");
}
}
}
#[test]
fn screen_png8_without_matting_keeps_transparent_edge_colors() {
let base = vectorcraft_testkit::TempDir::new("screen-png8-unmatted");
std::fs::create_dir_all(base.join("main")).unwrap();
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
logged(
&mut s,
&base,
&format!(
"Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 20, 20); \
vc.run('shape.rectangle', {{x: 0, y: 0, width: 20, height: 20}}); \
vc.run('paint.setFill', {{color: '#ff0000'}}); d.pageItems[0].opacity = 50; \
var o = new ExportForScreensOptionsPNG8(); o.matte = false; \
d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG8, o);",
quoted(&dir.join("png8"))
),
);
let output = dir.join("png8");
let files = names(&output);
assert_eq!(files.len(), 1);
let rgba = image::open(output.join(&files[0])).unwrap().to_rgba8();
let pixel = rgba.get_pixel(5, 5).0;
assert!(pixel[0] > 200 && pixel[1] < 20 && pixel[2] < 20, "{pixel:?}");
}
#[test]
fn linked_screen_svg_images_are_rejected_before_output_is_created() {
let base = vectorcraft_testkit::TempDir::new("screen-svg-linked");
std::fs::create_dir_all(base.join("main")).unwrap();
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
let output = dir.join("svg");
let error = failure(
&mut s,
&base,
&format!(
"Folder.userData; var o = new ExportForScreensOptionsWebOptimizedSVG(); \
o.rasterImageLocation = RasterImageLocation.LINK; \
app.activeDocument.exportForScreens(new Folder({}), ExportForScreensType.SE_SVG, o);",
quoted(&output)
),
);
assert!(error.contains("not available yet"), "{error}");
assert!(!output.exists());
}
/// A volume root the person picked is a folder the export may write into: the export goes on to
/// the command, which here refuses an asset the document does not have, and writes nothing.
#[cfg(unix)]
#[test]
fn a_picked_volume_root_is_a_folder_to_export_into() {
let base = vectorcraft_testkit::TempDir::new("screen-root");
std::fs::create_dir_all(base.join("main")).unwrap();
let mut s = session(&base);
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.script_frames = true;
let main = base.join("main/main.jsx");
let script = "var p = Folder.selectDialog('p'); var i = new ExportForScreensItemToExport(); i.artboards = ''; i.assets = [987654321];\n\
try { app.activeDocument.exportForScreens(p, ExportForScreensType.SE_PNG24, undefined, i); vc.log('exported'); } catch (e) { vc.log(String(e)); }";
std::fs::write(&main, script).unwrap();
assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true);
let mut picked = false;
let mut report = None;
for _ in 0..10_000 {
if !picked && s.script_picker().is_some() {
picked = true;
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec!["/".into()], always: false }));
}
if let Some(r) = s.script_pump() {
report = Some(r.unwrap());
break;
}
}
let report = report.unwrap_or_else(|| panic!("the run neither ended nor waited"));
assert!(picked, "{report}");
let said = report["log"][0].as_str().unwrap_or_default().to_string();
assert!(!said.contains(DENIED) && !said.contains("exported") && said.contains("987654321"), "{said}");
}
/// A fresh folder for test `name`, by its real path, with `main` for the script.
fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-screens-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
std::fs::create_dir_all(base.join("outside")).unwrap();
std::fs::canonicalize(&base).unwrap()
}
/// A session whose scripts keep their data folders in `base/settings/Script Data`.
fn session(base: &Path) -> Session {
let mut s = Session::new();
s.attach_script_data(base.join("settings/Script Data"));
s
}
/// Runs `main/main.jsx` in `base` with the text `text` in `s`.
fn run(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
let main = base.join("main/main.jsx");
std::fs::write(&main, text.as_bytes()).unwrap();
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
}
fn logged(s: &mut Session, base: &Path, text: &str) -> Value {
run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone()
}
fn failure(s: &mut Session, base: &Path, text: &str) -> String {
run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string()
}
/// The script's data folder, where it may write.
fn data_folder(s: &mut Session, base: &Path) -> PathBuf {
PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap())
}
fn quoted(p: &Path) -> String {
serde_json::to_string(&p.to_string_lossy()).unwrap()
}
/// The names of the files in `dir`, sorted; none when it is not there.
fn names(dir: &Path) -> Vec<String> {
let mut v: Vec<String> =
std::fs::read_dir(dir).map(|r| r.map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default();
v.sort();
v
}
/// A script that makes a document of two artboards with a rectangle on the first, in `dir`.
fn two_artboards(dir: &Path) -> String {
format!(
"Folder.userData; var dir = {}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n",
quoted(dir)
)
}
/// Each export type writes its format into the folder, a file per artboard of the item's range, at
/// the size the options' scale type gives.
#[test]
fn export_for_screens_writes_each_format_into_the_folder() {
let base = folder("formats");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let out = logged(
&mut s,
&base,
&format!(
"{}var one = new ExportForScreensItemToExport(); one.artboards = '1';\n\
vc.log([one.typename, new ExportForScreensItemToExport().artboards, new ExportForScreensOptionsJPEG().scaleTypeValue]);\n\
d.exportForScreens(new Folder(dir + '/jpg'), ExportForScreensType.SE_JPEG100, undefined, one);\n\
var p = new ExportForScreensOptionsPNG24(); p.scaleType = ExportForScreensScaleType.SCALEBYFACTOR; p.scaleTypeValue = 2;\n\
d.exportForScreens(new Folder(dir + '/png'), ExportForScreensType.SE_PNG24, p);\n\
var w = new ExportForScreensOptionsPNG8(); w.scaleType = ExportForScreensScaleType.SCALEBYWIDTH; w.scaleTypeValue = 50;\n\
d.exportForScreens(new Folder(dir + '/png8'), ExportForScreensType.SE_PNG8, w, one);\n\
var r = new ExportForScreensOptionsJPEG(); r.scaleType = ExportForScreensScaleType.SCALEBYRESOLUTION; r.scaleTypeValue = 144;\n\
d.exportForScreens(new Folder(dir + '/ppi'), ExportForScreensType.SE_JPEG20, r, one);\n\
d.exportForScreens(new Folder(dir + '/svg'), ExportForScreensType.SE_SVG);\n\
d.exportForScreens(new Folder(dir + '/pdf'), ExportForScreensType.SE_PDF, new ExportForScreensPDFOptions(), one);",
two_artboards(&dir)
),
);
assert_eq!(out[0], json!(["ExportForScreensItemToExport", "all", 1]));
let size = |sub: &str| {
let files = names(&dir.join(sub));
let image = image::open(dir.join(sub).join(&files[0])).unwrap();
(files, image.width(), image.height())
};
let (jpg, w, h) = size("jpg");
assert!(jpg.len() == 1 && jpg[0].ends_with(".jpg"), "one artboard: {jpg:?}");
assert_eq!((w, h), (200, 100), "a pixel per point at 1x");
let (png, w, h) = size("png");
assert!(png.len() == 2 && png.iter().all(|n| n.ends_with("@2x.png")), "both artboards at 2x: {png:?}");
assert_eq!((w, h), (400, 200), "{png:?}");
let (png8, w, h) = size("png8");
assert_eq!(png8.len(), 1, "{png8:?}");
assert_eq!((w, h), (50, 25), "50 pixels wide, in proportion");
let (_, w, h) = size("ppi");
assert_eq!((w, h), (400, 200), "144 ppi is two pixels per point");
let svg = names(&dir.join("svg"));
assert!(svg.len() == 2 && svg.iter().all(|n| n.ends_with(".svg")), "{svg:?}");
let pdf = names(&dir.join("pdf"));
assert_eq!(pdf.len(), 1, "{pdf:?}");
assert!(std::fs::read(dir.join("pdf").join(&pdf[0])).unwrap().starts_with(b"%PDF"));
assert_eq!(s.active().unwrap().path, None, "the export leaves the document's file as it is");
let _ = std::fs::remove_dir_all(base);
}
/// Without options, an export writes what an untouched new options object of its class gives.
#[test]
fn omitted_options_are_a_new_options_objects_defaults() {
let base = folder("defaults");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let types = [
("SE_JPEG80", "ExportForScreensOptionsJPEG"),
("SE_PNG24", "ExportForScreensOptionsPNG24"),
("SE_PNG8", "ExportForScreensOptionsPNG8"),
("SE_SVG", "ExportForScreensOptionsWebOptimizedSVG"),
];
let calls: String = types
.iter()
.map(|(t, c)| {
format!(
"d.exportForScreens(new Folder(dir + '/{t}-a'), ExportForScreensType.{t});\n\
d.exportForScreens(new Folder(dir + '/{t}-b'), ExportForScreensType.{t}, new {c}());\n"
)
})
.collect();
logged(&mut s, &base, &format!("{}{calls}", two_artboards(&dir)));
for (t, _) in types {
let (a, b) = (dir.join(format!("{t}-a")), dir.join(format!("{t}-b")));
assert!(names(&a) == names(&b) && names(&a).len() == 2, "{t}: {:?} {:?}", names(&a), names(&b));
for n in names(&a) {
assert!(std::fs::read(a.join(&n)).unwrap() == std::fs::read(b.join(&n)).unwrap(), "{t}: {n} differs");
}
}
let _ = std::fs::remove_dir_all(base);
}
/// `itemToExport` exports the artboards of its range, its assets and the whole document, each that
/// it names; one that names nothing throws and writes nothing.
#[test]
fn item_to_export_picks_artboards_assets_and_the_document() {
let base = folder("items");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
logged(
&mut s,
&base,
&format!(
"{}var ids = vc.run('assets.add', {{name: 'Logo', multiple: false}}).assets;\n\
var a = new ExportForScreensItemToExport(); a.artboards = ''; a.assets = ids;\n\
d.exportForScreens(new Folder(dir + '/assets'), ExportForScreensType.SE_SVG, undefined, a);\n\
var whole = new ExportForScreensItemToExport(); whole.artboards = ''; whole.document = true;\n\
d.exportForScreens(new Folder(dir + '/document'), ExportForScreensType.SE_PNG24, undefined, whole);\n\
var both = new ExportForScreensItemToExport(); both.assets = ids; both.artboards = '2';\n\
d.exportForScreens(new Folder(dir + '/both'), ExportForScreensType.SE_SVG, undefined, both);",
two_artboards(&dir)
),
);
assert_eq!(names(&dir.join("assets")), ["Logo.svg"]);
let whole = names(&dir.join("document"));
assert_eq!(whole.len(), 1, "{whole:?}");
let image = image::open(dir.join("document").join(&whole[0])).unwrap();
let (w, h) = (image.width(), image.height());
assert!((50..60).contains(&w) && (20..30).contains(&h), "the bounds of the document's art, not an artboard: {w}x{h}");
let both = names(&dir.join("both"));
assert!(both.len() == 2 && both.contains(&"Logo.svg".to_string()), "artboard 2 and the asset: {both:?}");
for empty in ["''", "' '"] {
let e = failure(
&mut s,
&base,
&format!(
"Folder.userData; var i = new ExportForScreensItemToExport(); i.artboards = {empty};\n\
app.activeDocument.exportForScreens(new Folder({} + '/none'), ExportForScreensType.SE_PNG24, undefined, i);",
quoted(&dir)
),
);
assert!(e.contains("nothing to export"), "{empty}: {e}");
}
assert!(!dir.join("none").exists(), "an empty item writes nothing");
let _ = std::fs::remove_dir_all(base);
}
/// An asset named as an artboard of the item's range gets a file of its own: the artboard's file
/// keeps its name and the asset's is numbered, in place of writing over it.
#[test]
fn an_asset_named_as_an_artboard_does_not_overwrite_its_file() {
let base = folder("clash");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
logged(
&mut s,
&base,
&format!(
"{}vc.run('artboard.setProps', {{artboards: [{{index: 0, name: 'Logo'}}]}});\n\
var ids = vc.run('assets.add', {{name: 'Logo', multiple: false}}).assets;\n\
var both = new ExportForScreensItemToExport(); both.artboards = '1'; both.assets = ids;\n\
d.exportForScreens(new Folder(dir + '/both'), ExportForScreensType.SE_SVG, undefined, both);",
two_artboards(&dir)
),
);
assert_eq!(names(&dir.join("both")), ["Logo-2.svg", "Logo.svg"]);
let _ = std::fs::remove_dir_all(base);
}
/// The prefix comes before each file's name, and a path character in it does not make a folder or
/// reach out of the export folder.
#[test]
fn a_file_name_prefix_stays_in_the_folder() {
let base = folder("prefix");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
logged(
&mut s,
&base,
&format!(
"{}d.exportForScreens(new Folder(dir + '/out'), ExportForScreensType.SE_SVG, undefined, undefined, 'web-');\n\
d.exportForScreens(new Folder(dir + '/up'), ExportForScreensType.SE_SVG, undefined, undefined, '../x/');",
two_artboards(&dir)
),
);
let out = names(&dir.join("out"));
assert!(out.len() == 2 && out.iter().all(|n| n.starts_with("web-")), "{out:?}");
let up = names(&dir.join("up"));
assert!(up.len() == 2 && up.iter().all(|n| n.starts_with("..-x-")), "{up:?}");
let entries: Vec<_> = std::fs::read_dir(dir.join("up")).unwrap().map(|e| e.unwrap()).collect();
assert_eq!(entries.len(), 2, "{entries:?}");
assert!(entries.iter().all(|e| e.file_type().unwrap().is_file()), "no folder was made");
assert!(!dir.join("x").exists(), "nothing is written beside the folder");
let _ = std::fs::remove_dir_all(base);
}
/// The folder goes through the script's file grants: one outside them, and a file given as the
/// folder, throw before anything is written.
#[test]
fn an_unwritable_folder_is_refused() {
let base = folder("refused");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
std::fs::write(dir.join("taken"), "kept").unwrap();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let outside = quoted(&base.join("outside/screens"));
let e = failure(
&mut s,
&base,
&format!("Folder.userData; app.activeDocument.exportForScreens(new Folder({outside}), ExportForScreensType.SE_PNG24);"),
);
assert!(e.contains(DENIED), "{e}");
assert!(!base.join("outside/screens").exists());
let taken = quoted(&dir.join("taken"));
let e =
failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.exportForScreens(new Folder({taken}), ExportForScreensType.SE_PNG24);"));
assert!(e.contains(crate::script::files::NOT_FOLDER), "{e}");
assert_eq!(std::fs::read_to_string(dir.join("taken")).unwrap(), "kept");
assert_eq!(names(&base.join("outside")), Vec::<String>::new());
let _ = std::fs::remove_dir_all(base);
}
/// Only a `Folder` the `Folder` class made (or a `File`) names the folder: an object made from
/// `Folder.prototype` throws a `TypeError`, and a `Folder` whose hidden path property a script set
/// keeps its own path.
#[test]
fn a_forged_folder_is_refused() {
let base = folder("forged");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let (inside, outside) = (quoted(&dir.join("in")), quoted(&base.join("outside/x")));
let call = |f: &str| format!("Folder.userData; app.activeDocument.exportForScreens({f}, ExportForScreensType.SE_SVG);");
let made = format!("(function () {{ var f = Object.create(Folder.prototype); f.__vcPath = {inside}; return f; }})()");
let e = failure(&mut s, &base, &call(&made));
assert!(e.contains("TypeError") && e.contains("needs a Folder"), "{e}");
let moved = format!("(function () {{ var f = new Folder({outside}); f.__vcPath = {inside}; return f; }})()");
let e = failure(&mut s, &base, &call(&moved));
assert!(e.contains(DENIED), "{e}");
assert!(!dir.join("in").exists() && !base.join("outside/x").exists(), "nothing is written");
logged(&mut s, &base, &call(&format!("new File({inside})")));
assert_eq!(names(&dir.join("in")).len(), 1, "a File names the folder at its path");
let _ = std::fs::remove_dir_all(base);
}
/// Bad arguments throw before anything is written.
#[test]
fn bad_arguments_are_refused_with_an_error() {
let base = folder("bad");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let f = format!("new Folder({})", quoted(&dir.join("x")));
let e = "app.activeDocument.exportForScreens";
let long = "a".repeat(300);
let cases: Vec<(String, &str)> = vec![
(format!("{e}('x', ExportForScreensType.SE_PNG24);"), "needs a Folder"),
(format!("{e}({f}, 'SE_PNG24');"), "ExportForScreensType"),
(format!("{e}({f}, ExportType.PNG24);"), "ExportForScreensType"),
(format!("{e}({f}, ExportForScreensType.SE_PNG24, new ExportForScreensOptionsJPEG());"), "ExportForScreensOptionsPNG24"),
(
format!("{e}({f}, ExportForScreensType.SE_SVG, {{typename: 'ExportForScreensOptionsWebOptimizedSVG', svgMinified: true}});"),
"has no option svgMinified",
),
(format!("var o = new ExportForScreensOptionsJPEG(); o.progressiveScan = 6; {e}({f}, ExportForScreensType.SE_JPEG50, o);"), "from 3 to 5"),
(format!("var o = new ExportForScreensOptionsPNG8(); o.colorCount = 1; {e}({f}, ExportForScreensType.SE_PNG8, o);"), "from 2 to 256"),
(format!("var o = new ExportForScreensOptionsPNG8(); o.matteColor = 1; {e}({f}, ExportForScreensType.SE_PNG8, o);"), "not available yet"),
(format!("var o = new ExportForScreensOptionsPNG24(); o.scaleTypeValue = 0; {e}({f}, ExportForScreensType.SE_PNG24, o);"), "above 0"),
(
format!("var o = new ExportForScreensOptionsPNG24(); o.scaleTypeValue = 100; {e}({f}, ExportForScreensType.SE_PNG24, o);"),
"from 0.01 to 64",
),
(
format!(
"var o = new ExportForScreensOptionsPNG24(); o.scaleType = ExportForScreensScaleType.SCALEBYRESOLUTION; o.scaleTypeValue = 5000; {e}({f}, ExportForScreensType.SE_PNG24, o);"
),
"from 0.72 to 4608",
),
(
format!("var o = new ExportForScreensOptionsPNG24(); o.scaleType = 'SCALEBYWIDTH'; {e}({f}, ExportForScreensType.SE_PNG24, o);"),
"ExportForScreensScaleType",
),
(
format!("var o = new ExportForScreensOptionsPNG24(); o.antiAliasing = true; {e}({f}, ExportForScreensType.SE_PNG24, o);"),
"AntiAliasingMethod",
),
(
format!("var o = new ExportForScreensOptionsWebOptimizedSVG(); o.svgId = SVGFontType.SVGFONT; {e}({f}, ExportForScreensType.SE_SVG, o);"),
"SVGIdType",
),
(format!("var o = new ExportForScreensPDFOptions(); o.pdfPreset = '{long}'; {e}({f}, ExportForScreensType.SE_PDF, o);"), "255 bytes"),
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, {{artboards: '1'}});"), "ExportForScreensItemToExport"),
(format!("var i = new ExportForScreensItemToExport(); i.artboards = '2-1'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), "range"),
(
format!("var i = new ExportForScreensItemToExport(); i.artboards = 0; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
"whole number from 1",
),
(
format!("var i = new ExportForScreensItemToExport(); i.assets = 3; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
"array of asset ids",
),
(
format!("var i = new ExportForScreensItemToExport(); i.assets = [1.5]; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
"not an asset id",
),
(
format!("var i = new ExportForScreensItemToExport(); i.document = 'yes'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
"true or false",
),
(
format!("var i = new ExportForScreensItemToExport(); i.artboard = '1'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"),
"has no option artboard",
),
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, undefined, 5);"), "fileNamePrefix must be a string"),
(format!("{e}({f}, ExportForScreensType.SE_PNG24, null);"), "the options must be an object"),
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, null);"), "ExportForScreensItemToExport"),
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, undefined, null);"), "fileNamePrefix must be a string"),
(format!("var i = new ExportForScreensItemToExport(); i.artboards = '3'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), "range"),
];
for (case, wanted) in &cases {
let e = failure(&mut s, &base, &format!("Folder.userData; {case}"));
assert!(e.contains(wanted), "{case}: {e}");
}
assert!(!dir.join("x").exists(), "nothing was written");
let _ = std::fs::remove_dir_all(base);
}
+1
View File
@@ -400,6 +400,7 @@ const NOT_LOCATIONS: &[&str] = &[
"emptyTextPaths",
"sortPaths",
"alterPaths",
"compoundPaths",
"includeLinkedFiles",
"linksFolder",
];
@@ -47,6 +47,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"),
("Document.prototype.exportForScreens", "app.activeDocument.exportForScreens(f, ExportForScreensType.SE_PNG24);", "filesWritten"),
("Document.prototype.imageCapture", "app.activeDocument.imageCapture(f);", "filesWritten"),
("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"),
];
@@ -98,12 +99,14 @@ const INSIDE: &[(&str, &str)] = &[
),
(
"",
"activeDocument activeDocument= app Application Artboard Artboards BlendModes CompoundPathItem CompoundPathItems \
CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
"activeDocument activeDocument= app Application Artboard Artboards BlendModes Brush Brushes ColorModel CompoundPathItem \
CompoundPathItems CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \
PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \
selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
GraphicStyle GraphicStyles GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint \
PathPointSelection PathPoints PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems \
RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \
Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Tag Tags TracingObject TracingOptions Transformation \
View Views ZOrderMethod",
),
("Application.", "prototype"),
(
@@ -132,15 +135,15 @@ const INSIDE: &[(&str, &str)] = &[
("Document.", "prototype"),
(
"Document.prototype.",
"activeLayer activeLayer= artboards characterStyles close compoundPathItems constructor convertCoordinate \
"activeLayer activeLayer= artboards brushes characterStyles close compoundPathItems constructor convertCoordinate \
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems rulerOrigin \
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
symbols symbols= tags textFrames toString typename views width",
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName gradients \
gradients= graphicStyles groupItems height layers name pageItems paragraphStyles parent path pathItems patterns \
patterns= placedItems rasterItems rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= \
spots stories swatchGroups swatches symbolItems symbols tags textFrames toString typename views width",
),
("Views.", "prototype"),
("Views.prototype.", "constructor index length parent toString typename"),
@@ -246,6 +249,35 @@ const INSIDE: &[(&str, &str)] = &[
"anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \
rightDirection= selected selected= toString typename",
),
("Swatches.", "prototype"),
("Swatches.prototype.", "add constructor getByName getSelected getSelected= index length parent removeAll typename"),
("Swatch.", "prototype"),
("Swatch.prototype.", "color color= constructor name name= parent remove typename"),
("Spots.", "prototype"),
("Spots.prototype.", "add constructor getByName index length parent removeAll typename"),
("Spot.", "prototype"),
("Spot.prototype.", "color color= colorType colorType= constructor getInternalColor name name= parent remove spotKind typename"),
("SwatchGroups.", "prototype"),
("SwatchGroups.prototype.", "add constructor getByName index length parent removeAll typename"),
("SwatchGroup.", "prototype"),
("SwatchGroup.prototype.", "addSpot addSwatch constructor getAllSwatches name name= parent remove removeAll typename"),
("Symbols.", "prototype"),
("Symbols.prototype.", "add constructor getByName index length parent removeAll typename"),
("Symbol.", "prototype"),
("Symbol.prototype.", "constructor duplicate name name= parent remove typename"),
("SymbolItems.", "prototype"),
("SymbolItems.prototype.", "add constructor getByName index length parent removeAll typename"),
("SymbolItem.", "prototype"),
("SymbolItem.prototype.", "constructor symbol symbol="),
("GraphicStyles.", "prototype"),
("GraphicStyles.prototype.", "constructor getByName index length parent removeAll typename"),
("GraphicStyle.", "prototype"),
("GraphicStyle.prototype.", "applyTo constructor mergeTo name name= parent remove typename"),
("Brushes.", "prototype"),
("Brushes.prototype.", "constructor getByName index length parent typename"),
("Brush.", "prototype"),
("Brush.prototype.", "applyTo constructor name parent typename"),
("ColorModel.", "PROCESS REGISTRATION SPOT"),
("Tags.", "prototype"),
("Tags.prototype.", "add constructor getByName index length parent removeAll typename"),
("Tag.", "prototype"),
@@ -272,8 +304,14 @@ const INSIDE: &[(&str, &str)] = &[
("PolarityValues.", "NEGATIVE POSITIVE"),
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"),
("SpotColorKind.", "SPOTCMYK SPOTLAB SPOTRGB"),
("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"),
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
(
"SymbolRegistrationPoint.",
"SYMBOLBOTTOMLEFTPOINT SYMBOLBOTTOMMIDDLEPOINT SYMBOLBOTTOMRIGHTPOINT SYMBOLCENTERPOINT SYMBOLMIDDLELEFTPOINT \
SYMBOLMIDDLERIGHTPOINT SYMBOLTOPLEFTPOINT SYMBOLTOPMIDDLEPOINT SYMBOLTOPRIGHTPOINT",
),
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
// The enumerations of saving, exporting and opening.
@@ -340,6 +378,13 @@ const INSIDE: &[(&str, &str)] = &[
("Document.prototype.", "rasterize windowCapture windowCapture="),
("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"),
("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"),
// The enumerations of exporting for screens (`AntiAliasingMethod`, `SVGCSSPropertyLocation` and `SVGFontType` are above).
("", "ExportForScreensScaleType ExportForScreensType JPEGCompressionMethodType RasterImageLocation SVGIdType"),
("ExportForScreensScaleType.", "SCALEBYFACTOR SCALEBYHEIGHT SCALEBYRESOLUTION SCALEBYWIDTH"),
("ExportForScreensType.", "SE_JPEG100 SE_JPEG20 SE_JPEG50 SE_JPEG80 SE_PDF SE_PNG24 SE_PNG8 SE_SVG"),
("JPEGCompressionMethodType.", "BASELINEOPTIMIZED BASELINESTANDARD PROGRESSIVE"),
("RasterImageLocation.", "EMBED LINK PRESERVE"),
("SVGIdType.", "SVGIDMINIMAL SVGIDREGULAR SVGIDUNIQUE"),
// The enumerations of placed and raster items.
("", "ImageColorSpace RasterLinkState"),
("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"),
@@ -435,6 +480,7 @@ const INSIDE: &[(&str, &str)] = &[
("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"),
("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"),
("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"),
// The text classes and their enumerations.
(
"",
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
@@ -570,9 +616,11 @@ const INSIDE: &[(&str, &str)] = &[
/// that have no members of their own, the color classes, and the save, export, rasterize and image
/// capture option classes.
const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor cmykColor \
EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions \
ImageCaptureOptions RasterizeOptions";
ImageCaptureOptions RasterizeOptions \
ExportForScreensItemToExport ExportForScreensOptionsJPEG ExportForScreensOptionsPNG24 \
ExportForScreensOptionsPNG8 ExportForScreensOptionsWebOptimizedSVG ExportForScreensPDFOptions";
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
/// own API, and what `vc.run` does depends on the command it runs.
@@ -140,6 +140,144 @@ fn native_composite_meanings_survive_editable_and_embedded_placement() {
}
}
#[test]
fn native_dimension_label_font_follows_a_renamed_composite_font() {
let _context = FontContext::hold();
let dir = TempDir::new("native-composite-dimension");
let path = dir.join("dimension.vectorcraft");
// The second name is 255 bytes, so an alias that only counted characters would pass the 256
// bytes a dimension's family keeps.
for name in ["NativeAdoptionDimension".to_string(), "\u{3042}".repeat(85)] {
assert_dimension_alias(&path, &name);
}
}
fn assert_dimension_alias(path: &Path, name: &str) {
let incoming = CompositeFont::new(name, "Source Sans 3", "Regular");
let mut source = destination(std::slice::from_ref(&incoming));
let options = json!({"fontFamily": incoming.name, "fontStyle": "Regular"});
source.execute("dimension.create", &json!({"a": [4, 20], "b": [60, 20], "options": options})).unwrap();
let source_doc = document(&source).clone();
source.execute("type.compositeFonts.set", &json!({"fonts": []})).unwrap();
write_native(path, &source_doc);
for linked in [false, true] {
let mut existing = incoming.clone();
existing.parts.roman.size = 125.0;
let mut session = destination(&[existing]);
let id = place(&mut session, path, linked);
let root = document(&session).node(id).unwrap();
let (mut stored, mut drawn) = (Vec::new(), Vec::new());
root.walk(&mut |node| {
if let Some(dimension) = &node.extras().dimension {
stored.push(dimension.options.font_family.clone());
}
if let NodeKind::Text(text) = &node.kind {
drawn.extend(text.runs.iter().map(|run| run.style.font_family.clone()));
}
});
assert_eq!(stored.len(), 1, "REGRESSION: the placed art keeps its one editable dimension");
assert!(stored[0].len() <= 256, "REGRESSION: the alias fits a dimension's family ({} bytes)", stored[0].len());
assert!(!drawn.is_empty(), "CONTROL: the dimension draws a label");
assert!(!CompositeFont::same_name(&drawn[0], &incoming.name), "CONTROL: the conflicting name is aliased");
assert!(
drawn.iter().all(|family| family == &stored[0]),
"REGRESSION: a redrawn dimension label must keep the aliased composite font ({stored:?} vs {drawn:?})"
);
}
}
#[test]
fn native_dimension_reuses_an_equal_same_named_composite_font_with_a_longer_spelling() {
let _context = FontContext::hold();
let dir = TempDir::new("native-composite-dimension-same-name");
let path = dir.join("dimension.vectorcraft");
// 86 ASCII letters are 86 bytes; 86 Kelvin signs are the same name in any case and 258 bytes.
let incoming = CompositeFont::new("k".repeat(86), "Source Sans 3", "Regular");
let mut source = destination(std::slice::from_ref(&incoming));
let options = json!({"fontFamily": incoming.name, "fontStyle": "Regular"});
source.execute("dimension.create", &json!({"a": [4, 20], "b": [60, 20], "options": options})).unwrap();
let source_doc = document(&source).clone();
source.execute("type.compositeFonts.set", &json!({"fonts": []})).unwrap();
write_native(&path, &source_doc);
let mut existing = incoming.clone();
existing.name = "\u{212A}".repeat(86);
assert!(existing.name.len() > 256, "CONTROL: the destination's spelling is longer than a dimension's family keeps");
assert!(CompositeFont::same_name(&existing.name, &incoming.name), "CONTROL: the two spellings are one name");
for linked in [false, true] {
let mut session = destination(std::slice::from_ref(&existing));
let id = place(&mut session, &path, linked);
assert_eq!(
document(&session).composite_fonts.len(),
1,
"REGRESSION: an equal composite font of the same name is reused, not copied under a new name"
);
let mut stored = Vec::new();
document(&session).node(id).unwrap().walk(&mut |node| {
stored.extend(node.extras().dimension.as_ref().map(|d| d.options.font_family.clone()));
});
assert_eq!(stored, vec![incoming.name.clone()], "REGRESSION: the dimension keeps its own spelling of the reused name");
}
}
#[test]
fn native_composite_alias_skips_a_family_named_by_a_dimension_in_brush_art() {
let _context = FontContext::hold();
let dir = TempDir::new("native-composite-brush-dimension");
let path = dir.join("lettering.vectorcraft");
let incoming = CompositeFont::new("NativeAdoptionBrushDimension", "Source Sans 3", "Regular");
write_native(&path, &font_document(&incoming));
let taken = format!("{} 2", incoming.name);
// The destination's only use of the first free alias is a dimension inside an art brush.
let mut builder = destination(&[]);
let options = json!({"fontFamily": taken, "fontStyle": "Regular"});
let made = builder.execute("dimension.create", &json!({"a": [4, 20], "b": [60, 20], "options": options})).unwrap();
let dimension = NodeId(made["id"].as_u64().unwrap());
builder.execute("brush.new", &json!({"type": "art", "name": "NativeAdoptionDimensionBrush", "ids": [dimension.0]})).unwrap();
let mut doc = document(&builder).clone();
if doc.node(dimension).is_some() {
doc.remove(dimension).unwrap();
}
// Leave the dimension's options as the only place the family is named, as in a label drawn
// before its options changed, so the reservation cannot come from the label's own runs.
fn relabel(node: &mut Node) {
if let NodeKind::Text(text) = &mut node.kind {
for run in &mut text.runs {
run.style.font_family = "Source Sans 3".into();
}
}
for child in node.children_mut().into_iter().flatten() {
relabel(std::sync::Arc::make_mut(child));
}
}
let mut brushes = vectorcraft_brush::library(&doc);
for art in brushes.iter_mut().flat_map(|brush| brush.art_mut()) {
relabel(art);
}
vectorcraft_brush::store(&mut doc, &brushes);
let mut in_art = Vec::new();
doc.visit_stored(|node, _| in_art.extend(node.extras().dimension.as_ref().map(|d| d.options.font_family.clone())));
assert!(in_art.is_empty(), "CONTROL: no dimension is left in the document's art");
let mut in_brush = Vec::new();
for brush in vectorcraft_brush::library(&doc) {
if let vectorcraft_brush::BrushKind::Art(art) = &brush.kind {
art.art.walk(&mut |node| in_brush.extend(node.extras().dimension.as_ref().map(|d| d.options.font_family.clone())));
}
}
assert_eq!(in_brush, vec![taken.clone()], "CONTROL: the brush art holds the dimension");
let mut existing = incoming.clone();
existing.parts.roman.size = 125.0;
let mut session = Session::new();
session.add_document(doc, None);
session.execute("type.compositeFonts.set", &json!({"fonts": [existing]})).unwrap();
let id = place(&mut session, &path, false);
let family = placed_family(&session, id);
assert!(!CompositeFont::same_name(&family, &incoming.name), "CONTROL: the conflicting name is aliased");
assert!(
!CompositeFont::same_name(&family, &taken),
"REGRESSION: the alias must not take a family a brush-art dimension already names ({family})"
);
}
#[test]
fn native_composite_alias_is_reused_without_changing_destination_art() {
let _context = FontContext::hold();
+21 -15
View File
@@ -80,6 +80,27 @@ impl Interp {
})?;
instance(self, proto, fs)
}
/// The [`crate::Data`] for `id` when it is a `File` the `File` class made (its prototype is
/// `File.prototype` and it holds its path in its [`Class::FsEntry`]), as [`file_ref_path`] reads
/// it, or a `Folder` the `Folder` class made, as [`folder_ref`] gives one; `None` for any other
/// object, one made with `Object.create(File.prototype)` or `Object.create(Folder.prototype)`
/// included.
pub(crate) fn file_ref_of(&self, id: ObjId) -> JsResult<Option<crate::Data>> {
let Some(c) = &self.files else { return Ok(None) };
let o = self.object(id)?;
let key = if o.proto == Some(c.file_proto) {
crate::FILE_REF_KEY
} else if o.proto == Some(c.folder_proto) {
FOLDER_REF_KEY
} else {
return Ok(None);
};
Ok(match &o.class {
Class::FsEntry(s) => Some(crate::Data::Object(vec![(key.to_string(), crate::Data::String(s.to_rust_string()))])),
_ => None,
})
}
}
/// The path of `o` when the `File` or `Folder` class made it.
@@ -147,21 +168,6 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
})
}
/// The path of `id` when it is a `File` the `File` class made: its prototype is `File.prototype`
/// and it holds its path in its [`Class::FsEntry`]. `None` for anything else, a `Folder` and an
/// object made with `Object.create(File.prototype)` included.
pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult<Option<String>> {
let Some(c) = &i.files else { return Ok(None) };
let o = i.object(id)?;
if o.proto != Some(c.file_proto) {
return Ok(None);
}
Ok(match own_path(i, id)? {
Some(Value::String(s)) => Some(s.to_rust_string()),
_ => None,
})
}
fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> {
if let Value::String(s) = &value {
i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?;
+11 -7
View File
@@ -203,9 +203,9 @@ struct Reading {
ancestors: Vec<ObjId>,
path: Vec<Step>,
function: Rc<str>,
/// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under
/// [`crate::FILE_REF_KEY`], and a plain object that has one of the keys, or
/// [`crate::FOLDER_REF_KEY`], is refused.
/// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` or a `Folder` as its
/// path under [`crate::FILE_REF_KEY`] or [`crate::FOLDER_REF_KEY`], and a plain object that has
/// one of those keys is refused.
hosted: bool,
}
@@ -276,12 +276,16 @@ impl Interp {
if r.ancestors.len() >= r.limits.depth {
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
}
// A `File` reads as its path ([`crate::FILE_REF_KEY`]).
// A `File` or a `Folder` reads as its path ([`crate::FILE_REF_KEY`], [`crate::FOLDER_REF_KEY`]).
if r.hosted
&& let Some(path) = crate::file_classes::file_path(self, id)?
&& let Some(file) = self.file_ref_of(id)?
{
self.charge_reading(r, path.len().saturating_add(16))?;
return Ok(Data::Object(vec![(crate::FILE_REF_KEY.to_string(), Data::String(path))]));
let len: usize = match &file {
Data::Object(items) => items.iter().map(|(_, v)| if let Data::String(p) = v { p.len() } else { 0 }).sum(),
_ => 0,
};
self.charge_reading(r, len.saturating_add(16))?;
return Ok(file);
}
let shape = match &self.object(id)?.class {
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
+17 -18
View File
@@ -29,7 +29,8 @@
//!
//! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each
//! member of its class and of the classes it descends from, apart from the members that are not
//! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members,
//! available yet ([`HostMember::Unavailable`]). A member a class declares, available or not, hides
//! the member of that name in the classes it descends from. `for`-`in` lists the properties among those members,
//! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and
//! `Object.getOwnPropertyDescriptor` do not report the members.
//!
@@ -38,7 +39,7 @@
//! told always matches what the class has. A class that names a member twice, or describes a member
//! it does not have, is refused.
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key};
@@ -147,10 +148,9 @@ pub(crate) struct Entry {
family: u32,
/// The class this class's prototype inherits from, as an index into the realm's classes.
parent: Option<u32>,
/// The names of the members `hasOwnProperty` reports: every member but the unavailable ones.
own: Rc<HashSet<Key>>,
/// The names of the members this class declares as unavailable.
unavailable: Rc<HashSet<Key>>,
/// The names of the members the class declares, each with whether `hasOwnProperty` reports it:
/// every member but the unavailable ones.
own: Rc<HashMap<Key, bool>>,
/// The class's own members as `reflect` lists them.
members: Rc<[Reflected]>,
}
@@ -250,19 +250,15 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec<f64>)> {
impl Interp {
/// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host
/// class, and `k` names an available member of that class or of a class it descends from. The
/// nearest class that declares `k` decides, so a member a class declares unavailable is not
/// reported even when a class it descends from has it.
/// class, and the closest of that class and the classes it descends from that declares `k`
/// declares it as available.
pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult<bool> {
let Class::Host(h) = &self.object(id)?.class else { return Ok(false) };
let mut class = Some(h.class);
while let Some(c) = class {
let Some(e) = self.host_classes.get(c as usize) else { return Err(Abrupt::Internal("host class out of range".into())) };
if e.own.contains(k) {
return Ok(true);
}
if e.unavailable.contains(k) {
return Ok(false);
if let Some(available) = e.own.get(k) {
return Ok(*available);
}
class = e.parent;
}
@@ -625,8 +621,7 @@ fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, und
let r = fill_class(i, proto, &class);
i.temp_roots.truncate(mark);
let ctor = r?;
let (unavailable, own_members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_)));
let names = |list: Vec<&(String, HostMember)>| list.into_iter().map(|(name, _)| key(name)).collect::<HashSet<Key>>();
let own = class.members.iter().map(|(name, m)| (key(name), !matches!(m, HostMember::Unavailable(_)))).collect();
i.host_classes.push(Entry {
name: class.name.as_str().into(),
proto,
@@ -635,10 +630,14 @@ fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, und
index: class.index,
family,
parent: parent_class,
own: Rc::new(names(own_members)),
unavailable: Rc::new(names(unavailable)),
own: Rc::new(own),
members,
});
// The host class named `Symbol` keeps the built-in `Symbol` global. Its objects use the host prototype.
let global = i.global;
if class.name == "Symbol" && i.get_own_property(global, &key(&class.name))?.is_some() {
return Ok(());
}
undo.define_global(i, &class.name, Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
}
+60
View File
@@ -24,6 +24,31 @@ fn non_finite_indexer_keys_reach_the_host_unchanged() {
assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into()));
}
#[test]
fn a_host_class_named_like_a_built_in_global_leaves_the_built_in() {
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 10_000_000, ..Limits::default() });
let name: HostFunction = Rc::new(|_| Ok(Data::String("art".into())));
let class = HostClass {
name: "Symbol".into(),
parent: None,
members: vec![("name".into(), HostMember::Get(name))],
info: Vec::new(),
index: None,
construct: None,
};
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Symbol", &[1.0]))]).unwrap();
let source = "[typeof Symbol(), typeof Symbol.iterator, it.name, it instanceof Symbol].join('|')";
assert_eq!(r.run(source).unwrap(), JsValue::String("symbol|symbol|art|false".into()));
}
#[test]
fn a_host_class_replaces_an_existing_global_other_than_symbol() {
let mut r = realm(1_000_000);
let class = HostClass { name: "Math".into(), parent: None, members: vec![], info: Vec::new(), index: None, construct: None };
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Math", &[1.0]))]).unwrap();
assert_eq!(r.run("it instanceof Math && it.constructor === Math").unwrap(), JsValue::Bool(true));
}
#[test]
fn host_receivers_obey_limits_lowered_after_the_object_was_created() {
for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] {
@@ -1129,6 +1154,41 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() {
);
}
#[test]
fn a_member_a_class_declares_hides_the_one_its_parent_declares() {
let mut r = realm(1_000_000);
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into())));
let base = HostClass {
name: "Base".into(),
parent: None,
members: vec![
("size".to_string(), HostMember::Get(value.clone())),
("later".to_string(), HostMember::Unavailable(missing.clone())),
("kept".to_string(), HostMember::Get(value.clone())),
],
info: Vec::new(),
index: None,
construct: None,
};
let leaf = HostClass {
name: "Leaf".into(),
parent: Some("Base".into()),
members: vec![("size".to_string(), HostMember::Unavailable(missing)), ("later".to_string(), HostMember::Get(value))],
info: Vec::new(),
index: None,
construct: None,
};
r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap();
r.start(
"var read; try { it.size; read = 'read'; } catch (e) { read = 'threw'; }\
[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), read, it.hasOwnProperty('later'),\
it.propertyIsEnumerable('later'), it.hasOwnProperty('kept')].join()",
)
.unwrap();
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,threw,true,true,true".into()));
}
#[test]
fn an_unavailable_member_hides_the_member_its_parent_class_has() {
let mut r = realm(1_000_000);
+1 -1
View File
@@ -1555,7 +1555,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
),
(
"ui.widthPointEdit",
+15 -4
View File
@@ -53,6 +53,8 @@ pub struct RasterExportOptions {
pub quality: u8,
/// WebP: lossless (`true`), or lossy at [`Self::quality`].
pub webp_lossless: bool,
/// WebP: the sRGB profile in an `ICCP` chunk.
pub webp_embed_icc: bool,
/// JPEG colour model, coding and profile.
pub jpeg: jpeg::JpegOptions,
/// PNG-8 and GIF: the colour reduction (also BMP's at 1, 4 and 8 bits).
@@ -79,6 +81,7 @@ impl Default for RasterExportOptions {
interlaced: false,
quality: 90,
webp_lossless: true,
webp_embed_icc: true,
jpeg: jpeg::JpegOptions::default(),
palette: quantize::PaletteOptions::default(),
tiff: tiff::TiffOptions::default(),
@@ -128,7 +131,7 @@ impl RasterExportOptions {
};
jpeg::encode(&px, img.width, img.height, self.quality, Some(self.ppi), &self.jpeg)
}
RasterFormat::WebP => webp(img, (!self.webp_lossless).then_some(self.quality)),
RasterFormat::WebP => webp(img, (!self.webp_lossless).then_some(self.quality), self.webp_embed_icc),
RasterFormat::Png8 | RasterFormat::Gif => {
let ix = quantize::quantize(&img.to_straight(), img.width, img.height, &self.palette);
match format {
@@ -188,8 +191,14 @@ pub fn on_white(p: &[u8; 4]) -> [u8; 3] {
}
/// WebP: lossless (`VP8L`) when `lossy_quality` is `None`, else lossy (`VP8 `, with an `ALPH`
/// chunk when some pixels are not opaque) at that quality 0–100.
pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>) -> Result<Vec<u8>, String> {
/// chunk when some pixels are not opaque) at that quality 0–100. With `embed_icc` the file is
/// extended (`VP8X`) and holds the sRGB profile in an `ICCP` chunk.
pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>, embed_icc: bool) -> Result<Vec<u8>, String> {
let icc = if embed_icc {
Some(vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).map_err(|e| format!("WebP colour profile: {e}"))?.to_vec())
} else {
None
};
let src = craft_image_codecs::Image::from_raw(
img.width,
img.height,
@@ -197,10 +206,12 @@ pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>) -> Result<Vec<u8>,
craft_image_codecs::SampleType::U8,
img.to_straight(),
)
.map_err(|e| format!("WebP encoding failed: {e}"))?;
.map_err(|e| format!("WebP encoding failed: {e}"))?
.with_icc(icc);
let opts = craft_image_codecs::EncodeOptions {
webp_lossless: lossy_quality.is_none(),
webp_quality: lossy_quality.unwrap_or(100).min(100),
embed_icc,
..craft_image_codecs::EncodeOptions::default()
};
let file = craft_image_codecs::encode(&src, craft_image_codecs::Format::WebP, &opts).map_err(|e| format!("WebP encoding failed: {e}"))?;
+32 -2
View File
@@ -220,9 +220,10 @@ fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> {
#[test]
fn lossy_webp_keeps_transparent_pixels_transparent() {
let d = circle_doc();
let lossless = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &RasterExportOptions::default()).unwrap();
let no_icc = RasterExportOptions { webp_embed_icc: false, ..Default::default() };
let lossless = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &no_icc).unwrap();
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
let o = RasterExportOptions { webp_lossless: false, quality: 75, ..Default::default() };
let o = RasterExportOptions { webp_lossless: false, quality: 75, ..no_icc };
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap();
assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ALPH", *b"VP8 "]);
let img = export(&d, RasterFormat::WebP, &o);
@@ -236,6 +237,35 @@ fn lossy_webp_keeps_transparent_pixels_transparent() {
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
}
/// The payload of the first chunk of type `ty` in RIFF WebP `file`.
fn webp_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> &'a [u8] {
let at = chunk_offset(file, ty);
let len = u32::from_le_bytes(file[at + 4..at + 8].try_into().unwrap()) as usize;
&file[at + 8..at + 8 + len]
}
/// By default a WebP file, lossless or lossy, holds the sRGB profile in an `ICCP` chunk that its
/// `VP8X` header flags, and a decoder reads the profile back; with `webp_embed_icc` off it holds
/// none.
#[test]
fn webp_embeds_the_srgb_profile_unless_told_not_to() {
let d = circle_doc();
let srgb = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).unwrap();
for lossless in [true, false] {
let o = RasterExportOptions { webp_lossless: lossless, ..Default::default() };
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap();
let chunks = webp_chunks(&file);
assert_eq!(chunks[..2], [*b"VP8X", *b"ICCP"], "lossless {lossless}: {chunks:?}");
assert_ne!(webp_chunk(&file, b"VP8X")[0] & 0x20, 0, "lossless {lossless}: the VP8X ICC flag");
assert_eq!(webp_chunk(&file, b"ICCP"), &*srgb, "lossless {lossless}");
let mut dec = image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&file)).unwrap();
assert_eq!(image::ImageDecoder::icc_profile(&mut dec).unwrap().as_deref(), Some(&*srgb), "lossless {lossless}");
let off = RasterExportOptions { webp_embed_icc: false, ..o };
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &off).unwrap();
assert!(!webp_chunks(&file).contains(b"ICCP"), "lossless {lossless}");
}
}
/// A lossy frame's tag (RFC 6386 §9.1) holds its first partition's size in 19 bits. A frame whose
/// size field is at that limit may hold a larger partition, so it is refused; frames below it
/// decode with another decoder at every quality, a 1 × 1 image and transparent pixels included.
+1 -1
View File
@@ -424,7 +424,7 @@ impl Rendered {
}
/// Encode as lossless WebP.
pub fn to_webp(&self) -> Result<Vec<u8>, String> {
encode::webp(self, None)
encode::webp(self, None, false)
}
/// Straight-alpha RGBA at (x, y).
pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
+82 -14
View File
@@ -27,7 +27,10 @@ use crate::catalog::{self, FeatureId};
use crate::directives;
use crate::lex::{Lexer, T, Token, expr_after};
use crate::report::{self, Acc, OutsideId};
use sig::{COMPOUND, LineBreaks, NEWER, Read, Sig, ends_value, for_in, goes_on_after, goes_on_with, is, member_mark, newer_number, unquote, word};
use sig::{
COMPOUND, LineBreaks, NEWER, Read, Sig, ends_value, exact_unquote, for_in, goes_on_after, goes_on_with, is, member_mark, newer_number, unquote,
word,
};
mod declared;
mod features;
@@ -691,6 +694,18 @@ struct Analyzer<'s, 'a, 'l> {
/// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit
/// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing.
writers: HashMap<String, u8>,
/// The variables a function body read before any literal gave them methods, in a way that
/// changes or shares them ([`Analyzer::writer_use`]): the body may run after the literal (a
/// hoisted declaration), so the literal's methods are not the script's own. Each name has the
/// most function bodies that were open where it was read; a literal in a body with that many
/// open or more is unaffected, since it gives a variable of its own.
shared_early: HashMap<String, usize>,
/// [`Analyzer::shared_early`] had no room for a name: no literal gives methods that are the
/// script's own from then on.
shared_full: bool,
/// The function body that the token being read closed (its `}`): how many bodies were open
/// in it and the names it declared. A value read just before the `}` is read in that body.
closed_body: Option<(usize, Vec<String>)>,
/// The object literals being assigned to a variable, the innermost last, up to
/// [`crate::Limits::nesting`] of them.
objects: Vec<ObjectValue>,
@@ -700,6 +715,29 @@ struct Analyzer<'s, 'a, 'l> {
/// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver
/// that is not such a variable.
index_receiver: u8,
/// Whether that receiver's own methods hold at this place ([`Analyzer::stable`]).
index_stable: bool,
/// The depths of the open `[` that index the global object (`$.global[`, `this[`,
/// `globalThis[`), the innermost last, up to [`crate::Limits::nesting`] of them.
global_indexes: Vec<usize>,
/// The last token was the `]` that closes an index of the global object.
global_index_closed: bool,
/// The offset of the last `]` that closes an index of the global object by a string literal
/// alone, with the variable name it reads (`$.global['local']`, `this['local']`), or `None` when
/// the literal does not decode to one exact name.
global_bracket: Option<(usize, Option<String>)>,
/// The offset of the last name read as a property of the global object (`local` in
/// `$.global.local`, `globalThis.local` or `this.local`).
global_member: Option<usize>,
/// The `with` statement whose head is being read: the bracket depth of its `with`, and whether
/// its `)` was read.
with_head: Option<(usize, bool)>,
/// The bracket depths the bodies of the open `with` statements hold at, the innermost last, up
/// to [`crate::Limits::nesting`] of them ([`Analyzer::with_step`]).
withs: Vec<usize>,
/// A `with` statement had no room in [`Analyzer::withs`]: no call of a literal's own method is
/// known from then on.
withs_full: bool,
/// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`].
others: bool,
/// The variables that may get another value when code read elsewhere runs: assigned inside a
@@ -786,9 +824,20 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(),
maybe_files_full: false,
writers: HashMap::new(),
shared_early: HashMap::new(),
shared_full: false,
closed_body: None,
objects: vec![],
closed: None,
index_receiver: 0,
index_stable: false,
global_indexes: vec![],
global_index_closed: false,
global_bracket: None,
global_member: None,
with_head: None,
withs: vec![],
withs_full: false,
others: known.others || declared.includes,
later: HashSet::new(),
later_full: false,
@@ -872,6 +921,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
fn token(&mut self, mut t: Sig<'s>) {
self.acc.steps = self.acc.steps.saturating_add(1);
self.closed_body = None;
// The name of a grouped value whose last `)` was read, or of a value without parentheses that
// `t` ends, holds the value, or nothing the check follows, before `t` starts a member chain or
// closes a function body.
@@ -1195,7 +1245,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
/// in them gets back what it held outside them, and the `var` statement a body was in goes on.
fn close_scopes(&mut self) {
while self.scopes.last().is_some_and(|s| self.depth() < s.depth) {
let open = self.scopes.len();
let Some(scope) = self.scopes.pop() else { return };
if self.closed_body.is_none() {
self.closed_body = Some((open, scope.saved.keys().cloned().collect()));
}
self.var_depth = scope.var_depth;
for (name, saved) in scope.saved {
self.restore(name, saved);
@@ -1491,6 +1545,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
{
let h1 = self.h[1];
let declared = word(h1, "var") || (is(h1, ",") && self.var_depth.is_some());
if !declared && !member_mark(h1) && !is(h1, "@") {
self.share_early(name.text);
}
if declared {
if self.in_catch(name.text) {
self.declare_in_catch(name.text);
@@ -1507,13 +1564,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.assign = Some(Assign { name: name.text.to_string(), after_new: false });
}
}
if let Some((name, _)) = self.updated(t)
&& !self.scopes.is_empty()
&& !self.declared_in_body(name)
{
self.reassigned_later(name);
let updated = self.updated(t);
if let Some((name, _)) = updated {
self.share_early(name);
if !self.scopes.is_empty() && !self.declared_in_body(name) {
self.reassigned_later(name);
}
}
match self.updated(t) {
match updated {
// The value on the right is read at this depth, and the name holds nothing the check
// follows once that value ends ([`Analyzer::settle_groups`]).
Some((name, true)) => self.start_value(name.to_string(), Operand::Other),
@@ -1527,19 +1585,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
/// closes a function body, so a literal given to the body's own variable stays inside the body.
/// No variable joins when code the scan does not follow at that point may give it another value:
/// a function body that assigns its name ([`Declared::body_assigned`], [`Analyzer::later`]), a
/// member assignment of a property of that name, which may be the global object's
/// ([`Declared::rebound`]), a function body that assigns a `saveAs` or `exportFile` property of
/// any object ([`Declared::body_writer_assigned`]), code given as text or a `with` statement
/// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that
/// function body read before the literal that changes or shares the variable, or assigns a property
/// of that name, which may be the global object's ([`Analyzer::shared_early`]), code given as text
/// or a `with` statement ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that
/// assigns the variable use [`Declared::looped`] to classify its methods.
fn settle_literal(&mut self, t: &Sig<'s>) {
if let Some((name, bits)) = self.closed.take()
&& (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t)))
&& !self.shared_full
&& self.shared_early.get(&name).is_none_or(|&open| open <= self.scopes.len())
&& !self.unsure
&& !self.others
&& !self.declared.rebound.contains(&name)
&& !self.declared.body_assigned.contains(name.as_str())
&& !self.declared.body_writer_assigned
&& !self.later_full
&& !self.later.contains(&name)
&& !self.declared.looped_full
@@ -1586,8 +1643,19 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
/// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing
/// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the
/// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on
/// (`{…} && d`), see the variable as it was.
/// (`{…} && d`), see the variable as it was. A `this` or the variable's own name inside the body
/// of such a function expression takes the method out as well: running it may replace the
/// object's methods (`{saveAs: function () { this.saveAs = d.saveAs; }}`).
fn object_key(&mut self, t: &Sig<'s>, before: usize) {
if t.kind == T::Ident {
for o in self.objects.iter_mut().filter(|o| o.depth < before) {
if let Some((bit, Value::Body)) = o.value
&& (t.text == "this" || t.text == o.name)
{
o.value = Some((bit, Value::Other));
}
}
}
if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) {
o.step(t);
}
+203 -14
View File
@@ -3,8 +3,8 @@
use std::collections::{HashMap, HashSet};
use super::{
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark,
unquote, word,
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, exact_unquote, for_in, goes_on_after, goes_on_with, is,
member_mark, unquote, word,
};
/// The names that give variables values the analysis doesn't read: a `with` statement makes an
@@ -76,11 +76,16 @@ pub(crate) struct Declared<'s> {
/// also before its body in the text when it is a declaration, so a variable of that name may lose
/// the value an assignment the analysis read gave it.
pub(super) body_assigned: HashSet<&'s str>,
/// A function body assigns a property named as one of [`catalog::DOM_FILE_WRITES`]
/// (`o.saveAs = …`, `this['exportFile'] = …`). The function may run at any time after it is
/// defined, and the object may be any variable's, so no variable's method of that name stays
/// the script's own.
pub(super) body_writer_assigned: bool,
/// The variables whose document write method a function body may replace (`local.saveAs = …`,
/// `local['saveAs'] += …`, `local[k] = …`, `var y = local`), unless the body declared the name
/// before it, each by the offset of the `{` of the function body that declares it anywhere in
/// the body (`None`: the global code's). The function may run at any time after it is defined,
/// also before its body in the text when it is a declaration.
pub(super) method_replaced: HashSet<(Option<usize>, &'s str)>,
/// The variables of [`Declared::method_replaced`] whose declaring body is not known, because a
/// body around the replacement is past [`crate::Limits::nesting`] or ran out of room for its
/// names: the replacement counts for a variable of that name in any body.
pub(super) method_replaced_any: HashSet<&'s str>,
/// The file has an `#include` line: the included file's code may give its variables values.
pub(super) includes: bool,
/// The variables assigned inside a loop, its parentheses included (`name = …`), each by the
@@ -139,6 +144,9 @@ struct Declarations<'s, 'a, 'l> {
brackets: Brackets,
/// The three significant tokens before this one, the latest first.
h: [Option<Sig<'s>>; 3],
/// The two significant tokens before the three of `h`, the latest first.
h3: Option<Sig<'s>>,
h4: Option<Sig<'s>>,
/// `function` was read at this bracket depth, and its body's `{` is still to come.
function: Option<usize>,
/// The bracket depth of the `var` statement being read.
@@ -155,6 +163,20 @@ struct Declarations<'s, 'a, 'l> {
keys: Vec<Key>,
/// The loops being read, the innermost last, up to [`crate::Limits::nesting`].
loops: Vec<Loop>,
/// The replacements of a variable's methods ([`Declared::method_replaced`]) read so far, each with
/// the entries of [`Declared::bodies`] around it, the outermost first. A `var` statement later in
/// a body declares the name for the whole body, so the body that declares the variable is found
/// once every body's names are known.
replaced: HashSet<(Vec<usize>, &'s str)>,
/// The entries of [`Declared::bodies`] whose names ran out of room: one of them may declare any
/// name.
names_full: HashSet<usize>,
/// The parameters of the function whose parentheses are being read: the bracket depth inside
/// them, the names so far, and whether they ran out of room.
params: Option<(usize, Vec<&'s str>, bool)>,
/// The parameters of each entry of [`Declared::bodies`], which are the body's own variables
/// (ECMA-262 3rd edition, section 10.1.3).
body_params: HashMap<usize, Vec<&'s str>>,
out: Declared<'s>,
}
@@ -200,6 +222,8 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
acc,
brackets: Brackets::default(),
h: [None; 3],
h3: None,
h4: None,
function: None,
var_depth: None,
assign: None,
@@ -207,6 +231,10 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
untracked: None,
keys: vec![],
loops: vec![],
replaced: HashSet::new(),
names_full: HashSet::new(),
params: None,
body_params: HashMap::new(),
out: Declared::default(),
};
let mut breaks = LineBreaks::default();
@@ -221,6 +249,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
while let Some(body) = d.bodies.pop() {
d.settle_looped(body);
}
d.settle_replaced();
let mut out = d.out;
for ids in out.looped.values_mut() {
ids.sort_unstable();
@@ -255,6 +284,17 @@ impl<'s> Declarations<'s, '_, '_> {
self.bracket(&t);
} else if t.kind == T::Ident {
self.declaration(&t);
let depth = self.depth();
if let Some((at, names, full)) = self.params.as_mut()
&& *at == depth
&& (is(h0, "(") || is(h0, ","))
{
if self.acc.room(names.len()) {
names.push(t.text);
} else {
*full = true;
}
}
}
let depth = self.depth();
self.loop_end(&t, depth);
@@ -266,6 +306,27 @@ impl<'s> Declarations<'s, '_, '_> {
{
self.looped(name.text);
}
// `o.local = …` or `o['local'] = …` in a loop: the object may be the global object
// ([`Declared::rebound`]), so the global variable of that name may get another value on each
// pass. A key with an escape may spell any name: any variable may be assigned in a loop.
if t.is("=") && !self.loops.is_empty() {
let property = if member_mark(h1) {
h0.filter(|s| s.kind == T::Ident).map(|s| s.text)
} else if is(h0, "]") && is(self.h[2], "[") {
let key = h1.filter(|s| s.kind == T::Str);
if key.is_some_and(|s| s.text.contains('\\')) {
self.out.looped_full = true;
}
key.filter(|s| s.text.len() >= 2 && !s.text.contains('\\')).and_then(|s| s.text.get(1..s.text.len() - 1))
} else {
None
};
if let Some(name) = property {
let id = self.out.loop_spans.len().saturating_sub(1);
self.keep_looped(None, name, vec![id]);
}
}
self.method_replacement(&t);
if let Some(after_new) = self.assign.take() {
if t.word("new") && !after_new {
self.assign = Some(true);
@@ -289,9 +350,123 @@ impl<'s> Declarations<'s, '_, '_> {
if !self.bodies.is_empty() || self.untracked.is_some() {
self.body_assignment(&t, depth);
}
self.h4 = self.h3;
self.h3 = self.h[2];
self.h = [Some(t), h0, h1];
}
/// `t` changes or shares a variable's methods, as [`Analyzer::writer_use`] reads it: `=`, a
/// compound operator, `++` or `--` on `local.saveAs` or `local['saveAs']` (one of the document
/// write methods), `++local.saveAs`, a key in brackets that is not one string literal
/// (`local[k]`, `local['sa' + 'veAs']`), `delete local`, or `local` used as a value
/// (`var y = local`, `f(local)`), where another name may hold its object. In a loop, `local` may
/// hold another method when a call of it earlier in the loop runs again ([`Declared::looped`]); in
/// a function body that does not declare `local`, the function may replace the method before any
/// call of it runs ([`Declared::method_replaced`]).
fn method_replacement(&mut self, t: &Sig<'s>) {
let [h0, h1, h2] = self.h;
let (h3, h4) = (self.h3, self.h4);
let ident = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| s.kind == T::Ident && !member_mark(before));
let write = |s: Option<Sig<'s>>| s.is_some_and(|s| s.kind == T::Ident && catalog::DOM_FILE_WRITES.contains(&s.text));
let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--"));
let key = t.is(":") && (is(h1, "{") || is(h1, ","));
let receiver = if changes && is(h1, ".") && write(h0) {
ident(h2, h3)
} else if changes
&& is(h0, "]")
&& is(h2, "[")
&& let Some(key) = h1.filter(|s| s.kind == T::Str)
{
// A key whose escapes do not decode to one exact name may spell any method's.
let writes = exact_unquote(key.text).is_none_or(|m| catalog::DOM_FILE_WRITES.contains(&m.as_str()));
ident(h3, h4).filter(|_| writes)
} else if is(h0, ".") && (is(h2, "++") || is(h2, "--")) && write(Some(*t)) && (h2.is_some_and(|s| s.nl) || !h1.is_some_and(|s| s.nl)) {
// `++local.saveAs`, not `n++` ending the line before `local.saveAs`.
ident(h1, h2)
} else if word(h0, "delete") {
ident(Some(*t), h0)
} else if let Some(name) = ident(h0, h1).filter(|_| !t.is(".") && !t.is("[") && !t.is("=") && !key) {
// `local` used as a value, or changed by a compound or update operator.
Some(name)
} else if is(h0, "[") {
// `local[k]`: a key that is not one string or number literal may name any method.
ident(h1, h2).filter(|_| t.kind != T::Str && t.kind != T::Number)
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str || s.kind == T::Number) {
// `local['sa' + k]`
ident(h2, h3).filter(|_| !t.is("]"))
} else {
None
};
let Some(name) = receiver.map(|s| s.text) else { return };
if !self.loops.is_empty() {
self.looped(name);
}
// Only the innermost body's own variable is not the one a nested function may reach from
// outside before the call runs.
let own = self.untracked.is_none()
&& self.bodies.last().is_some_and(|b| b.names.contains(name) || self.body_params.get(&b.index).is_some_and(|p| p.contains(&name)));
if (!self.bodies.is_empty() || self.untracked.is_some()) && !own {
if self.untracked.is_some() {
// A body past the nesting limit keeps no names, so any body around may declare the
// variable.
if self.out.method_replaced_any.contains(name) || self.acc.room(self.out.method_replaced_any.len()) {
self.out.method_replaced_any.insert(name);
} else {
self.out.unsure = true;
}
} else {
let key = (self.bodies.iter().map(|b| b.index).collect::<Vec<_>>(), name);
if self.replaced.contains(&key) || self.acc.room(self.replaced.len()) {
self.replaced.insert(key);
} else {
self.out.unsure = true;
}
}
}
}
/// Keeps each replacement in [`Self::replaced`] for the innermost body around it that declares
/// the variable anywhere in the body, or as a parameter, or for the global code when none does.
/// A replacement of a variable of the innermost body itself is not kept, as when the body
/// declared it before the replacement. When a body around it ran out of room for its names, the
/// body that declares the variable is not known, and the replacement counts for the variable of
/// that name in every body ([`Declared::method_replaced_any`]).
fn settle_replaced(&mut self) {
for (around, name) in std::mem::take(&mut self.replaced) {
let mut owner = None;
let mut known = true;
for (i, &index) in around.iter().enumerate().rev() {
if self.out.bodies.get(index).is_some_and(|(_, names)| names.contains(&name))
|| self.body_params.get(&index).is_some_and(|p| p.contains(&name))
{
owner = self.out.bodies.get(index).map(|(at, _)| (*at, i + 1 == around.len()));
break;
}
if self.names_full.contains(&index) {
known = false;
break;
}
}
if !known {
if self.out.method_replaced_any.contains(name) || self.acc.room(self.out.method_replaced_any.len()) {
self.out.method_replaced_any.insert(name);
} else {
self.out.unsure = true;
}
continue;
}
if owner.is_some_and(|(_, innermost)| innermost) {
continue;
}
let key = (owner.map(|(at, _)| at), name);
if self.out.method_replaced.contains(&key) || self.acc.room(self.out.method_replaced.len()) {
self.out.method_replaced.insert(key);
} else {
self.out.unsure = true;
}
}
}
/// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one
/// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`].
fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) {
@@ -557,9 +732,6 @@ impl<'s> Declarations<'s, '_, '_> {
None
};
if let Some(name) = property {
if (!self.bodies.is_empty() || self.untracked.is_some()) && catalog::DOM_FILE_WRITES.contains(&name.as_str()) {
self.out.body_writer_assigned = true;
}
if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) {
self.out.rebound.insert(name);
} else {
@@ -579,7 +751,11 @@ impl<'s> Declarations<'s, '_, '_> {
match t.text {
"(" | "[" | "{" => {
let body = t.text == "{" && self.function.take() == Some(self.depth());
let params = t.text == "(" && self.function == Some(self.depth());
self.brackets.open(t, self.acc.limits.nesting);
if params {
self.params = Some((self.depth(), vec![], false));
}
if t.text == "[" {
// After a value, `[` starts a property's name in brackets (ECMA-262 3rd
// edition, section 11.2.1); elsewhere it starts an array literal.
@@ -593,8 +769,17 @@ impl<'s> Declarations<'s, '_, '_> {
if !body {
return;
}
let params = self.params.take();
if self.bodies.len() < self.acc.limits.nesting {
let index = self.out.bodies.len();
if let Some((_, names, full)) = params {
if full {
self.names_full.insert(index);
}
if !names.is_empty() {
self.body_params.insert(index, names);
}
}
self.out.bodies.push((t.start, vec![]));
self.bodies.push(Body {
depth: self.depth(),
@@ -652,10 +837,14 @@ impl<'s> Declarations<'s, '_, '_> {
return;
}
if let Some(body) = self.bodies.last_mut() {
if (var || body.depth == depth) && !body.names.contains(t.text) && self.acc.room(body.names.len()) {
body.names.insert(t.text);
if let Some((_, names)) = self.out.bodies.get_mut(body.index) {
names.push(t.text);
if (var || body.depth == depth) && !body.names.contains(t.text) {
if self.acc.room(body.names.len()) {
body.names.insert(t.text);
if let Some((_, names)) = self.out.bodies.get_mut(body.index) {
names.push(t.text);
}
} else {
self.names_full.insert(body.index);
}
}
} else if function && depth == 0 && !self.out.global.contains(t.text) && self.acc.room(self.out.global.len()) {
+339 -26
View File
@@ -1,6 +1,36 @@
//! The platform features, menu commands and later syntax the analysis recognises.
use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word};
use super::{
Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, exact_unquote, is, member_mark, newer_number, report, unquote, word,
};
/// Words that start or continue a statement or an expression, never a variable's name.
const RESERVED: [&str; 24] = [
"var",
"function",
"if",
"else",
"for",
"while",
"do",
"return",
"new",
"typeof",
"delete",
"in",
"instanceof",
"this",
"with",
"switch",
"case",
"try",
"catch",
"finally",
"throw",
"break",
"continue",
"void",
];
/// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…).
pub(super) fn platform_name(n: &str) -> bool {
@@ -85,6 +115,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
}
self.with_step(t);
self.writer_use(t);
match t.kind {
T::Ident => self.name(t, line),
@@ -292,7 +323,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
// `local['saveAs']`: what the object before the bracket defines, for a call that may follow.
"[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)),
"[" => {
self.index_receiver = self.writer_bits(h0, h1, Some(t.start));
self.index_stable = h0.is_some_and(|r| self.stable(r.text));
}
"(" => self.call(t, line),
// `Name.prototype["+"] = …` defines an operator.
"=" => {
@@ -338,15 +372,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
chain.and_then(|c| c.path.strip_suffix(called))
}
/// `(` after a name: a call.
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
/// What the call whose `(` is the current token reaches.
fn classify_call(&mut self, t: &Sig<'s>, line: Option<usize>) {
let [h0, h1, h2, h3] = self.h;
// `doc['saveAs'](f)`, `doc['exportVariables'](f)` and `app['open'](f)`: a method named by a string literal in brackets.
if is(h0, "]")
&& is(h2, "[")
&& let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
{
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !Self::defines(self.index_receiver, &name))
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !(self.index_stable && Self::defines(self.index_receiver, &name)))
|| (name == catalog::DOM_PRINT && self.document_print("[]()"))
{
self.acc.feature(FeatureId::FileWrite, line);
@@ -388,7 +422,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
{
self.acc.feature(FeatureId::FileRead, line);
} else if (file && catalog::FILE_WRITES.contains(&n))
|| (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n))
|| (catalog::DOM_FILE_WRITES.contains(&n)
&& !(h2.is_some_and(|r| self.stable(r.text)) && Self::defines(self.writer_bits(h2, h3, Some(t.start)), n)))
|| (n == catalog::DOM_PRINT && self.document_print(".print()"))
{
self.acc.feature(FeatureId::FileWrite, line);
@@ -413,6 +448,113 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// Whether a call of `name`'s own method may be left out: the call is in the global code, or in a
/// function body that declares `name` itself. A body that reads `name` from outside may run
/// after the variable was given another value, so its calls are not known. Inside the body of a
/// `with` statement the name may be a property of the statement's object, so no call is known
/// there ([`Analyzer::with_step`]).
fn stable(&self, name: &str) -> bool {
!self.withs_full && self.withs.is_empty() && self.scopes.last().is_none_or(|s| s.saved.contains_key(name))
}
/// Follows the `with` statements around `t`. A body in braces ends with its `}`; a body without
/// braces is taken to last until the block the statement is in closes.
fn with_step(&mut self, t: &Sig<'s>) {
let depth = self.depth();
self.withs.retain(|d| *d <= depth);
match self.with_head {
Some((d, false)) if t.is(")") && depth == d => self.with_head = Some((d, true)),
Some((d, true)) => {
self.with_head = None;
let body = if t.is("{") { depth } else { d };
if self.withs.len() < self.acc.limits.nesting {
self.withs.push(body);
} else {
self.withs_full = true;
}
}
_ => {}
}
if t.kind == T::Ident && t.text == "with" && !member_mark(self.h[0]) {
self.with_head = Some((depth, false));
}
}
/// `name` may have been given another value through the global object: neither the variable
/// nor the outer variables of that name that the open function bodies and `catch` blocks keep
/// to put back hold their literal's methods any longer.
fn forget_writer(&mut self, name: &str) {
self.writers.remove(name);
for s in &mut self.scopes {
if let Some(saved) = s.saved.get_mut(name) {
saved.writer = 0;
}
}
for c in self.catches.iter_mut().filter(|c| c.name == name) {
c.saved.writer = 0;
}
}
/// The global variable `name` read through the global object may be held under another name
/// ([`Self::forget_writer`]). A variable of that name that the innermost function body or a
/// `catch` block declares is another variable, and keeps its literal's methods.
fn forget_global_writer(&mut self, name: &str) {
let shadowed = self.scopes.last().is_some_and(|s| s.saved.contains_key(name)) || self.catches.iter().any(|c| c.name == name);
if !shadowed {
self.forget_writer(name);
return;
}
for s in &mut self.scopes {
if let Some(saved) = s.saved.get_mut(name) {
saved.writer = 0;
}
}
for c in self.catches.iter_mut().filter(|c| c.name == name) {
c.saved.writer = 0;
}
}
/// Any variable may have been given another value through the global object
/// ([`Self::forget_writer`] for every name).
fn forget_writers(&mut self) {
self.writers.clear();
for saved in self.scopes.iter_mut().flat_map(|s| s.saved.values_mut()) {
saved.writer = 0;
}
for c in &mut self.catches {
c.saved.writer = 0;
}
}
/// A function body uses `name`, which no literal has given methods and the body does not declare,
/// in a way that may change or share it ([`Analyzer::shared_early`]). With no room left for the
/// name, no literal's methods are the script's own from then on.
pub(super) fn share_early(&mut self, name: &str) {
self.share_early_as(name, false);
}
/// [`Analyzer::share_early`], and with `global` set, for the global variable `name` read through
/// the global object (`$.global.local`) even when the body declares a variable of that name.
fn share_early_as(&mut self, name: &str, global: bool) {
// A value read just before the `}` that closes a function body is read in that body.
let (open, declared) = match &self.closed_body {
Some((open, names)) => (*open, names.iter().any(|n| n == name)),
None => match self.scopes.last() {
Some(body) => (self.scopes.len(), body.saved.contains_key(name)),
None => return,
},
};
if (declared && !global) || self.writers.contains_key(name) {
return;
}
if self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len()) {
let seen = self.shared_early.entry(name.to_string()).or_insert(open);
*seen = (*seen).max(open);
} else {
self.shared_full = true;
}
}
/// Whether `receiver`, which `before` comes before, is the application object: the name `app`
/// that no `.` comes before and that the script has not declared as its own.
fn app_receiver(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
@@ -430,9 +572,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) {
return 0;
}
// A function body that replaces the method may run before the call, wherever it is in
// the text. The replacement is kept for the body that declares the variable: the
// innermost body around the call that declares it, or the global code.
let looped = at.is_some_and(|at| {
let owner = self.scopes.iter().rev().find(|s| s.saved.get(r.text).is_some_and(|v| v.local)).map(|s| s.start);
self.declared.looped_full
|| self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| {
|| self.declared.method_replaced_any.contains(r.text)
|| self.declared.method_replaced.contains(&(owner, r.text))
|| self.declared.looped.get(&(owner, r.text)).is_some_and(|ids| {
let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at);
next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok())
})
@@ -447,9 +595,39 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
/// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or
/// `exportFile` is assigned: another name may hold its object, or its methods may change, so its
/// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`,
/// `local[k] = w`, `delete local.saveAs`).
/// `local[k] = w`, `delete local.saveAs`). A property assignment whose name is such a variable's
/// (`this.local = d`, `$.global['local'] = d`) may give the variable a new value through the global
/// object, so its methods are no longer known either. An assignment to a property of the global
/// object under any other key (`$.global[key] = d`, `this['lo' + 'cal'] = d`) may give any such
/// variable a new value: no variable's methods are known after it.
fn writer_use(&mut self, t: &Sig<'s>) {
let [h0, h1, h2, h3] = self.h;
let global_index_closed = std::mem::take(&mut self.global_index_closed);
if t.kind == T::Ident
&& is(h0, ".")
&& ((word(h1, "global") && is(h2, ".") && word(h3, "$") && !member_mark(self.h4))
|| ((word(h1, "this") || word(h1, "globalThis")) && !member_mark(h2)))
{
self.global_member = Some(t.start);
}
if t.is("[") {
let global = (word(h0, "global") && is(h1, ".") && word(h2, "$") && !member_mark(h3))
|| ((word(h0, "this") || word(h0, "globalThis")) && !member_mark(h1));
if global && self.global_indexes.len() < self.acc.limits.nesting {
self.global_indexes.push(self.depth());
}
} else if t.is("]") {
let depth = self.depth();
self.global_index_closed = self.global_indexes.last() == Some(&(depth + 1));
self.global_indexes.retain(|d| *d <= depth);
// `$.global['local']` or `this['local']`: the `]` reads the global variable `local`.
if self.global_index_closed
&& is(h1, "[")
&& let Some(key) = h0.filter(|s| s.kind == T::Str)
{
self.global_bracket = Some((t.start, exact_unquote(key.text)));
}
}
let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--"));
let key = t.is(":") && (is(h1, "{") || is(h1, ","));
// `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a
@@ -468,31 +646,166 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.reassigned_global(&name);
}
}
let h4 = self.h4;
// `$.global.local`, `globalThis.local` or `this.local`: `h2` names the global variable `local`.
let global_member = h2.is_some_and(|s| self.global_member == Some(s.start));
let writer = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text);
let escaped = if word(h0, "delete") {
// `delete local…`
writer(Some(*t), h0)
} else if let Some(name) = writer(h0, h1) {
// `local` followed by anything but a member, its own assignment or an object key's `:`.
(!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name)
} else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) {
// `local.saveAs = …`
writer(h2, h3)
} else if is(h0, "[") {
// `local[k]` with a key that is not a string literal.
writer(h1, h2).filter(|_| t.kind != T::Str)
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) {
// `local['name' + k]`.
writer(h2, h3).filter(|_| !t.is("]"))
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
// `local['saveAs'] = …`, not `other.local['saveAs'] = …`.
writer(h3, self.h4)
let escape = |writer: &dyn Fn(Option<Sig<'s>>, Option<Sig<'s>>) -> Option<&'s str>| -> Option<&'s str> {
if word(h0, "delete") {
// `delete local…`
writer(Some(*t), h0)
} else if let Some(name) = writer(h0, h1) {
// `local` followed by anything but a member, its own assignment or an object key's `:`.
(!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name)
} else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) {
// `local.saveAs = …` or `$.global.local.saveAs = …`
writer(h2, if global_member { None } else { h3 })
} else if is(h0, "[") {
// `local[k]` with a key that is not a string literal.
writer(h1, h2).filter(|_| t.kind != T::Str)
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) {
// `local['name' + k]`.
writer(h2, h3).filter(|_| !t.is("]"))
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
// `local['saveAs'] = …`, not `other.local['saveAs'] = …`.
writer(h3, h4)
} else {
None
}
};
let escaped = escape(&writer);
// A function body reads a variable of the enclosing code that no literal has given methods yet
// in a way that changes or shares it: the body may run after the literal, as a hoisted
// declaration does.
let early = if escaped.is_none() && !self.scopes.is_empty() {
let captured = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| {
s.filter(|s| {
s.kind == T::Ident
&& !member_mark(before)
&& !self.writers.contains_key(s.text)
&& self.scopes.last().is_some_and(|b| !b.saved.contains_key(s.text))
})
.map(|s| s.text)
};
escape(&captured)
} else {
None
};
if let Some(name) = escaped {
self.writers.remove(name);
}
if let Some(name) = early {
self.share_early(name);
}
// `$.global['local']` or `this['local']` used as a value (`var alias = $.global['local']`,
// `f(this['local'])`): another name may hold the global variable's object.
if !changes
&& !t.is(".")
&& !t.is("[")
&& let Some((_, name)) = self.global_bracket.as_ref().filter(|(at, _)| h0.is_some_and(|s| s.start == *at))
{
match name.clone() {
Some(name) => {
self.forget_global_writer(&name);
self.share_early_as(&name, true);
}
None => self.forget_writers(),
}
}
// `$.global.local`, `this.local` or `globalThis.local` used as a value (`var alias = this.local`),
// not `holder.local`: another name may hold the global variable's object.
if !changes
&& !t.is(".")
&& !t.is("[")
&& let Some(m) = h0.filter(|s| s.kind == T::Ident && self.global_member == Some(s.start))
{
self.forget_global_writer(m.text);
self.share_early_as(m.text, true);
}
// A document write method of a global variable replaced through a bracket form:
// `$.global['local'].saveAs = …`, `this['local']['saveAs'] = …` or `$.global.local['saveAs'] = …`.
if changes {
let write_key = |s: Option<Sig<'s>>| s.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str()));
let bracketed =
|s: Option<Sig<'s>>| s.and_then(|s| self.global_bracket.as_ref().filter(|(at, _)| *at == s.start).map(|(_, name)| name.clone()));
let global = if is(h1, ".") && h0.is_some_and(|m| m.kind == T::Ident) && write_key(h0) {
bracketed(h2)
} else if is(h0, "]") && is(h2, "[") && h1.is_some_and(|m| m.kind == T::Str) && write_key(h1) {
bracketed(h3).or_else(|| h3.filter(|s| s.kind == T::Ident && self.global_member == Some(s.start)).map(|s| Some(s.text.to_string())))
} else {
None
};
match global {
// The global variable's value may be saved under a body's or a `catch`'s own variable of
// that name, so forget every value of the name.
Some(Some(name)) => {
self.forget_writer(&name);
self.share_early_as(&name, true);
}
// A key that does not decode to one exact name may name any variable.
Some(None) => self.forget_writers(),
None => {}
}
}
// A name read in a function body that the body does not declare, as a receiver or otherwise. A
// receiver is settled once its member is read: assigning a property that is not one of the
// document methods that write a file (`d.n = 1`) leaves its methods as they are.
if let Some(r) = h0.filter(|r| r.kind == T::Ident && !member_mark(h1) && !RESERVED.contains(&r.text) && !t.is(".")) {
self.share_early(r.text);
}
if let Some(r) = h2.filter(|r| is(h1, ".") && r.kind == T::Ident && (!member_mark(h3) || global_member) && !RESERVED.contains(&r.text)) {
let own_property = t.is("=") && h0.is_some_and(|m| m.kind == T::Ident && !catalog::DOM_FILE_WRITES.contains(&m.text));
if !own_property {
self.share_early_as(r.text, global_member);
}
}
if changes {
// A member assignment of a property `local` (`o.local = …`, `o['local'] = …`): the object may
// be the global object (`this`, `globalThis`, `$.global`, or any object holding it, as
// `holder.this`), so the variable of that name may get another value.
let rebound = if is(h1, ".") {
h0.filter(|s| s.kind == T::Ident).map(|s| Some(s.text.to_string()))
} else if is(h0, "]") && is(h2, "[") && h1.is_some_and(|s| s.kind == T::Str) {
h1.filter(|s| s.kind == T::Str).map(|s| exact_unquote(s.text))
} else {
None
};
if let Some(Some(name)) = rebound {
// In a function body: the function may run after a later literal gives the name methods.
if !self.scopes.is_empty() {
self.reassigned_later(&name);
}
self.forget_writer(&name);
} else if global_index_closed || rebound.is_some() {
// `$.global[key] = …`, or a key that does not decode to one exact name: the key may
// name any of them.
self.forget_writers();
}
}
}
/// `(` after a name: a call ([`Self::classify_call`]). A call of a variable of
/// [`Analyzer::writers`]'s method other than the `saveAs` or `exportFile` its literal defines
/// (`local.install()`, `local['install']()`) may replace the object's methods through `this`, so
/// after the call they are no longer known.
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
let [h0, h1, h2, h3] = self.h;
let bits = self.writer_bits(h2, h3, None);
let receiver = if is(h1, ".") && bits != 0 && h0.is_some_and(|s| s.kind == T::Ident && !Self::defines(bits, s.text)) {
h2
} else if is(h0, "]")
&& is(h2, "[")
&& self.index_receiver != 0
&& h1.is_some_and(|s| s.kind == T::Str && !Self::defines(self.index_receiver, &unquote(s.text, 32)))
{
h3
} else {
None
};
self.classify_call(t, line);
if let Some(r) = receiver {
self.writers.remove(r.text);
}
}
/// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called.
+28
View File
@@ -135,6 +135,34 @@ pub(super) fn newer_number(text: &str) -> bool {
text.contains('_') || (b.len() > 1 && b.last() == Some(&b'n')) || matches!((b.first(), b.get(1)), (Some(b'0'), Some(b'b' | b'B' | b'o' | b'O')))
}
/// A string literal's whole value ([`unquote`] without a length limit), or `None` when an escape
/// does not decode to exactly one character: a `\x` without two hex digits, a `\u` without four
/// (`\u{63}` included), or a code unit that is not a character on its own.
pub(super) fn exact_unquote(text: &str) -> Option<String> {
let b = text.as_bytes();
let mut i = 0;
while i < b.len() {
if b[i] == b'\\' {
let digits = match b.get(i + 1) {
Some(b'x') => 2,
Some(b'u') => 4,
_ => 0,
};
if digits > 0 {
let hex = b.get(i + 2..i + 2 + digits).filter(|d| d.iter().all(u8::is_ascii_hexdigit))?;
// A surrogate code unit (`\uD800` to `\uDFFF`) is not a character on its own.
if digits == 4 && matches!(hex[0], b'd' | b'D') && matches!(hex[1], b'8'..=b'9' | b'a'..=b'f' | b'A'..=b'F') {
return None;
}
}
i += 2;
} else {
i += 1;
}
}
Some(unquote(text, text.chars().count()))
}
/// A string literal's value, its quotes removed and its escapes undone (`\n`, `\xHH`, `\uHHHH`,
/// octal escapes, a backslash before a line break), up to `max` characters.
pub(super) fn unquote(text: &str, max: usize) -> String {
+4 -2
View File
@@ -76,8 +76,10 @@ pub(crate) const REFLECT: &str = "reflect";
// The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/
pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"];
// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/
pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "imageCapture", "saveAs"];
// Document methods that write the file they are given, or files in the folder they are given:
// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and
// https://www.indesignjs.de/indesignapi/illustrator/Document.html (exportForScreens)
pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "imageCapture", "saveAs", "exportForScreens"];
// Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/
pub(crate) const DOM_FILE_READS: &[&str] = &["open"];
+650
View File
@@ -19,6 +19,20 @@ fn feature<'r>(r: &'r Report, id: &str) -> Option<&'r Feature> {
r.features.iter().find(|f| f.id == id)
}
#[test]
fn save_changes_text_requires_enumeration_member_context() {
for source in ["vc.log('SAVECHANGES');", "var text = 'SAVECHANGES';", "other['SAVECHANGES'];"] {
let r = report(source);
assert!(feature(&r, "file.write").is_none(), "{source}");
assert!(!r.outside.iter().any(|outside| outside.id == "filesWritten"), "{source}");
}
for source in ["SaveOptions['SAVECHANGES'];", "'SaveOptions.SAVECHANGES';"] {
let r = report(source);
assert!(feature(&r, "file.write").is_some(), "{source}");
assert!(r.outside.iter().any(|outside| outside.id == "filesWritten"), "{source}");
}
}
fn problems(r: &Report) -> Vec<(&'static str, Option<usize>, Option<&str>)> {
r.problems.iter().map(|p| (p.code, p.line, p.detail.as_deref())).collect()
}
@@ -588,6 +602,21 @@ fn export_variables_in_brackets_writes_a_file() {
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
}
/// A document's `exportForScreens` writes files into the folder it is given, called directly or by
/// its name in brackets; an object of the script's own that defines it writes nothing.
#[test]
fn export_for_screens_writes_files() {
let r = report(concat!(
"var dir = new Folder(p);\n",
"app.activeDocument.exportForScreens(dir, ExportForScreensType.SE_PNG24);\n",
"documents[0]['exportForScreens'](dir, ExportForScreensType.SE_SVG);\n",
"var local = {exportForScreens: function () {}};\n",
"local.exportForScreens(dir);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[2, 3][..])]);
}
#[test]
fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() {
for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] {
@@ -912,6 +941,627 @@ fn labels_hidden_globals_and_other_objects_keep_writes_known() {
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17, 20][..]));
}
/// A call of another method of such an object may replace its `saveAs` through `this`, and a property
/// assignment that names the variable (`this.local = d`) may give it another value through the global
/// object: after either, its `saveAs` writes the file again.
#[test]
fn a_method_call_or_a_global_property_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}, install: function () { this.saveAs = app.activeDocument.saveAs; }};\n",
"var b = {saveAs: function () {}, install: function () {}};\n",
"var c = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
"a.saveAs(f); a.install();\n",
"b['install']();\n",
"this.c = app.activeDocument;\n",
"$.global['e'] = app.activeDocument;\n",
"g.saveAs(f); g.saveAs(f);\n",
"a.saveAs(f);\n",
"b.saveAs(f);\n",
"c.saveAs(f);\n",
"e.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13][..]));
}
/// An assignment to a property under a key that is not one string literal may give any such variable
/// another value through the global object, so every `saveAs` of such a variable writes the file,
/// before the assignment too.
#[test]
fn a_computed_global_property_ends_every_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
"var rows = [];\n",
"rows[k] = 1; $.global['b'] = app.activeDocument;\n",
"a.saveAs(f);\n",
"$.global[key] = app.activeDocument;\n",
"a.saveAs(f);\n",
"var c = {saveAs: function () {}};\n",
"this['lo' + 'cal'] = app.activeDocument;\n",
"c.saveAs(f);\n",
"var h = {saveAs: function () {}};\n",
"globalThis[names[0]] = app.activeDocument;\n",
"h.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 7, 10, 13][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 7, 10, 13][..])]);
}
/// A `saveAs` whose body uses `this` or the variable's own name may replace the object's methods
/// when it runs, so it is not the script's own and its calls write the file. A `this` in another
/// method's body leaves `saveAs` the script's own.
#[test]
fn an_own_save_as_that_may_replace_itself_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var doc = app.activeDocument;\n",
"var a = {saveAs: function () { this.saveAs = function (g) { doc.saveAs(g); }; }};\n",
"var b = {saveAs: function () { b.saveAs = w; }};\n",
"var c = {saveAs: function (g) { return g; }, install: function () { this.n = 1; }};\n",
"a.saveAs(f);\n",
"a.saveAs(f);\n",
"b.saveAs(f);\n",
"c.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 6, 7, 8][..]));
}
/// A loop that replaces a variable's `saveAs` (`local.saveAs = …`, `local['saveAs'] = …`) may run a
/// call of it before the replacement in the text on a later pass: the call writes a file. A loop
/// that only calls the method, or replaces it on another object, leaves it the script's own.
#[test]
fn an_own_save_as_replaced_later_in_a_loop_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"for (;;) { local.saveAs(f); local.saveAs = g; }\n",
"var other = {saveAs: function () {}};\n",
"while (n--) { other.saveAs(f); other['saveAs'] = g; }\n",
"var calm = {saveAs: function () {}};\n",
"for (;;) { calm.saveAs(f); holder.calm.saveAs = g; }\n",
"for (;;) { calm.saveAs(f); }\n",
"for (;;) { calm.saveAs(f); holder.calm['saveAs'] = g; }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..]));
}
/// A function declared after a call is hoisted, so it may replace the variable's `saveAs` before the
/// call runs: the call writes a file. A function that only calls the method, or replaces it on a
/// variable of its own, leaves it the script's own.
#[test]
fn a_hoisted_function_declared_later_that_replaces_the_method_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"install();\n",
"function install() { local.saveAs = app.activeDocument.saveAs; }\n",
"var other = {saveAs: function () {}};\n",
"other.saveAs(f);\n",
"function swap(w) { other['saveAs'] = w; }\n",
"var calm = {saveAs: function () {}};\n",
"calm.saveAs(f);\n",
"function d() { calm.saveAs(f); }\n",
"function e() { var calm = {}; calm.saveAs = 1; }\n",
"var third = {saveAs: function () {}};\n",
"third.saveAs(f);\n",
"function h(w) { third['save\\x41s'] = w; }\n",
"function run() {\n",
" var mine = {saveAs: function () {}};\n",
" fix(); mine.saveAs(f);\n",
" function fix() { mine.saveAs = app.activeDocument.saveAs; }\n",
"}\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 7, 11, 14, 18][..]));
}
/// A hoisted function declared after a call may also replace the variable's `saveAs` under a key
/// the check can't read (`local[k] = w`, `local['sa' + 've' + 'As'] = w`), with a compound or update
/// operator (`local.saveAs += w`, `local['saveAs']++`, `++local.saveAs`), or through another name
/// that holds the object (`var y = local; y.saveAs = w`, `give(local)`): the call writes a file. The
/// same holds in a loop, where the replacement may run before the call on a later pass.
#[test]
fn a_method_replaced_by_a_computed_key_an_operator_or_an_alias_ends_the_own_save_as() {
let head = "var f = new File(p);\nvar local = {saveAs: function () {}};\n";
let mut wrong = vec![];
for (tail, lines) in [
("local.saveAs(f);\nfunction h(w, k) { local[k] = w; }\n", &[3][..]),
("local.saveAs(f);\nfunction h(w) { local['sa' + 've' + 'As'] = w; }\n", &[3]),
("local.saveAs(f);\nfunction h(w) { local.saveAs += w; }\n", &[3]),
("local.saveAs(f);\nfunction h() { local['saveAs']++; }\n", &[3]),
("local.saveAs(f);\nfunction h() { local.saveAs--; }\n", &[3]),
("local.saveAs(f);\nfunction h() { ++local.saveAs; }\n", &[3]),
("local.saveAs(f);\nfunction h(w) { var y = local; y.saveAs = w; }\n", &[3]),
("local.saveAs(f);\nfunction h() { give(local); }\n", &[3]),
("for (;;) { local.saveAs(f); local[k] = w; }\n", &[3]),
("for (;;) { local.saveAs(f); local.saveAs += w; }\n", &[3]),
("for (;;) { local.saveAs(f); var z = local; }\n", &[3]),
("local.saveAs(f);\nfunction h() { local.saveAs(f); local['name'] = 1; }\n", &[4]),
("local.saveAs(f);\nfunction h() { return local[0]; }\n", &[]),
] {
let r = report(&format!("{head}{tail}"));
if feature(&r, "file.write").map_or(&[][..], |f| f.lines.as_slice()) != lines || r.truncated {
wrong.push((tail, feature(&r, "file.write").map(|f| f.lines.clone())));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// A function that replaces a variable's `saveAs` may stand before the `var` statement that declares
/// the variable in the body around it, since `var` declares the name for the whole body: the call
/// after the literal writes a file. A function whose own later `var` declares the name replaces
/// the method on its own variable, which leaves the outer one the script's own.
#[test]
fn a_method_replaced_before_the_hoisted_var_that_declares_it_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function run() {\n",
" function fix() { give(mine); }\n",
" var mine = {saveAs: function () {}};\n",
" mine.saveAs(f);\n",
"}\n",
"function late() {\n",
" mine2 = {saveAs: function () {}};\n",
" mine2.saveAs(f);\n",
" function fix() { give(mine2); }\n",
" var mine2;\n",
"}\n",
"function deep() {\n",
" held = {saveAs: function () {}};\n",
" held.saveAs(f);\n",
" function a() { function b() { held.saveAs = w; } }\n",
" var held;\n",
"}\n",
"function calm() {\n",
" var quiet = {saveAs: function () {}};\n",
" function g(w) { give(quiet); var quiet; }\n",
" quiet.saveAs(f);\n",
"}\n",
"function own() {\n",
" give(mine3);\n",
" var mine3 = {saveAs: function () {}};\n",
" mine3.saveAs(f);\n",
"}\n",
"function par() {\n",
" function fix(mine4) { mine4.saveAs = w; }\n",
" var mine4 = {saveAs: function () {}};\n",
" mine4.saveAs(f);\n",
"}\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"function h(a, local) { return local; }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 9, 15][..]));
}
/// A call inside a nested function on a variable of the body around it, whose `saveAs` another
/// function replaces, writes a file: the replacement is looked up for the body that declares the
/// variable, not for the innermost body.
#[test]
fn a_call_in_a_nested_function_on_a_replaced_outer_variable_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"function run() {\n",
" var mine = {saveAs: function () {}};\n",
" function use() { mine.saveAs(f); }\n",
" function fix(w) { give(mine); }\n",
"}\n",
"var top = {saveAs: function () {}};\n",
"function use2() { var other = 1; top.saveAs(f); }\n",
"function fix2(w) { give(top); }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 8][..]));
}
/// A global variable read through the global object as a value (`$.global.local`, `this.local`,
/// `globalThis.local`) may be held under another name, also by a hoisted function declared before
/// the literal: the variable's `saveAs` writes a file.
#[test]
fn a_global_member_used_as_a_value_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function a() { var alias = $.global.local; alias.saveAs = app.activeDocument.saveAs; }\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"var other = {saveAs: function () {}};\n",
"var held = this.other;\n",
"other.saveAs(f);\n",
"function b() { use(globalThis.third); }\n",
"var third = {saveAs: function () {}};\n",
"third.saveAs(f);\n",
"var calm = {saveAs: function () {}};\n",
"use(holder.calm);\n",
"calm.saveAs(f);\n",
"function g() { var mine = {saveAs: function () {}}; var alias = $.global.mine; mine.saveAs(f); }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10][..]));
}
/// A function declared before the literal is hoisted, so it may change or share the variable before
/// the literal's later calls run: its calls then keep reporting the write. A function with a
/// variable of its own of the same name, and one that only calls the method, leave the method the
/// script's own.
#[test]
fn a_hoisted_function_that_changes_or_shares_the_variable_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function a(w) { local.saveAs = w; }\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"function b() { use(other); }\n",
"var other = {saveAs: function () {}};\n",
"other.saveAs(f);\n",
"function c() { var calm = app.activeDocument; use(calm); }\n",
"var calm = {saveAs: function () {}};\n",
"calm.saveAs(f);\n",
"function d() { quiet.saveAs(f); }\n",
"var quiet = {saveAs: function () {}};\n",
"quiet.saveAs(f);\n",
"function g1() { use(mine); }\n",
"function g2() { var mine = {saveAs: function () {}}; mine.saveAs(f); }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 11, 13][..]));
}
/// A function body that declares the variable's name itself can still give the variable another
/// value through the global object: the variable's methods are not put back when the body closes.
/// A body that only declares the name leaves the methods the script's own.
#[test]
fn a_global_assignment_under_a_shadowing_declaration_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"function replace() { var local = 1; $.global.local = app.activeDocument; }\n",
"replace();\n",
"local.saveAs(f);\n",
"var calm = {saveAs: function () {}};\n",
"function keep() { var calm = 1; }\n",
"keep();\n",
"calm.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5][..]));
}
/// An assignment under a computed key of the global object may give any variable another value, so
/// after one anywhere in the file every call is reported.
#[test]
fn a_computed_global_assignment_ends_every_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"var other = {saveAs: function () {}};\n",
"function any() { var other = 1; $.global[k] = app.activeDocument; }\n",
"any();\n",
"other.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5][..]));
}
/// A function declared before the literal may run after it and give the variable another value
/// through any form of a global object property: `$.global.name`, `globalThis.name` and
/// `$.global['name']`. The literal's later calls keep reporting the write. An assignment in the
/// global code runs once, before a later literal, and leaves that literal's methods the script's own.
#[test]
fn a_hoisted_global_property_assignment_ends_a_later_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function replace() { $.global.local = app.activeDocument; }\n",
"var local = {saveAs: function () {}};\n",
"replace();\n",
"local.saveAs(f);\n",
"function swap() { globalThis.other = app.activeDocument; }\n",
"var other = {saveAs: function () {}};\n",
"swap();\n",
"other.saveAs(f);\n",
"function put() { $.global['third'] = app.activeDocument; }\n",
"var third = {saveAs: function () {}};\n",
"put();\n",
"third.saveAs(f);\n",
"$.global.fresh = 1;\n",
"var fresh = {saveAs: function () {}};\n",
"fresh.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 9, 13][..]));
}
/// Inside the body of a `with` statement a name may be a property of the statement's object, so a
/// call of a literal's method there is reported. A `with` statement also gives names values the
/// check does not read, so the calls after its body are reported too.
#[test]
fn a_call_inside_a_with_body_is_not_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"with ({local: app.activeDocument}) {\n",
" local.saveAs(f);\n",
"}\n",
"local.saveAs(f);\n",
"if (x) { with (o) local.saveAs(f); }\n",
"local.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6, 7, 8][..]));
}
/// A table of shared names with no room left for one more means a function may share any name: no
/// literal after it gives methods that are the script's own.
#[test]
fn a_full_table_of_shared_names_keeps_reporting_the_write() {
let src = concat!(
"var f = new File(p);\n",
"function a(w) { p1.saveAs = w; p2.saveAs = w; p3.saveAs = w; }\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
);
let r = check("test.jsx", src.as_bytes(), None, &Limits { entries: 2, ..Limits::default() });
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..]));
}
/// A function body that assigns a variable it does not declare (`=`, a compound operator, `++` or
/// `--`) may run after the literal and give the variable another value.
#[test]
fn an_assignment_in_a_hoisted_function_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function a(w) { local = w; }\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"function b() { other += 1; }\n",
"var other = {saveAs: function () {}};\n",
"other.saveAs(f);\n",
"function c() { third++; }\n",
"var third = {saveAs: function () {}};\n",
"third.saveAs(f);\n",
"function e() { --fourth; }\n",
"var fourth = {saveAs: function () {}};\n",
"fourth.saveAs(f);\n",
"function d() { var mine = 1; mine = 2; }\n",
"var mine = {saveAs: function () {}};\n",
"mine.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10, 13][..]));
}
/// A function body that calls a method of, or reads, a variable it does not declare may run before
/// the literal as well, so a later literal's calls keep reporting the write.
#[test]
fn a_member_call_or_read_in_a_hoisted_function_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function a() { local.run(); }\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"function b() { other['m'](); }\n",
"var other = {saveAs: function () {}};\n",
"other.saveAs(f);\n",
"function c() { return third.name; }\n",
"var third = {saveAs: function () {}};\n",
"third.saveAs(f);\n",
"function d() { var calm = 1; return calm.name; }\n",
"var calm = {saveAs: function () {}};\n",
"calm.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10][..]));
}
/// A function that reads the variable from outside runs after whatever the script gave it since, so
/// its calls keep reporting the write. A `var` after a label or a `case` is in a branch as well.
#[test]
fn a_captured_or_labelled_own_save_as_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"function run() { local.saveAs(f); }\n",
"function run2() { local['saveAs'](f); }\n",
"local = app.activeDocument;\n",
"run();\n",
"function own() { var inner = {saveAs: function () {}}; inner.saveAs(f); inner['saveAs'](f); }\n",
"if (flag) skip:\n",
"var lab = {saveAs: function () {}};\n",
"lab.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4, 10][..]));
}
/// A property assignment in a loop may give the global variable of that name another value on the
/// next pass, so a call on it in the same loop may write a file.
#[test]
fn a_property_assignment_in_a_loop_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"for (var i = 0; i < 2; i++) {\n",
" local.saveAs(f);\n",
" $.global.local = app.activeDocument;\n",
"}\n",
"var other = {saveAs: function () {}};\n",
"for (var j = 0; j < 2; j++) {\n",
" other.saveAs(f);\n",
" $.global['other'] = app.activeDocument;\n",
"}\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 9][..]));
// The property names the global variable, not a function's own variable of the same name.
let r = report(concat!(
"var f = new File(p);\n",
"function g() {\n",
" var local = {saveAs: function () {}};\n",
" for (var i = 0; i < 2; i++) { local.saveAs(f); $.global.local = app.activeDocument; }\n",
"}\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), None);
// A key with an escape may name the variable.
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"for (var i = 0; i < 2; i++) { local.saveAs(f); $.global['lo\\u0063al'] = app.activeDocument; }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
// Hex escapes and a line continuation in the key.
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"for (var i = 0; i < 2; i++) { local.saveAs(f); this['lo\\x63\\\n",
"al'] = app.activeDocument; }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
// A key longer than 256 characters names the variable of that whole name.
let long = "v".repeat(300);
let r = report(&format!(
"var f = new File(p);\nvar {long} = {{saveAs: function () {{}}}};\nfor (var i = 0; i < 2; i++) {{ {long}.saveAs(f); $.global['{long}'] = app.activeDocument; }}\n"
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
let r = report(&format!("var f = new File(p);\nvar {long} = {{saveAs: function () {{}}}};\n$.global['{long}'].saveAs = w;\n{long}.saveAs(f);\n"));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..]));
// A key whose escape does not decode to one exact name may name any variable.
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"this['lo\\u{63}al'] = app.activeDocument;\n",
"local.saveAs(f);\n",
"var kept = {saveAs: function () {}};\n",
"$.global['k\\uD800'].saveAs = w;\n",
"kept.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..]));
}
/// A function that replaces a method through the global object's property (`$.global.local.saveAs`)
/// changes the variable's methods, as `local.saveAs = …` does.
#[test]
fn a_method_replaced_through_the_global_object_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function install() {\n",
" $.global.local.saveAs = function (f) {\n",
" app.activeDocument.saveAs(f);\n",
" };\n",
"}\n",
"var local = {saveAs: function () {}};\n",
"install();\n",
"local.saveAs(f);\n",
"var mine = {saveAs: function () {}};\n",
"globalThis.mine.saveAs = w;\n",
"mine.saveAs(f);\n",
"function install2() { var kept; $.global.kept.saveAs = w; }\n",
"var kept = {saveAs: function () {}};\n",
"install2();\n",
"kept.saveAs(f);\n",
"var safe = {saveAs: function () {}};\n",
"holder.global.safe.saveAs = w;\n",
"safe.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 9, 12, 16][..]));
}
/// Bracket forms of the global object's property (`$.global['local'].saveAs`, `this['local'].saveAs`,
/// `$.global.local['saveAs']`) change the variable's methods, as the dot forms do.
#[test]
fn a_method_replaced_through_a_bracketed_global_member_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function install() {\n",
" $.global['local'].saveAs = function (f) {\n",
" app.activeDocument.saveAs(f);\n",
" };\n",
"}\n",
"var local = {saveAs: function () {}};\n",
"install();\n",
"local.saveAs(f);\n",
"var mine = {saveAs: function () {}};\n",
"this['mine'].saveAs = w;\n",
"mine.saveAs(f);\n",
"var third = {saveAs: function () {}};\n",
"$.global.third['saveAs'] = w;\n",
"third.saveAs(f);\n",
"var fourth = {saveAs: function () {}};\n",
"globalThis['fourth']['saveAs'] = w;\n",
"fourth.saveAs(f);\n",
"var safe = {saveAs: function () {}};\n",
"holder.global['safe'].saveAs = w;\n",
"safe.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 9, 12, 15, 18][..]));
// A body's own variable of the same name does not keep the global variable's methods.
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"function g() { var local = {saveAs: function () {}}; $.global['local'].saveAs = w; }\n",
"g();\n",
"local.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5][..]));
}
/// A bracketed read of the global variable used as a value (`var alias = $.global['local']`) shares
/// its object, so a later literal's `saveAs` is not the script's own.
#[test]
fn a_bracketed_global_member_used_as_a_value_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function install() {\n",
" var alias = $.global['local'];\n",
" alias.saveAs = function (f) {\n",
" app.activeDocument.saveAs(f);\n",
" };\n",
"}\n",
"var local = {saveAs: function () {}};\n",
"install();\n",
"local.saveAs(f);\n",
"var safe = {saveAs: function () {}};\n",
"var other = holder['safe'];\n",
"safe.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 10][..]));
}
/// A hoisted function body whose last value, read without a `;` before its closing `}`, is the
/// variable shares it with its caller, as one that ends with `;` does.
#[test]
fn a_variable_read_just_before_a_function_body_closes_ends_the_own_save_as() {
for read in ["$.global['local']", "$.global.local", "this.local", "local"] {
let r = report(&format!(
concat!(
"var f = new File(p);\n",
"function get() {{ return {} }}\n",
"var local = {{saveAs: function () {{}}}};\n",
"get().saveAs = function (f) {{\n",
" app.activeDocument.saveAs(f);\n",
"}};\n",
"local.saveAs(f);\n",
),
read
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 7][..]), "{read}");
}
}
/// `$.global.local.saveAs = …` in a function whose parameter is named `local` replaces the global
/// variable's method; the parameter alone leaves the outer literal's `saveAs` the script's own.
#[test]
fn a_dot_global_method_assignment_under_a_parameter_shadow_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"function install(local) {\n",
" $.global.local.saveAs = function (f) {\n",
" app.activeDocument.saveAs(f);\n",
" };\n",
"}\n",
"install(null);\n",
"local.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 9][..]));
let r = report(concat!(
"var f = new File(p);\n",
"function install(local) { local.n = 1; }\n",
"var local = {saveAs: function () {}};\n",
"install({});\n",
"local.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), None);
}
/// Only a `var` statement directly in a function body or the global code that gives its first name
/// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the
/// statement. A literal given in a branch, one the value goes on from, one given by an assignment
+5 -2
View File
@@ -2,7 +2,10 @@
//! Document Health Check on the selection, or the document while nothing is selected, lists what it
//! found, and shows or fixes the issues picked in the list (Fix All: every issue listed), each fix
//! one undo step. Below, the add-on's one-click tools open their options as their menu items do,
//! and its text tools, which the panel can hide, act on the selected type.
//! and its text tools, which the panel can hide, act on the selected type. Release All
//! Containers… opens its own dialog ([`release`]).
pub mod release;
use craft::behavior::{DisplayOrder, ItemSource, Selection};
use craft::keymap::Mods;
@@ -98,7 +101,7 @@ fn modified(id: &str, mut p: Value, held: Mods) -> Value {
pub fn menu() -> Vec<Node> {
let mut items = vec![cp("Document Health Check", "window.panel", json!({ "panel": ID })), Sep];
items.extend(tools().into_iter().map(|(label, id, p)| cp(label, id, p)));
items.extend([Sep, c("Fix All Issues", "addon.cleanup.fix"), Sep]);
items.extend([c("Release All Containers…", release::COMMAND), Sep, c("Fix All Issues", "addon.cleanup.fix"), Sep]);
let by = |b: &str| json!({ "by": b });
let align = |a: &str| json!({ "align": a });
items.extend([
@@ -0,0 +1,57 @@
//! Release All Containers in the interface: its dialog (where to release, the selection or the
//! whole document, and which containers: groups, clipping masks and compound paths), which
//! previews on the canvas and runs `addon.cleanup.releaseAll` on OK, one undo step. It opens on the
//! selection, or the document while nothing is selected, with every kind ticked.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind};
use serde_json::{Value, json};
use crate::VectorcraftApp;
use crate::addons::dialogs::{self, Spec};
use crate::dialogs::form;
/// The command.
pub const COMMAND: &str = "addon.cleanup.releaseAll";
/// Where it releases, as the command's `scope` names it, and the labels.
const SCOPES: [(&str, &str); 2] = [("selection", "Selection"), ("document", "Document")];
/// The kinds of container, as the command names them, and their labels.
const KINDS: [(&str, &str); 3] = [("groups", "Groups"), ("clipGroups", "Clipping Masks"), ("compoundPaths", "Compound Paths")];
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
/// The dialog's rows.
fn rows() -> Vec<Param> {
let scopes = SCOPES.iter().map(|&(id, label)| (id.to_string(), tl!(label).into())).collect();
let mut rows = vec![Param::new("scope", tl!("Release In:"), ParamKind::choice(scopes, Some(SCOPES[0].0.into())))];
rows.extend(KINDS.iter().map(|&(key, label)| Param::new(key, tl!(label), ParamKind::bool(true))));
rows
}
/// The command's parameters from the dialog's fields.
pub(crate) fn params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&rows(), fields))
}
/// Opens the dialog on the selection, or the document while nothing is selected, with every kind
/// of container ticked.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let selected = !app.session.active().ok_or("no document open")?.selection.is_empty();
let scope = if selected { "selection" } else { "document" };
let opening = json!({ "scope": scope, "groups": true, "clipGroups": true, "compoundPaths": true });
let fields = form::fields_of(&rows(), opening.as_object().ok_or("no options")?);
dialogs::open(app, &SPEC, fields, move |fields| {
let any = KINDS.iter().any(|(key, _)| fields.bool(key).unwrap_or(true));
let somewhere = selected || fields.text("scope") != Some("selection");
let reason = if any { tl!("Nothing is selected.") } else { tl!("Tick at least one kind of container.") };
ParamDialog::new(COMMAND, tl!("Release All Containers"), rows())
.previews(true)
.ok_enabled(any && somewhere)
.ok_reason(reason.into())
.values(Bind::bound(fields))
})
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,99 @@
use serde_json::json;
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_engine::Session;
use crate::VectorcraftApp;
use crate::addons::dialogs::tests as host;
use crate::tests::panel_harness::Panel as Harness;
/// An app with a window and a selected group holding a rectangle and a compound path of two; the
/// group, the rectangle and the compound path.
fn app() -> (VectorcraftApp, NodeId, NodeId, NodeId) {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
let (a, p, q) = (rect(10), rect(50), rect(55));
app.run("select.set", json!({"ids": [p.0, q.0]})).unwrap();
let holes = NodeId(app.run("object.compoundPath.make", json!({})).unwrap()["id"].as_u64().unwrap());
app.run("select.set", json!({"ids": [a.0, holes.0]})).unwrap();
let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap());
(app, group, a, holes)
}
/// The objects directly in the first layer.
fn top(app: &VectorcraftApp) -> Vec<NodeId> {
app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
fn undo_len(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().history.undo.len()
}
#[test]
fn release_all_previews_keyboard_choices_cancels_and_commits_one_step() {
let (app, group, a, holes) = app();
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
let undo = undo_len(&panel.app());
host::open_item(&mut panel.app(), "Artwork Cleanup", "Release All Containers…");
panel.frame();
let id = host::dialog_id(&panel.app());
assert_eq!(host::read(&panel.app(), id, |f| f.text("scope").map(str::to_string)), Some("selection".into()), "opens on the selection");
assert_eq!(top(&panel.app()).len(), 3, "the preview shows the rectangle and the compound path's two paths");
// Compound Paths unticked with the keyboard: the compound path stays in the preview.
panel.focus("Compound Paths");
panel.key(egui::Key::Space, egui::Modifiers::NONE);
panel.frame();
assert_eq!(host::read(&panel.app(), id, |f| f.bool("compoundPaths")), Some(false));
assert_eq!(top(&panel.app()), [a, holes], "the group is released and the compound path stays");
panel.click("Cancel");
panel.frame();
assert_eq!(top(&panel.app()), [group], "rolled back");
assert_eq!(undo_len(&panel.app()), undo);
host::open_item(&mut panel.app(), "Artwork Cleanup", "Release All Containers…");
panel.frame();
panel.click("OK");
panel.frame();
let app = panel.app();
assert!(!app.any_dialog_open());
assert_eq!(undo_len(&app), undo + 1, "one undo step");
let left = top(&app);
assert_eq!(left.len(), 3);
let doc = &app.session.doc().unwrap().doc;
assert!(left.iter().all(|id| matches!(doc.node(*id).unwrap().kind, NodeKind::Path { .. })), "only paths are left");
}
#[test]
fn release_all_turns_ok_off_with_nothing_to_release_in() {
let (app, group, ..) = app();
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
host::open_item(&mut panel.app(), "Artwork Cleanup", "Release All Containers…");
panel.frame();
for label in ["Groups", "Clipping Masks", "Compound Paths"] {
panel.focus(label);
panel.key(egui::Key::Space, egui::Modifiers::NONE);
panel.frame();
}
assert!(!panel.enabled("OK"), "no kind of container ticked");
assert_eq!(top(&panel.app()), [group], "nothing previewed");
panel.focus("Groups");
panel.key(egui::Key::Space, egui::Modifiers::NONE);
panel.frame();
assert!(panel.enabled("OK"));
panel.click("Cancel");
panel.frame();
// With nothing selected, it opens on the document, and Selection turns OK off.
panel.app().run("select.set", json!({"ids": []})).unwrap();
host::open_item(&mut panel.app(), "Artwork Cleanup", "Release All Containers…");
panel.frame();
let id = host::dialog_id(&panel.app());
assert_eq!(host::read(&panel.app(), id, |f| f.text("scope").map(str::to_string)), Some("document".into()));
assert!(panel.enabled("OK"));
host::set(&panel.app(), id, "scope", json!("selection"));
panel.frame();
assert!(!panel.enabled("OK"), "nothing is selected");
host::set(&panel.app(), id, "scope", json!("document"));
panel.frame();
panel.click("OK");
panel.frame();
assert_eq!(top(&panel.app()).len(), 3, "the document's containers are released");
}
+2 -1
View File
@@ -110,8 +110,9 @@ pub(crate) fn open(
/// The dialog the menu item of command `id` opens, with no params; `None` for another command.
pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, String>> {
use super::{color, document, pathtools, select, typetools};
use super::{cleanup, color, document, pathtools, select, typetools};
let open: fn(&mut VectorcraftApp) -> Result<Value, String> = match id {
cleanup::release::COMMAND => cleanup::release::open,
document::FLOOD_FILL => document::open_flood_fill,
pathtools::set_corners::COMMAND => pathtools::set_corners::open,
pathtools::dashes::COMMAND => pathtools::dashes::open,
+6
View File
@@ -215,6 +215,9 @@ impl VectorcraftApp {
run_count: 0,
channel: None,
deferred_control: None,
held_set: None,
held_before: crate::control::Hiding::default(),
held_confirms: Vec::new(),
control_rotate_press: None,
pointer_waits: Vec::new(),
context: 0,
@@ -849,6 +852,9 @@ impl VectorcraftApp {
panel_docking::close_overlays_for_modal(self, &ctx);
let drawn_document = self.session.active().map(|st| (st.uid, st.revision));
dialogs::host::pump(self, &ctx);
// The pump answered the held OKs it could: the confirms waiting on them reply before the next pass's shell
// closes an accepted dialog.
self.poll_held();
// The canvas has already painted. A dialog can apply or roll back its preview
// on the final input frame, with no further mouse movement to wake the window.
if self.session.active().map(|st| (st.uid, st.revision)) != drawn_document {
+48 -5
View File
@@ -82,14 +82,15 @@ impl VectorcraftApp {
};
let document = self.document_identity();
let now = self.instant();
if let Some(channel) = self.channel.as_mut() {
channel.settle_at(req, reply, document, settle, now);
}
self.settle_control(req, reply, document, settle, now);
}
// A request above may have closed a dialog whose held OK a confirm waits on.
self.poll_held();
// A capture is issued only after passes settle it, and an idle window runs none; a hidden
// one runs only this logic unless asked to paint. Its readback finishes only in a later frame,
// so frames keep coming until it is answered, as production's did.
if self.channel.as_ref().is_some_and(|channel| channel.captures.any_pending()) {
// so frames keep coming until it is answered, as production's did. The app answers a held OK
// only in a pass that pumps the dialogs, so frames also keep coming while a confirm waits on one.
if self.channel.as_ref().is_some_and(|channel| channel.captures.any_pending()) || !self.held_confirms.is_empty() {
if self.viewport_hidden(ctx) {
host.paint_while_hidden();
}
@@ -124,6 +125,48 @@ impl VectorcraftApp {
}
}
/// Hands the reply to `req` to the control channel ([`ControlChannel::settle_at`]). The app holds the reply of a
/// confirm that waits for its answer to a dialog's held OK ([`craft::automation::Reply::AfterHeldOk`],
/// [`control::HeldConfirm`]), and [`Self::poll_held`] sends it.
pub(crate) fn settle_control(
&mut self,
mut req: craft::automation::ControlRequest,
reply: craft::automation::Reply,
document: Option<DocumentId>,
settle: f64,
now: craft::ui::runtime::motion::Instant,
) {
let held_set = self.held_set.take();
let before = std::mem::take(&mut self.held_before);
let Some(channel) = self.channel.as_mut() else { return };
if matches!(reply, craft::automation::Reply::AfterHeldOk { .. }) {
self.held_confirms.push(control::HeldConfirm::hold(&mut req, held_set, before));
}
channel.settle_at(req, reply, document, settle, now);
}
/// Answers the `ui.dialog.confirm` replies held on a dialog's OK ([`craft::automation::Reply::AfterHeldOk`]) once
/// the app accepted or refused it, or the dialog closed, each as its request's reply shows it
/// ([`control::HeldConfirm::forward`]). Called after the dialog pump of a pass, before the next pass's shell
/// closes a dialog the app accepted, and after the control requests.
pub(crate) fn poll_held(&mut self) {
if let Some(dialogs) = self.dialogs()
&& let Some(channel) = self.channel.as_mut()
{
dialogs.with(|host| channel.poll_held(host));
}
if self.held_confirms.is_empty() {
return;
}
// What a reply hides is read once, and only when an answer has come under a read root.
let hiding = std::cell::OnceCell::new();
let roots = self.automation_roots.clone();
let mut held = std::mem::take(&mut self.held_confirms);
let app = &*self;
file_access::confine(roots.as_ref(), || held.retain(|confirm| confirm.forward(|| hiding.get_or_init(|| control::deferred_hiding(app)))));
self.held_confirms = held;
}
/// Answers the `ui.pointer` replies held on the tool's edit ([`control::PointerWait`]). The canvas
/// checks on the tool each pass it is drawn; this checks too, for passes without it.
fn answer_pointer_waits(&mut self, ctx: &egui::Context) {
+125 -23
View File
@@ -18,8 +18,11 @@
//! - `ui.find`: the controls of the window's access tree that match a name or role
//! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}`
//! - `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel`: answered by
//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`), and by
//! `dialogs::simplify_slider::dialog_method` for the Simplify and Smooth sliders
//! `craft::automation::dialogs::dialog_reply` for the dialog asked for (`dialog`, default `"top"`), and by
//! `dialogs::simplify_slider::dialog_method` for the Simplify and Smooth sliders. A set with an `action` replies
//! `{dialog, result}`: the dialog as the set left it, and the reply to its confirm or cancel. A confirm, or a set with
//! `action: "confirm"`, of a dialog that holds its OK replies once the app accepts it, or with the app's
//! refusal as its error
//! - `ui.resize {width, height}`, `ui.focus`, `ui.screenshot {path?, focus?}` (without a path the
//! PNG comes back in the reply)
//! - `ui.render {path?, scale?, artboard?, data?, traceViews?}`: render an artboard headlessly
@@ -130,6 +133,25 @@ fn wrap(r: Result<Value, String>) -> Reply {
Reply::from_result(r)
}
/// The hosted dialog that `params` names (`dialog`: an id as a decimal string or a number, or `"top"` for the top
/// one) as `ui.inspect` lists it, `{id, parent, key, fields}`, or null when none is open.
fn set_dialog(host: &craft::ui::dialog::DialogHost, params: &Value) -> Value {
let Ok(id) = craft::automation::dialogs::dialog_id(host, params) else { return Value::Null };
let id = id.value().to_string();
let open = craft::automation::dialogs::inspect(host);
open.as_array().and_then(|list| list.iter().find(|d| d["id"] == id.as_str())).cloned().unwrap_or(Value::Null)
}
/// The reply to a `ui.dialog.set` with an `action`, from `reply`, the reply to its confirm or cancel: on success
/// `{dialog, result}`, with `dialog` as the set left it and `result` the answer's result, and otherwise `reply`.
pub(crate) fn answered_set(dialog: Value, reply: Value) -> Value {
if reply["ok"] != true {
return reply;
}
let result = reply.get("result").cloned().unwrap_or(Value::Null);
json!({"ok": true, "result": {"dialog": dialog, "result": result}})
}
pub fn all_commands(app: &VectorcraftApp) -> Value {
let mut v: Vec<Value> = app.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect();
for (id, label, sc, params) in crate::menus::UI_COMMANDS {
@@ -1177,9 +1199,11 @@ const DOCKING_ACTION: &str = "action";
/// succeeded or failed ([`sent_paths`]), except where a `path` or `files` entry of its result names the
/// file the request wrote inside the write roots, as the request gave it. A reply with no `/`, `\` or `%` in it is not searched, since every hidden path
/// holds a separator, written or escaped. A screenshot's reply is hidden when it is sent
/// ([`Hiding::hide_error`]); a `ui.pointer` reply sent after the tool's edit holds no library id
/// ([`Hiding::hide_error`]), and so is a confirm's reply held on a dialog's OK ([`HeldConfirm::forward`]); a `ui.pointer` reply sent after the tool's edit holds no library id
/// or path.
pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Reply {
app.held_set = None;
app.held_before = Hiding::default();
let method = req.method.as_str();
if vectorcraft_engine::file_access::current().is_none() {
return dispatch(app, ctx, method, &req.params);
@@ -1198,11 +1222,67 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
err(format!("internal error: {msg} (please report this bug)"))
}
};
let Reply::Done(mut reply) = reply else { return reply };
let mut reply = match reply {
Reply::Done(reply) => reply,
held @ Reply::AfterHeldOk { .. } => {
app.held_before = before;
return held;
}
other => return other,
};
hide_in_reply(app, &mut reply, &req.params, before);
Reply::Done(reply)
}
/// A `ui.dialog.confirm`, or a `ui.dialog.set` with `action: "confirm"`, whose reply waits for the app's answer to
/// the dialog's held OK ([`Reply::AfterHeldOk`]). The control channel sends that answer to `answer`, and
/// [`Self::forward`] sends it on as the request's reply.
pub(crate) struct HeldConfirm {
/// Where the control channel sends the answer.
answer: std::sync::mpsc::Receiver<Value>,
/// Where the request's reply goes.
reply: std::sync::mpsc::Sender<Value>,
/// The request's params: the reply hides the paths outside the read root that they hold.
params: Value,
/// The dialog that a set with an `action` set, which the reply shows as `dialog`.
dialog: Option<Value>,
/// The libraries hidden before the request ran ([`handle`]): the reply hides them too.
before: Hiding,
}
impl HeldConfirm {
/// Holds the reply of `req`: the control channel answers the returned confirm in its place. `dialog` is the
/// dialog `req` set, for a set with an `action`, and `before` the libraries hidden before `req` ran.
pub(crate) fn hold(req: &mut ControlRequest, dialog: Option<Value>, before: Hiding) -> Self {
let (to_confirm, answer) = std::sync::mpsc::channel();
let reply = std::mem::replace(&mut req.reply, to_confirm);
Self { answer, reply, params: req.params.clone(), dialog, before }
}
/// Sends the control channel's answer on as the request's reply: inside `{dialog, result}` for a set with an
/// `action`, and under a read root with the libraries hidden before the request ran and what `hiding` returns
/// hidden, as [`handle`] hides a reply it sends at once. `hiding` is called only for an answer sent under a read
/// root that holds a `/`, `\` or `%`. True while the answer has not come.
pub(crate) fn forward<'a>(&self, hiding: impl FnOnce() -> &'a Hiding) -> bool {
let answer = match self.answer.try_recv() {
Ok(answer) => answer,
Err(std::sync::mpsc::TryRecvError::Empty) => return true,
Err(std::sync::mpsc::TryRecvError::Disconnected) => return false,
};
let mut reply = match &self.dialog {
Some(dialog) => answered_set(dialog.clone(), answer),
None => answer,
};
if vectorcraft_engine::file_access::current().is_some() && holds_a_separator(&reply) {
let mut hiding = hiding().clone();
hiding.merge(self.before.clone());
hiding.hide(&mut reply, &self.params);
}
let _ = self.reply.send(reply);
false
}
}
/// Hides in `reply` the libraries hidden now and in `before`, and the paths outside the read root that
/// `sent`, the request's params, holds ([`handle`]), and the recovery folders outside the read root
/// that are in use or that a failure message named, with each folder on the way to one that the reply
@@ -1479,12 +1559,13 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val
Some(_) => return err("`action` must be confirm or cancel"),
};
let pdf = app.save_pdf.as_ref().map(|open| open.id).filter(|_| method == "ui.dialog.set");
let mut held_set = None;
let reply = dialogs.with(|host| {
// A Color Picker whose Recolor Artwork row changed while it was open refuses OK.
if method == "ui.dialog.confirm"
&& let Err(reason) = crate::dialogs::color_picker::check_confirm(app, host, &params)
{
return Some(Err(reason));
return Some(wrap(Err(reason)));
}
// The answer goes to the dialog the fields went to, even when setting them opens another over it.
if answer.is_some()
@@ -1502,41 +1583,46 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val
if answer == Some("ui.dialog.confirm")
&& let Err(reason) = crate::dialogs::color_picker::check_confirm(app, host, &params)
{
return Some(Err(reason));
return Some(wrap(Err(reason)));
}
let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog"));
let set = if answer.is_none() || sets {
// A Save PDF settings object keeps the options it leaves out.
match pdf.and_then(|id| crate::dialogs::save_pdf::set_settings_objects(host, ctx, id, &params)) {
Some(set) => Some(set.map(|()| Value::Null)),
// A confirm that files a dialog's held OK replies once the app accepts or refuses it.
None if method != "ui.dialog.set" => return craft::automation::dialogs::dialog_reply(host, ctx, method, &params),
None => craft::automation::dialogs::dialog_method(host, ctx, method, &params),
}
} else {
Some(Ok(Value::Null))
};
match (set, answer) {
// A set with an `action` replies `{dialog, result}`: the dialog as the set left it, and the answer's
// result. A confirm that files the dialog's held OK replies once the app answers it.
(Some(Ok(_)), Some(answer)) => {
let dialog = set_dialog(host, &params);
if answer == "ui.dialog.confirm"
&& let Ok(id) = craft::automation::dialogs::dialog_id(host, &params)
{
crate::dialogs::print::prepare_confirm(app, host, id);
}
craft::automation::dialogs::dialog_method(host, ctx, answer, &json!({ "dialog": params["dialog"] }))
match craft::automation::dialogs::dialog_reply(host, ctx, answer, &json!({ "dialog": params["dialog"] })) {
Some(Reply::Done(reply)) => Some(Reply::Done(answered_set(dialog, reply))),
Some(held) => {
held_set = Some(dialog);
Some(held)
}
None => None,
}
}
// A set answers with the dialog it set, `{id, parent, key, fields}`, as production did.
(Some(Ok(_)), None) if method == "ui.dialog.set" => {
let open = craft::automation::dialogs::inspect(host);
let list = open.as_array().map_or(&[][..], Vec::as_slice);
let set = if params["dialog"] == "top" { list.last() } else { list.iter().find(|d| d["id"] == params["dialog"]) };
Some(Ok(set.cloned().unwrap_or(Value::Null)))
}
(set, _) => set,
(Some(Ok(_)), None) if method == "ui.dialog.set" => Some(ok(set_dialog(host, &params))),
(set, _) => set.map(wrap),
}
});
match reply {
Some(r) => wrap(r),
None => err(format!("unknown method `{method}`")),
}
app.held_set = held_set;
reply.unwrap_or_else(|| err(format!("unknown method `{method}`")))
}
"ui.resize" => {
let (w, h) = match coord(p, "width", 1440.0).and_then(|w| Ok((w, coord(p, "height", 900.0)?))) {
@@ -1696,14 +1782,30 @@ fn preferences_method(app: &mut VectorcraftApp, method: &str, p: &Value) -> Resu
for (field, value) in fields {
crate::prefs_dialog::set_field(app, &field, value)?;
}
match action {
Some("confirm") => crate::prefs_dialog::confirm(app),
// A set with an `action` replies `{dialog, result}`: the window as the set left it, as `ui.inspect` shows it, and
// the answer's result. Under a read root, the folder preferences the request may not read are left out, as
// `ui.inspect` leaves them out.
let dialog = (method == "ui.dialog.set" && action.is_some()).then(|| {
let mut fields = crate::prefs_dialog::fields(app);
if vectorcraft_engine::file_access::current().is_some()
&& let Some(fields) = fields.as_mut()
{
leave_out_unreadable_folders(fields);
}
json!({"kind": "preferences", "fields": fields})
});
let result = match action {
Some("confirm") => crate::prefs_dialog::confirm(app)?,
Some(_) => {
crate::prefs_dialog::cancel(app);
Ok(Value::Null)
Value::Null
}
None => Ok(Value::Null),
}
None => Value::Null,
};
Ok(match dialog {
Some(dialog) => json!({"dialog": dialog, "result": result}),
None => result,
})
}
/// `app.save` (`method`) or `app.export` with params `p`.
+132
View File
@@ -648,16 +648,148 @@ fn dialog_set_with_an_action_answers_the_same_dialog() {
}
let r = request(&mut app, json!({"fields": [{"field": "text", "value": "b"}], "action": "confirm"}));
assert_eq!(r["ok"], true, "{r}");
// The reply is `{dialog, result}`: the dialog as the set left it, and the reply to confirm.
assert_eq!(r["result"]["dialog"]["id"], id.value().to_string(), "{r}");
assert_eq!(r["result"]["dialog"]["fields"]["text"], "b", "{r}");
assert_eq!(r["result"].get("result"), Some(&Value::Null), "{r}");
let Some(DialogResult::Ok(answer)) = taken(&app, id) else { panic!("confirmed in the same request") };
assert_eq!(answer.fields.text("text"), Some("b"), "the answer holds the field set with it");
let id = open(&mut app);
let r = request(&mut app, json!({"fields": [{"field": "text", "value": "c"}], "action": "cancel"}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!(r["result"]["dialog"]["fields"]["text"], "c", "{r}");
assert_eq!(r["result"].get("result"), Some(&Value::Null), "{r}");
assert!(matches!(taken(&app, id), Some(DialogResult::Cancel)), "canceled in the same request");
// A dialog named by its id as a number replies with that dialog too, with an `action` and without one.
let id = open(&mut app);
let r = request(&mut app, json!({"dialog": id.value(), "field": "text", "value": "d"}));
assert_eq!(r["result"]["id"], id.value().to_string(), "{r}");
let r = request(&mut app, json!({"dialog": id.value(), "field": "text", "value": "e", "action": "cancel"}));
assert_eq!(r["result"]["dialog"]["id"], id.value().to_string(), "{r}");
assert_eq!(r["result"]["dialog"]["fields"]["text"], "e", "{r}");
assert!(matches!(taken(&app, id), Some(DialogResult::Cancel)), "canceled in the same request");
let r = request(&mut app, json!({"fields": [], "action": "confirm"}));
assert_eq!(r["ok"], false, "no dialog open: {r}");
}
/// A confirm of a dialog that holds its OK replies with the app's answer, through both ways of confirming:
/// `ui.dialog.confirm` gets the refusal of a color adjustment confirmed in another document than the one it
/// opened in, and `ui.dialog.set {action: "confirm"}` in its own document gets the acceptance. While the
/// window is hidden, the request asks for the pass that pumps the dialogs, and the reply waits for it.
#[test]
fn a_held_confirm_replies_with_the_apps_answer() {
let (tx, rx) = std::sync::mpsc::channel();
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()).with_control(rx));
let ctx = app.ui_ctx.clone().unwrap();
let mut ids = Vec::new();
for _ in 0..2 {
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
ids.push(app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
app.run("paint.setFill", json!({"color": "#808080"})).unwrap();
}
let fill = |app: &VectorcraftApp, id: u64| {
let node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone();
node.appearance.fill_paint().color().unwrap().to_hex()
};
app.run("document.activate", json!({"index": 0})).unwrap();
crate::dialogs::color_balance::open(&mut app);
app.dialogs()
.unwrap()
.with(|h| h.set_json_field(&ctx, craft::ui::dialog::dialog_id(crate::dialogs::color_balance::KIND), "r", json!(20)))
.unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let (req, reply) = ControlRequest::new("ui.dialog.confirm", json!({}));
tx.send(req).unwrap();
crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default());
let refused = json!({"ok": false, "error": "This adjustment can only apply to the document where it was opened."});
assert_eq!(reply.try_recv().ok(), Some(refused), "the confirm replies with the app's refusal");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the other document is not adjusted");
assert_eq!(fill(&app, ids[1]), "#808080");
app.run("document.activate", json!({"index": 0})).unwrap();
let hidden = || {
let mut raw = egui::RawInput::default();
raw.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { minimized: Some(true), ..Default::default() });
raw
};
let (req, reply) = ControlRequest::new("ui.dialog.set", json!({"fields": [], "action": "confirm"}));
tx.send(req).unwrap();
// A hidden window runs only the app's logic until it is asked to paint.
let out = crate::testing::part_frame(&mut app, &ctx, hidden(), |app, ui| app.tick(ui.ctx()));
assert!(reply.try_recv().is_err(), "the reply waits for the app's answer");
let commands = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(&[][..], |v| v.commands.as_slice());
assert!(commands.contains(&egui::ViewportCommand::RequestPaintWhileHidden), "the held OK asks for a pass: {commands:?}");
crate::testing::app_frame(&mut app, &ctx, hidden());
let r = reply.try_recv().expect("the confirm replies once the app accepts it");
assert_eq!(r["ok"], true, "{r}");
// A set with an `action` replies `{dialog, result}` once the app has answered too.
assert_eq!(r["result"]["dialog"]["key"], crate::dialogs::color_balance::KIND, "{r}");
assert_eq!(r["result"]["dialog"]["fields"]["r"].as_f64(), Some(20.0), "{r}");
assert_eq!(r["result"].get("result"), Some(&Value::Null), "{r}");
assert_eq!(fill(&app, ids[0]), "#b38080", "the adjustment applies in its own document");
assert!(app.held_confirms.is_empty(), "no confirm waits");
}
/// A held confirm whose dialog closes before the app answers its OK replies with an error, and a second confirm
/// sent while the first waits is refused without answering the first.
#[test]
fn a_held_confirm_answers_when_its_dialog_closes_first() {
let (tx, rx) = std::sync::mpsc::channel();
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()).with_control(rx));
let ctx = app.ui_ctx.clone().unwrap();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap();
crate::dialogs::color_balance::open(&mut app);
// A pass that runs only the app's logic answers the control requests, but not the held OK.
let logic = |app: &mut VectorcraftApp, method: &str| {
let (req, reply) = ControlRequest::new(method, json!({}));
tx.send(req).unwrap();
crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| app.tick(ui.ctx()));
reply
};
let first = logic(&mut app, "ui.dialog.confirm");
assert!(first.try_recv().is_err(), "the reply waits for the app's answer");
let second = logic(&mut app, "ui.dialog.confirm");
let r = second.try_recv().expect("a second confirm replies at once");
assert_eq!(r["ok"], false, "a second confirm while the first waits is refused: {r}");
assert!(first.try_recv().is_err(), "the first confirm still waits");
let cancel = logic(&mut app, "ui.dialog.cancel");
assert_eq!(cancel.try_recv().ok().map(|r| r["ok"].clone()), Some(json!(true)));
let closed = json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"});
assert_eq!(first.try_recv().ok(), Some(closed), "the first confirm replies that the dialog closed");
assert!(app.held_confirms.is_empty(), "no confirm waits");
}
/// Under a read root, a confirm's reply held on a dialog's OK shows a library the request could not read by the id
/// `ui.inspect` shows for it, even when the library is no longer in use once the app answers.
#[test]
fn a_held_confirm_hides_a_library_hidden_when_it_was_sent() {
let root = crate::tests_folder::Folder::new("held-before-root");
let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[root.as_path()], &[]).unwrap();
let path = std::env::temp_dir().join("vc-held-before").join("b.svg").to_string_lossy().into_owned();
let id = format!("loaded/{path}");
let (tx, rx) = std::sync::mpsc::channel();
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()).with_control(rx).with_automation_roots(roots));
let ctx = app.ui_ctx.clone().unwrap();
app.ui.color_guide_limit = id.clone();
crate::dialogs::action_set_options::open_new(&mut app);
let dialog = craft::ui::dialog::dialog_id("actionSetOptions");
app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, dialog, "name", json!(format!("from {id}")))).unwrap();
let (req, reply) = ControlRequest::new("ui.dialog.set", json!({"fields": [], "action": "confirm"}));
tx.send(req).unwrap();
// A pass that runs only the app's logic answers the request, but not the held OK.
crate::testing::part_frame(&mut app, &ctx, egui::RawInput::default(), |app, ui| app.tick(ui.ctx()));
assert!(reply.try_recv().is_err(), "the reply waits for the app's answer");
app.ui.color_guide_limit.clear();
crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default());
let r = reply.try_recv().expect("the confirm replies once the app accepts it");
assert_eq!(r["ok"], true, "{r}");
assert_eq!(r["result"]["dialog"]["fields"]["name"], "from loaded/b.svg", "{r}");
assert!(app.held_confirms.is_empty(), "no confirm waits");
}
/// #1004: `ui.render` (the MCP `screenshot` of a connected app) renders the artboard asked
/// for, at the scale asked for; the first without one.
#[test]
+56 -8
View File
@@ -332,9 +332,16 @@ impl HoldsOk for DxfImportDialog {
}
}
/// Is `ext` the extension of a drawing this dialog opens (DXF, or DWG converted to DXF)?
/// Is `ext` the extension (or format id) of a drawing this dialog opens (DXF, or DWG converted to
/// DXF)?
pub(crate) fn is_drawing_ext(ext: &str) -> bool {
matches!(ext, "dxf" | "dwg")
ext == "dxf" || is_dwg_ext(ext)
}
/// Is `ext` the extension (or format id) of a DWG drawing: `.dwg`, a `.dws` standards file or a
/// `.dwt` template?
pub(crate) fn is_dwg_ext(ext: &str) -> bool {
fileio::readable_format(ext).is_some_and(|f| fileio::reads_as_dwg(f.id))
}
/// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they
@@ -351,7 +358,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
/// drawing is converted on a job of its own ([`crate::opening::convert_drawing`]) and its dialog
/// opens once that is done ([`converted`]) → true; false when `bytes` aren't a DWG drawing.
pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, place: Option<&Value>) -> bool {
if !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| f.id != "dwg") {
if !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| !fileio::reads_as_dwg(f.id)) {
return false;
}
crate::opening::convert_drawing(app, name, bytes.to_vec(), path, place.cloned());
@@ -365,10 +372,10 @@ pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8],
/// converted (true).
pub fn convert_place_in_background(app: &mut VectorcraftApp, p: &Value) -> bool {
let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension);
if p.get("dxf").is_some() || named.as_deref() != Some("dwg") {
if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_dwg_ext) {
return false;
}
let Some((name, bytes, path)) = place_source(app, p, |ext| ext == "dwg") else { return false };
let Some((name, bytes, path)) = place_source(app, p, is_dwg_ext) else { return false };
if !vectorcraft_cad::is_dwg(&bytes) {
return false;
}
@@ -443,8 +450,8 @@ fn show(
open_held(app, dialog, move |app, choices| confirm(app, &source, choices)).is_some()
}
/// `file.place` with params `p` asks first (true) when they name a `.dxf` or `.dwg` drawing and no
/// `dxf` options.
/// `file.place` with params `p` asks first (true) when they name a `.dxf`, `.dwg`, `.dws` or `.dwt`
/// drawing and no `dxf` options.
pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool {
let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension);
if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_drawing_ext) {
@@ -456,7 +463,8 @@ pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool {
/// The `dxf` options a drawing `file.place` params `p` name is placed with when Show Import Options
/// is off: the choices confirmed last (fit, lineweights, centring, layers), the drawing at 1:1 in
/// its own unit. `None` when `p` names no `.dxf` or `.dwg` drawing or already gives `dxf` options.
/// its own unit. `None` when `p` names no DXF or DWG drawing ([`is_drawing_ext`]) or already gives
/// `dxf` options.
pub fn last_options(app: &VectorcraftApp, p: &Value) -> Option<Value> {
let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension);
if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_drawing_ext) {
@@ -808,6 +816,46 @@ mod tests {
});
}
/// A `.dwt` template and a `.dws` standards file are DWG drawings: they are converted off the UI
/// thread and go through the dialog as a `.dwg` does, and the template opens untitled.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn a_dwt_template_and_a_dws_file_open_and_place_as_dwg_drawings() {
vectorcraft_engine::dwg::allow_in_process();
let dwg = craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap();
let dir = crate::tests_folder::Folder::new("dxf-import-dwt-dws");
let (template, standards) = (dir.join("plan.dwt"), dir.join("plan.dws"));
std::fs::write(&template, &dwg).unwrap();
std::fs::write(&standards, &dwg).unwrap();
let (template, standards) = (template.to_string_lossy().into_owned(), standards.to_string_lossy().into_owned());
crate::opening::tests::with_threads(|| {
let mut app = host::app();
app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
crate::io::open_file(&mut app, &template, true).unwrap();
assert!(!host::is_open(&app, KIND) && app.opening.converting.len() == 1, "the template is converted first");
finish_conversions(&mut app);
assert_eq!(host::fields(&app, KIND)["mode"], "open");
host::confirm(&mut app, KIND).unwrap();
let st = app.session.doc().unwrap();
assert!(st.doc.title.starts_with("Untitled"), "a template opens untitled: {}", st.doc.title);
let w = st.doc.artboards[0].rect.width();
assert!((w - 100.0 * Unit::Millimeters.points()).abs() < 1e-6, "the model space line at 1:1: {w}");
crate::io::open_file(&mut app, &standards, true).unwrap();
assert_eq!(app.opening.converting.len(), 1, "the standards file is converted first");
finish_conversions(&mut app);
host::confirm(&mut app, KIND).unwrap();
assert_eq!(app.session.doc().unwrap().doc.title, "plan.dws");
// Placed by the user, each is converted first and asks for its options.
for path in [&template, &standards] {
crate::place::run_for_user(&mut app, &json!({ "path": path })).unwrap();
assert!(!host::is_open(&app, KIND), "{path}");
finish_conversions(&mut app);
assert_eq!(host::fields(&app, KIND)["mode"], "place", "{path}");
host::cancel(&app, KIND);
}
});
}
/// Waits for the DWG conversions under way to finish, then lets [`crate::opening::poll`] hand
/// them on.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
+5 -5
View File
@@ -264,11 +264,11 @@ mod tests {
}
assert_eq!(paras(&app, id), original, "{lang}: only the draft changes while open");
if answer == "ui.dialog.confirm" {
let (request, _) = ControlRequest::new(answer, json!({}));
match crate::control::handle(&mut app, &ctx, &request) {
Reply::Done(reply) => assert_eq!(reply["ok"], true, "{reply}"),
_ => panic!("confirmation should reply immediately"),
}
let (request, sent) = ControlRequest::new(answer, json!({}));
let reply = crate::control::handle(&mut app, &ctx, &request);
assert!(matches!(reply, Reply::AfterHeldOk { .. }), "the confirm waits for the app's answer to the held OK");
let reply = crate::testing::settled_reply(&mut app, &ctx, request, &sent, reply);
assert_eq!(reply["ok"], true, "{reply}");
} else {
click(&mut app, &mut frame, footer.center());
}
+4 -3
View File
@@ -1,6 +1,6 @@
//! The raster export options: PNG Options (resolution, background, anti-aliasing, interlaced),
//! JPEG Options (no transparency; colour model, quality 0–10, method and scans, profile, image
//! map), WebP Options (lossless, or lossy at a quality 0–100), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither,
//! map), WebP Options (lossless, or lossy at a quality 0–100, and the profile), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither,
//! transparency and its dither, matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options
//! ([`super::psd_options`]). Fields
//! are `document.export` params (format, path, artboard choice…); `__`-prefixed ones are the
@@ -115,7 +115,7 @@ pub(super) fn defaults(app: &VectorcraftApp, f: &Format) -> Map<String, Value> {
o.insert("interlaced".into(), json!(false));
}
"webp" => {
o.extend([("lossless".into(), json!(true)), ("quality".into(), json!(WEBP_QUALITY))]);
o.extend([("lossless".into(), json!(true)), ("quality".into(), json!(WEBP_QUALITY)), ("embedIcc".into(), json!(true))]);
}
"jpg" => {
let model = if cmyk { ColorModel::Cmyk } else { ColorModel::Rgb };
@@ -337,7 +337,7 @@ fn quality_row() -> Param {
}
/// The WebP Options rows: Lossless or Lossy compression, and the quality 0–100 that Lossy uses
/// (disabled while Lossless is chosen, keeping its value).
/// (disabled while Lossless is chosen, keeping its value), and Embed ICC Profile (sRGB).
fn webp_rows() -> Vec<Param> {
let [lossless, lossy] = WEBP_COMPRESSION_LABELS;
let compression = ParamKind::radio(vec![("true".into(), tl!(lossless).into()), ("false".into(), tl!(lossy).into())], Some("true".into()));
@@ -345,6 +345,7 @@ fn webp_rows() -> Vec<Param> {
Param::new("lossless", tl!("Compression:"), compression),
Param::new("quality", tl!("Quality:"), ParamKind::range(0.0, 100.0, f64::from(WEBP_QUALITY), SliderScale::Linear))
.enabled_when("lossless", "false"),
check("embedIcc", tl!("Embed ICC Profile"), true),
]
}
+14 -6
View File
@@ -925,15 +925,23 @@ pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Val
return Some(Err(e));
}
}
Some(match answer {
Some(true) => confirm(app),
Some(false) => cancel(app).map(|()| Value::Null),
// A set answers with the dialog it set, `{id, parent, key, fields}`, as the other dialogs' sets do.
None => Ok(with_host(app, |host, _| {
// A set answers with the dialog it set, `{id, parent, key, fields}`, as the other dialogs' sets do.
let set = (method == "ui.dialog.set").then(|| {
with_host(app, |host, _| {
let id = dialog_id(KIND).value().to_string();
craft::automation::dialogs::inspect(host).as_array().and_then(|open| open.iter().find(|d| d["id"] == id.as_str()).cloned())
})
.flatten()
.unwrap_or(Value::Null)),
.unwrap_or(Value::Null)
});
let result = match answer {
Some(true) => confirm(app),
Some(false) => cancel(app).map(|()| Value::Null),
None => return Some(Ok(set.unwrap_or(Value::Null))),
};
// A set with an `action` replies `{dialog, result}`: the dialog as the set left it, and the answer's result.
Some(match (set, result) {
(Some(dialog), Ok(result)) => Ok(json!({ "dialog": dialog, "result": result })),
(_, result) => result,
})
}
+5 -3
View File
@@ -90,10 +90,11 @@ pub(super) fn confirm(app: &mut VectorcraftApp) {
}
/// One control request, answered as the control channel answers it: at once, or, for synthetic input (`ui.text`,
/// `ui.key`), once the frames after it have processed the input.
/// `ui.key`), once the frames after it have processed the input, or, for a confirm of Print's held OK, once the app
/// answered it.
pub(super) fn call_raw(app: &mut VectorcraftApp, method: &str, params: Value) -> Value {
let ctx = ctx(app);
let (req, _reply) = craft::automation::ControlRequest::new(method, params);
let (req, answer) = craft::automation::ControlRequest::new(method, params);
let reply = match crate::control::handle(app, &ctx, &req) {
craft::automation::Reply::Done(reply) => reply,
craft::automation::Reply::AfterInput => {
@@ -102,7 +103,8 @@ pub(super) fn call_raw(app: &mut VectorcraftApp, method: &str, params: Value) ->
}
json!({"ok": true, "result": null})
}
_ => panic!("{method} is answered at once or after its input"),
held @ craft::automation::Reply::AfterHeldOk { .. } => crate::testing::settled_reply(app, &ctx, req, &answer, held),
_ => panic!("{method} is answered at once, after its input or after the app's answer"),
};
pump(app);
reply
@@ -45,8 +45,9 @@ fn raster_option_rows_reach_the_export_params() {
assert_eq!(gif[10] & 0x07, 1, "a global colour table of 4 entries");
}),
("png8", &[("reduction", json!("gray"))], |png| assert_eq!(png[25], 3, "indexed")),
("webp", &[("lossless", json!("false")), ("quality", json!(40))], |file| {
("webp", &[("lossless", json!("false")), ("quality", json!(40)), ("embedIcc", json!(false))], |file| {
assert!(file.windows(4).any(|w| w == b"VP8 ") && !file.windows(4).any(|w| w == b"VP8L"), "lossy");
assert!(!file.windows(4).any(|w| w == b"ICCP"), "no profile");
}),
("tiff", &[("byteOrder", json!("big")), ("colorModel", json!("cmyk")), ("lzw", json!(false))], |tiff| assert_eq!(&tiff[..4], b"MM\0*")),
("tga", &[("depth", json!("32"))], |tga| assert_eq!((tga[16], tga[17]), (32, 8))),
@@ -165,7 +166,8 @@ fn text_export_options_write_the_stories() {
assert_eq!((path.as_str(), bytes.as_slice()), ("/out/Untitled-1.txt", &b"Hello\r\nthere\r\n"[..]));
}
/// WebP is lossless by default, and OK writes a lossless file without a note.
/// WebP is lossless with the sRGB profile by default, and OK writes a lossless file holding the
/// profile, without a note.
#[test]
fn webp_is_lossless_by_default() {
let (mut app, written) = app(1);
@@ -175,7 +177,9 @@ fn webp_is_lossless_by_default() {
frame(&mut app);
confirm(&mut app);
assert!(!app.ui.status.contains("note"), "{}", app.ui.status);
assert_eq!(&written.borrow()[0].1[12..16], b"VP8L", "lossless by default");
let file = written.borrow()[0].1.clone();
assert!(file.windows(4).any(|w| w == b"VP8L"), "lossless by default");
assert!(file.windows(4).any(|w| w == b"ICCP"), "the profile by default");
}
#[test]
+1 -2
View File
@@ -127,14 +127,13 @@ impl VectorcraftApp {
/// after losing its graphics), everything uploaded to the old one is made again: the fonts and
/// theme, the canvas, the place cursor's thumbnails and every [`TexCache`]. The host hands it
/// the window's context when it creates the app, so the first frame's input has the app's
/// commands. Each new context draws its text without hinting ([`crate::ui_fonts::hinting_off`]).
/// commands.
pub fn adopt_context(&mut self, ctx: &egui::Context) {
let tag = context_tag(ctx);
self.ui_ctx = Some(ctx.clone());
if self.context == tag {
return;
}
crate::ui_fonts::hinting_off(ctx);
if self.context != 0 {
log::info!("vectorcraft: new graphics context: uploading the UI again");
forget_textures();
+8
View File
@@ -184,6 +184,14 @@ pub struct VectorcraftApp {
pub(crate) channel: Option<ControlChannel>,
/// A `ui.pointer` or `ui.tool.select` held until the synthetic input sent before it reached the tool.
deferred_control: Option<ControlRequest>,
/// The dialog that the request [`control::handle`] answered last set with `action: "confirm"`, when that confirm
/// filed the dialog's held OK: its reply shows it as `dialog` ([`control::HeldConfirm`]).
pub(crate) held_set: Option<serde_json::Value>,
/// The libraries hidden before the request [`control::handle`] answered last ran, when its confirm filed a
/// dialog's held OK: its reply hides them as well as those hidden when it is sent ([`control::HeldConfirm`]).
pub(crate) held_before: control::Hiding,
/// The confirms whose replies wait for the app's answer to a dialog's held OK.
pub(crate) held_confirms: Vec<control::HeldConfirm>,
/// Where a control-channel Rotate View drag began, kept between its requests.
pub(crate) control_rotate_press: Option<control::RotateViewPress>,
/// The `ui.pointer` replies that wait for the edit their gesture started on another thread.
+1 -1
View File
@@ -1556,7 +1556,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
),
(
"ui.widthPointEdit",
@@ -582,6 +582,25 @@ fn copy_and_cut_in_a_native_window_act_on_the_art_while_another_windows_label_ha
}
}
/// A panel or the Tools rail floated out of the dock opens an OS window that shows, in every built-in workspace,
/// including those whose Contextual Task Bar shows over the canvas.
#[test]
fn a_panel_floated_in_any_built_in_workspace_opens_a_shown_window() {
for workspace in crate::workspaces::builtins() {
for panel in ["tools", "properties"] {
let mut h = Harness::new();
h.app.run("window.workspace", json!({"name": workspace.name})).unwrap();
h.frames(3);
h.app.run("window.panel.float", json!({"panel": panel, "x": 200, "y": 200})).unwrap();
h.frames(6);
let viewport = h.viewport(panel);
let host = h.host.borrow();
let window = host.windows.get(&viewport).expect("the panel opened an OS window");
assert!(window.visible, "{}: the {panel} window shows", workspace.name);
}
}
}
/// A panel opened from the Window menu floats in an OS window that keeps showing while the art on
/// the canvas is selected and moved, and the Selection tool's move ends where it is released.
#[test]
+183 -16
View File
@@ -9,6 +9,7 @@
//! selected. Easing and Reverse Spine are dimmed for a blend made without a spine.
use std::ops::RangeInclusive;
use std::sync::Arc;
use craft::behavior::IconId;
use craft::ui::buttons::Button;
@@ -19,11 +20,12 @@ use craft::ui::form::{Field, FieldGroup};
use craft::ui::form::{SliderField, SliderFieldLayout};
use craft::ui::layout_components::Row;
use craft::ui::pickers::Select;
use craft::ui::runtime::focus::{self, FocusTarget};
use craft::ui::text::NumberField;
use egui::Ui;
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use vectorcraft_doc::live::BlendSpineMode;
use vectorcraft_doc::{NodeId, NodeKind, SymbolPart};
use super::selection_len;
use crate::VectorcraftApp;
@@ -80,32 +82,178 @@ fn spacing_params(mode: &str, steps: f64, distance: f64) -> Value {
}
}
/// The Ramp or Shift slider: `key` of `object.blend.options` as a percentage over `range`. A drag
/// previews the selected blends and its release records one undo step; a change without a drag,
/// from the keyboard, records one at once.
fn percent_slider(
app: &mut VectorcraftApp,
ui: &mut Ui,
/// The label, options key and percentage range for a Ramp or Shift slider.
struct PercentSlider {
label: &'static str,
key: &'static str,
value: Option<f64>,
range: RangeInclusive<f64>,
on: bool,
) {
}
/// The Ramp or Shift slider: `slider.key` of `object.blend.options` over `slider.range`. A drag
/// previews the selected blends and its release records one undo step; a change without a drag,
/// from the keyboard, records one at once. A value typed into its field and not yet committed is
/// dropped when the [`EditTarget`] changes, and an enabled field keeps the focus.
fn percent_slider(app: &mut VectorcraftApp, ui: &mut Ui, target: &EditTarget, slider: PercentSlider, value: Option<f64>, on: bool) {
let PercentSlider { label, key, range } = slider;
Field::new(label).enabled(on).show(ui, |ui, _| {
let shown = value.unwrap_or(0.0).clamp(*range.start(), *range.end());
let out =
SliderField::new(label, Bind::given(shown), range.clone()).layout(SliderFieldLayout::Inline).unit("%").step(1.0).enabled(on).show(ui);
// Until the craft-libs pin includes storytold/craft-libs#5024 (`SliderField::edit_target`),
// which then replaces this: when the edit target changes, the slider field gets a new id salt
// only if its number field held focus in the last pass or holds it now, so an unfinished
// value is dropped and never committed to the new target. Otherwise its id stays the same,
// including during a drag. When the id changes, the focus moves to the new track if the old
// track holds it now, or to the new number field if the old number field holds it now.
// Other focus moves keep their destination.
let held = ui.scope_id().with(("blend-percent-target", key));
let mut kept = ui.ctx().data(|d| d.get_temp::<PercentField>(held)).unwrap_or_default();
let previous_round = kept.round;
if &kept.target != target {
kept.target = target.clone();
let ctx = ui.ctx();
let track_focused = kept.track.is_some_and(|id| focus::has(ctx, id));
let typed_focused = kept.typed.is_some_and(|id| focus::has(ctx, id));
if kept.typed_focused || typed_focused {
kept.round = kept.round.wrapping_add(1);
kept.hand_off = if track_focused {
Some("slider")
} else if typed_focused {
Some("field")
} else {
None
};
}
}
let out = SliderField::new(label, Bind::given(shown), range.clone())
.layout(SliderFieldLayout::Inline)
.unit("%")
.step(1.0)
.enabled(on)
.id_salt(("blend-percent", key, kept.round))
.show(ui);
// The slider field's children are keyed "slider" (the track) and "field" (the number field
// that takes typing). A measuring pass moves no focus, so the hand-off waits for a pass that
// does.
let typed = out.edit.response.id.with("field");
// Disabled children have no focus stop. A request for one can outlive this target.
if !on {
kept.hand_off = None;
} else if ui.input(|i| i.pointer.any_pressed()) {
// Pointer focus moves settle at the end of the pass against the old ids. When these
// children are replaced, a primary press on the visible part of the row, on this layer,
// focuses the new child under it, even if released in this frame. Other button presses
// cancel the hand-off. SliderField exposes only the whole response; response_of supplies
// its child rects. A track press gets focus, but its drag cannot start on the replacement
// this frame.
let pressed = ui.input(|i| {
i.events.iter().find_map(|event| match event {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos),
_ => None,
})
});
kept.hand_off = if previous_round != kept.round || kept.hand_off.is_some() {
let on_row = |at: &egui::Pos2| {
out.edit.response.rect.contains(*at) && ui.clip_rect().contains(*at) && ui.ctx().layer_id_at(*at) == Some(ui.layer_id())
};
pressed.filter(on_row).and_then(|at| {
["field", "slider"].into_iter().find(|child| {
craft::ui::contract::response_of(ui, out.edit.response.id.with(child)).is_some_and(|response| response.rect.contains(at))
})
})
} else {
None
};
}
if let Some(child) = kept.hand_off
&& focus::request(ui.ctx(), FocusTarget::Id(out.edit.response.id.with(child)))
{
kept.hand_off = None;
}
kept.typed_focused = focus::has(ui.ctx(), typed);
kept.typed = Some(typed);
kept.track = Some(out.edit.response.id.with("slider"));
ui.ctx().data_mut(|d| d.insert_temp(held, kept));
apply_edits(app, &out.edit, EditPath::Preview, |app, v, phase| {
crate::panels::live_run(app, "Blend Options", "object.blend.options", json!({ key: *v }), phase);
});
});
}
/// The Steps, Distance, Ramp and Shift draft key: the document uid, its File › Revert count, and
/// each selected object id paired with its nearest blend id, or None when it resolves to no blend.
/// Symbol-part selections resolve to no blend, as the Blend commands require. A field drops an
/// unfinished value when this key changes, even when the new target shows the same value.
/// [`settings`] reuses this key until the document or selection changes and shares it with its fields.
pub(super) type EditTarget = Option<(u64, u64, Arc<Vec<(NodeId, Option<NodeId>)>>)>;
/// The resolved objects also hold the selection's ids, so checking the cache copies no selection.
struct TargetCache {
uid: u64,
revision: u64,
reverts: u64,
symbol_part: Option<SymbolPart>,
objects: Arc<Vec<(NodeId, Option<NodeId>)>>,
}
/// What the Ramp or Shift slider field keeps between passes: the [`EditTarget`] it last showed, the
/// round its id salt is on, the ids of its number field and its track, whether its number field
/// held focus in the last pass, and the child that still needs focus in a new round.
#[derive(Clone, Default)]
struct PercentField {
target: EditTarget,
round: u64,
typed: Option<egui::Id>,
track: Option<egui::Id>,
typed_focused: bool,
hand_off: Option<&'static str>,
}
/// The active document's uid and revert count, with each selected id and its resolved blend id.
/// Resolution uses the same nearest-node finder and symbol-part guard as the Blend commands.
/// Unchanged document revisions and selections reuse the resolved objects between passes.
pub(super) fn edit_target(app: &VectorcraftApp, ctx: &egui::Context) -> EditTarget {
let st = app.session.active()?;
let key = egui::Id::unique("blend-edit-target");
if let Some(held) = ctx.data(|d| d.get_temp::<Arc<TargetCache>>(key))
&& held.uid == st.uid
&& held.revision == st.revision
&& held.reverts == st.reverts
&& held.symbol_part == st.selection.symbol_part
&& held.objects.iter().map(|(id, _)| id).eq(st.selection.objects.iter())
{
return Some((st.uid, st.reverts, held.objects.clone()));
}
let mut find = st.doc.nearest_finder();
let objects: Vec<(NodeId, Option<NodeId>)> = st
.selection
.objects
.iter()
.map(|id| {
let blend =
if st.selection.symbol_part.is_none() { find.nearest(*id, |n| matches!(n.kind, NodeKind::Blend { .. })).map(|n| n.id) } else { None };
(*id, blend)
})
.collect();
let objects = Arc::new(objects);
ctx.data_mut(|d| {
d.insert_temp(
key,
Arc::new(TargetCache {
uid: st.uid,
revision: st.revision,
reverts: st.reverts,
symbol_part: st.selection.symbol_part.clone(),
objects: objects.clone(),
}),
);
});
Some((st.uid, st.reverts, objects))
}
/// Spacing and Orientation, as `object.blend.info` reports them; a change runs
/// `object.blend.options`.
fn settings(app: &mut VectorcraftApp, ui: &mut Ui) {
let info = app.session.execute("object.blend.info", &json!({})).unwrap_or_default();
let target = &edit_target(app, ui.ctx());
let mode = info["spacing"].as_str().unwrap_or("smooth");
let steps = info["steps"].as_f64().unwrap_or(5.0);
let distance = info["distance"].as_f64().unwrap_or(10.0);
@@ -119,7 +267,7 @@ fn settings(app: &mut VectorcraftApp, ui: &mut Ui) {
});
if mode == "distance" {
Field::new(tl!("Distance:")).show(ui, |ui, _| {
let out = NumberField::length(tl!("Distance:"), Bind::given(Some(distance)), general_lengths(app)).show(ui);
let out = NumberField::length(tl!("Distance:"), Bind::given(Some(distance)), general_lengths(app)).edit_target(target).show(ui);
if let Some(d) = out.events.committed().copied().flatten() {
change = Some(spacing_params("distance", steps, d));
}
@@ -128,7 +276,12 @@ fn settings(app: &mut VectorcraftApp, ui: &mut Ui) {
// Smooth Color picks the count itself: the field shows the steps, disabled.
let on = mode == "steps";
Field::new(tl!("Steps:")).enabled(on).show(ui, |ui, _| {
let out = NumberField::new(tl!("Steps:"), Bind::given(Some(steps))).range(1.0..=1000.0).commit_decimals(0).enabled(on).show(ui);
let out = NumberField::new(tl!("Steps:"), Bind::given(Some(steps)))
.range(1.0..=1000.0)
.commit_decimals(0)
.enabled(on)
.edit_target(target)
.show(ui);
if let Some(n) = out.events.committed().copied().flatten() {
change = Some(spacing_params("steps", n, distance));
}
@@ -160,8 +313,22 @@ fn settings(app: &mut VectorcraftApp, ui: &mut Ui) {
change = Some(json!({"easingType": value}));
}
});
percent_slider(app, ui, tl!("Ramp:"), "ramp", info["ramp"].as_f64(), 0.0..=100.0, selected && spined);
percent_slider(app, ui, tl!("Shift:"), "colorShift", info["colorShift"].as_f64(), -100.0..=100.0, selected);
percent_slider(
app,
ui,
target,
PercentSlider { label: tl!("Ramp:"), key: "ramp", range: 0.0..=100.0 },
info["ramp"].as_f64(),
selected && spined,
);
percent_slider(
app,
ui,
target,
PercentSlider { label: tl!("Shift:"), key: "colorShift", range: -100.0..=100.0 },
info["colorShift"].as_f64(),
selected,
);
if let Some(p) = change {
app.run("object.blend.options", p).ok();
}
+5 -4
View File
@@ -20,7 +20,7 @@ use craft::keymap::CommandRef;
use craft::theme::variant::Tone;
use craft::ui::choice::Segmented;
use craft::ui::contract::{
ActivateOn, Bind, BodyCx, CollectionEvent, DropAt, DropKind, DropPlace, Entry, ListDrag, Props as _, ReorderRule, SelectMode, Show as _,
ActivateOn, Bind, BodyCx, CollectionEvent, DropAt, DropKind, DropPlace, Entry, ListDrag, Props as _, ReorderRule, Scroll, SelectMode, Show as _,
ShowCollection as _, ShowContainer as _, Sizing, Trigger,
};
use craft::ui::display::{Divider, Shade, Text};
@@ -349,13 +349,14 @@ impl<'a> View<'a> {
}
}
/// The list: the ungrouped items, then the groups as sections. A drop anywhere on it away from
/// the items and groups takes an item out of its group, or adds art or a swatch ungrouped.
/// The list: the ungrouped items, then the groups as sections, scrolling under the header when
/// they are taller than the panel. A drop anywhere on it away from the items and groups takes an
/// item out of its group, or adds art or a swatch ungrouped.
fn show(&self, ui: &mut Ui, closed: &mut HashSet<(String, String)>, acts: &RefCell<Vec<Act>>) {
let membership = Arc::clone(&self.membership);
let list = DropAction::new(move |drag: &PanelDrag| membership.landing(drag, None).is_some())
.sizing(Sizing::Fill)
.show(ui, |ui, _| Stack::new().fill().show(ui, |ui, cx| self.contents(ui, cx, closed, acts)));
.show(ui, |ui, _| Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, cx| self.contents(ui, cx, closed, acts)));
if let Some(drag) = &list.output.dropped
&& let Some(act) = self.membership.landing(drag, None)
{
@@ -679,6 +679,34 @@ fn a_shrunk_thumbnail_keeps_its_color_beside_clear_pixels() {
}
}
/// A library longer than the panel scrolls: the wheel over the items brings the last one into view, in the list view
/// and in the thumbnail view, while the footer's New Group stays in view.
#[test]
fn a_long_library_scrolls_with_the_wheel() {
for list in [false, true] {
let mut app = app();
app.run("library.create", json!({"name": "Brand"})).unwrap();
for i in 0..400 {
app.run("library.add", json!({"kind": "fillColor", "color": format!("#{:06x}", i * 0x9731), "name": format!("Swatch {i}")})).unwrap();
}
app.ui.libraries_list_view = list;
let mut panel = Harness::new(app, show);
panel.room(egui::vec2(300.0, 400.0));
panel.frame();
panel.frame();
assert!(panel.in_view("Swatch 0"), "the first item shows (list view {list})");
assert!(!panel.in_view("Swatch 399"), "the last item starts out of view (list view {list})");
let at = panel.rect("Swatch 0").center();
for _ in 0..40 {
panel.scroll_at(at, -400.0);
}
panel.frame();
assert!(panel.in_view("Swatch 399"), "the wheel scrolls the last item into view (list view {list})");
assert!(!panel.in_view("Swatch 0"), "the first item scrolls out of view (list view {list})");
assert!(panel.in_view("New Group"), "the footer stays in view (list view {list})");
}
}
/// Graphic thumbnails decoded while the panel draws one frame.
fn decoded(panel: &mut Harness) -> usize {
super::counters::DECODED.with(|c| c.set(0));
+547
View File
@@ -70,6 +70,104 @@ fn info(p: &Panel) -> Value {
p.app().session.execute("object.blend.info", &json!({})).unwrap()
}
#[test]
fn the_edit_target_is_reused_until_the_document_or_selection_changes() {
use std::sync::Arc;
use vectorcraft_doc::SymbolPart;
use super::blend::edit_target;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let ctx = egui::Context::default();
let art = |app: &mut VectorcraftApp| {
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
let ids: Vec<NodeId> = (0..3)
.map(|i| {
let value = app.run("shape.rectangle", json!({"x": i * 80, "y": 0, "width": 20, "height": 20})).unwrap();
NodeId(value["id"].as_u64().unwrap())
})
.collect();
app.run("select.set", json!({"ids": [ids[0].0, ids[1].0]})).unwrap();
let blend = NodeId(app.run("object.blend.make", json!({"spacing": "steps", "steps": 5})).unwrap()["id"].as_u64().unwrap());
app.run("select.set", json!({"ids": [ids[0].0, blend.0, ids[1].0]})).unwrap();
(ids, blend)
};
let resolved = |app: &VectorcraftApp| edit_target(app, &ctx).unwrap().2;
let (ids, blend) = art(&mut app);
let first = resolved(&app);
assert_eq!(*first, vec![(ids[0], Some(blend)), (blend, Some(blend)), (ids[1], Some(blend))]);
for _ in 0..3 {
assert!(Arc::ptr_eq(&first, &resolved(&app)), "unchanged passes reuse the resolved key");
}
// Release, Undo and Redo change the nearest blends while the selected ids stay the same.
let selection = app.session.active().unwrap().selection.objects.clone();
let mut previous = first.clone();
for (cmd, has_blend) in [("object.blend.release", false), ("edit.undo", true), ("edit.redo", false), ("edit.undo", true)] {
app.run(cmd, json!({})).unwrap();
// Release selects its results; keep the original ids to isolate the document change.
app.session.active_mut().unwrap().selection.objects = selection.clone();
let next = resolved(&app);
assert_ne!(previous, next, "{cmd} changes the nearest blends for the same selected ids");
if has_blend {
assert_eq!(next, first, "Undo restores the nearest blends");
} else {
assert_eq!(*next, vec![(ids[0], None), (blend, None), (ids[1], None)], "Release leaves no nearest blends");
}
assert!(Arc::ptr_eq(&next, &resolved(&app)), "the new revision reuses its resolution");
previous = next;
}
// Only the middle selected id changes, at the same revision, length, first and last id.
app.session.active_mut().unwrap().selection.objects[1] = ids[2];
let changed_selection = resolved(&app);
assert_ne!(previous, changed_selection, "a selection change updates the resolved pairs");
assert_eq!(changed_selection[1], (ids[2], None), "the unblended rectangle has no nearest blend");
assert!(Arc::ptr_eq(&changed_selection, &resolved(&app)), "the new selection reuses its resolution");
// Symbol parts resolve to no blends, including when the selected object ids stay the same.
app.session.active_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: blend, path: vec![0] });
let part = resolved(&app);
assert_ne!(changed_selection, part);
assert_eq!(
*part,
vec![(ids[0], None), (ids[2], None), (ids[1], None)],
"symbol-part selections keep every selected id and resolve none to a blend"
);
assert!(Arc::ptr_eq(&part, &resolved(&app)), "the same symbol part reuses its resolution");
app.session.active_mut().unwrap().selection.symbol_part.as_mut().unwrap().path = vec![1];
let other_part = resolved(&app);
assert!(!Arc::ptr_eq(&part, &other_part), "the key is resolved for the new symbol-part selection");
app.session.active_mut().unwrap().selection.symbol_part = None;
let whole = resolved(&app);
assert_ne!(other_part, whole, "leaving symbol-part selection restores the nearest blends");
assert_eq!(whole, changed_selection);
// The revert count invalidates the cache even at the same revision and selection.
app.session.active_mut().unwrap().reverts += 1;
let reverted = resolved(&app);
assert!(!Arc::ptr_eq(&whole, &reverted), "the key is resolved for the new document state after reverting");
assert!(Arc::ptr_eq(&reverted, &resolved(&app)));
// Another document uses the same ids, revision, revert count and selection.
let st = app.session.active().unwrap();
let (revision, reverts, selection) = (st.revision, st.reverts, st.selection.objects.clone());
let (other_ids, other_blend) = art(&mut app);
assert_eq!((other_ids, other_blend), (ids, blend));
let st = app.session.active_mut().unwrap();
st.revision = revision;
st.reverts = reverts;
st.selection.objects = selection;
let other_document = resolved(&app);
assert!(!Arc::ptr_eq(&reverted, &other_document), "the key is resolved for the new document state in another document");
assert!(Arc::ptr_eq(&other_document, &resolved(&app)));
app.run("document.activate", json!({"index": 0})).unwrap();
let original_document = resolved(&app);
assert!(!Arc::ptr_eq(&other_document, &original_document), "the key is resolved for the new document state when returning to the first document");
assert_eq!(original_document, reverted);
assert!(Arc::ptr_eq(&original_document, &resolved(&app)));
}
#[test]
fn the_controls_are_dimmed_until_a_blend_or_two_objects_are_selected() {
let mut app = app();
@@ -257,3 +355,452 @@ fn ramp_and_reverse_spine_are_dimmed_while_a_selected_key_belongs_to_a_blend_wit
p.frame();
assert!(!p.enabled("Ramp:") && !p.enabled("Reverse Spine"));
}
#[test]
fn an_unfinished_steps_or_distance_value_does_not_reach_another_blend() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
// Two blends with the same spacing; typing starts on `a`, and `b` is selected before the value is finished.
let (mut app, a, b) = two_blends(json!({"smooth": true}));
app.run("object.blend.options", json!({"spacing": "steps", "steps": 5})).unwrap();
app.run("select.set", json!({"ids": [a.0]})).unwrap();
let mut p = Panel::new(app, show);
let spacings = |p: &Panel| {
let app = p.app();
(spec(&app, a).spacing, spec(&app, b).spacing)
};
let unfinished = |p: &mut Panel, name: &str| {
p.click_role(name, Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
};
unfinished(&mut p, "Steps:");
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.frame();
assert_eq!(p.value_role("Steps:", Role::SPIN_BUTTON).as_deref(), Some("5"), "the field shows the other blend's steps");
p.type_text("1");
p.key(Key::Enter, Modifiers::NONE);
assert_eq!(spacings(&p), (BlendSpacing::Steps(5), BlendSpacing::Steps(1)), "b takes 1 step, not 3+1");
p.app().run("select.set", json!({"ids": [a.0, b.0]})).unwrap();
p.app().run("object.blend.options", json!({"spacing": "distance", "distance": 10})).unwrap();
p.app().run("select.set", json!({"ids": [a.0]})).unwrap();
p.frame();
unfinished(&mut p, "Distance:");
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.frame();
p.type_text("1");
p.key(Key::Enter, Modifiers::NONE);
assert_eq!(spacings(&p), (BlendSpacing::Distance(10.0), BlendSpacing::Distance(1.0)), "b takes 1 pt, not 3+1");
}
#[test]
fn an_unfinished_ramp_or_shift_value_does_not_reach_another_blend() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
// Two blends with a spine and the same Ramp and Shift; typing starts on `a`, and `b` is selected before the value
// is finished.
let (mut app, a, b) = two_blends(json!({"smooth": true, "orientation": "path"}));
app.run("object.blend.options", json!({"ramp": 30, "colorShift": 30})).unwrap();
let mut p = Panel::new(app, show);
for name in ["Ramp:", "Shift:"] {
let value = |s: &BlendSpec| if name == "Ramp:" { s.ease.ramp * 100.0 } else { s.color_shift };
p.app().run("select.set", json!({"ids": [a.0]})).unwrap();
p.frame();
p.click_role(name, Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.frame();
assert_ne!(p.value_role(name, Role::SPIN_BUTTON).as_deref(), Some("3+"), "{name} drops the value typed for a");
p.type_text("1");
p.key(Key::Enter, Modifiers::NONE);
let (at_a, at_b) = {
let app = p.app();
(value(&spec(&app, a)), value(&spec(&app, b)))
};
assert!((at_a - 30.0).abs() < 1e-9 && (at_b - 1.0).abs() < 1e-9, "{name}: a keeps 30, b takes 1, not 3+1: {at_a} {at_b}");
}
}
#[test]
fn a_disabled_ramp_drops_its_draft_and_does_not_take_focus_when_enabled_again() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let (mut app, a, b) = two_blends(json!({"smooth": true, "createSpine": "never"}));
app.run("select.set", json!({"ids": [a.0]})).unwrap();
app.run("object.blend.options", json!({"ramp": 30})).unwrap();
let (before_a, before_b, depth) = (spec(&app, a), spec(&app, b), undo_depth(&app));
let mut p = Panel::new(app, show);
p.click_role("Ramp:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("12");
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.frame();
assert!(!p.enabled("Ramp:"), "the blend without a spine disables Ramp");
assert_eq!(spec(&p.app(), a), before_a, "disabling Ramp leaves a's draft uncommitted");
assert_eq!(spec(&p.app(), b), before_b, "disabling Ramp leaves b unchanged");
p.app().run("select.set", json!({"ids": [a.0]})).unwrap();
p.frame();
p.frame();
assert!(p.enabled("Ramp:"), "the blend with a spine enables Ramp again");
assert!(!p.focused_role("Ramp:", Role::SPIN_BUTTON), "enabling Ramp does not return focus to its number field");
assert!(!p.focused_role("Ramp:", Role::SLIDER), "enabling Ramp does not return focus to its track");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
assert_eq!(spec(&p.app(), a), before_a, "a keeps 30 without an explicit focus move to Ramp");
assert_eq!(spec(&p.app(), b), before_b, "the draft never changes b");
assert_eq!(undo_depth(&p.app()), depth, "dropping the draft adds no undo step");
}
#[test]
fn an_unfinished_ramp_or_shift_value_is_gone_when_its_blend_is_selected_again() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
// `3+` typed for `a`, `b` selected, then `a` selected again: the field shows a's value, and `1` and Enter give 1.
let (mut app, a, b) = two_blends(json!({"smooth": true, "orientation": "path"}));
app.run("object.blend.options", json!({"ramp": 30, "colorShift": 30})).unwrap();
let mut p = Panel::new(app, show);
for name in ["Ramp:", "Shift:"] {
let value = |s: &BlendSpec| if name == "Ramp:" { s.ease.ramp * 100.0 } else { s.color_shift };
p.app().run("select.set", json!({"ids": [a.0]})).unwrap();
p.frame();
p.click_role(name, Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.frame();
p.app().run("select.set", json!({"ids": [a.0]})).unwrap();
p.frame();
assert_ne!(p.value_role(name, Role::SPIN_BUTTON).as_deref(), Some("3+"), "{name} drops the value typed for a before b was selected");
p.type_text("1");
p.key(Key::Enter, Modifiers::NONE);
let (at_a, at_b) = {
let app = p.app();
(value(&spec(&app, a)), value(&spec(&app, b)))
};
assert!((at_a - 1.0).abs() < 1e-9 && (at_b - 30.0).abs() < 1e-9, "{name} a takes 1, not 3+1, and b keeps 30: {at_a} {at_b}");
}
}
#[test]
fn a_tab_in_the_frame_that_selects_another_blend_drops_the_unfinished_value_and_moves_the_focus_on() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
// `12` typed into Ramp for `a` and not committed; `b` is selected and Tab pressed in the same frame. Neither blend
// takes 12, and the focus leaves Ramp, so the next digits and Enter do not change b's Ramp either.
let (mut app, a, b) = two_blends(json!({"smooth": true, "orientation": "path"}));
app.run("object.blend.options", json!({"ramp": 30, "colorShift": 30})).unwrap();
app.run("select.set", json!({"ids": [a.0]})).unwrap();
let mut p = Panel::new(app, show);
p.click_role("Ramp:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("12");
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.key(Key::Tab, Modifiers::NONE);
p.frame();
let ramps = |p: &Panel| {
let app = p.app();
(spec(&app, a).ease.ramp, spec(&app, b).ease.ramp)
};
let (at_a, at_b) = ramps(&p);
assert!((at_a - 0.3).abs() < 1e-9 && (at_b - 0.3).abs() < 1e-9, "the Tab commits 12 to neither blend: {at_a} {at_b}");
p.key(Key::A, Modifiers::COMMAND);
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
let (at_a, at_b) = ramps(&p);
assert!((at_a - 0.3).abs() < 1e-9 && (at_b - 0.3).abs() < 1e-9, "Ramp keeps 30 on a and b after the Tab: {at_a} {at_b}");
}
#[test]
fn a_shift_tab_to_the_track_while_selecting_another_blend_drops_the_number_draft() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
for name in ["Ramp:", "Shift:"] {
let (mut app, a, b) = two_blends(json!({"smooth": true, "orientation": "path"}));
app.run("object.blend.options", json!({"ramp": 30, "colorShift": 30})).unwrap();
app.run("select.set", json!({"ids": [a.0]})).unwrap();
let mut p = Panel::new(app, show);
p.click_role(name, Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("12");
let (before_a, before_b, depth) = {
let app = p.app();
(spec(&app, a), spec(&app, b), undo_depth(&app))
};
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.key(Key::Tab, Modifiers::SHIFT);
assert_eq!(spec(&p.app(), a), before_a, "{name} leaves a unchanged");
assert_eq!(spec(&p.app(), b), before_b, "{name} drops the draft instead of committing it to b on Shift+Tab");
assert_eq!(undo_depth(&p.app()), depth, "{name} drops the draft without an undo step");
assert!(p.focused_role(name, Role::SLIDER), "{name} keeps focus on its track");
p.key(Key::ArrowRight, Modifiers::NONE);
assert_eq!(spec(&p.app(), a), before_a, "{name} leaves a unchanged after the arrow key");
assert_ne!(spec(&p.app(), b), before_b, "{name} moves b with the focused track's arrow key");
}
}
#[test]
fn a_click_in_the_frame_that_selects_another_blend_keeps_the_focus_it_gives() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
// `12` typed into Ramp for `a` and not committed; `b` is selected and Shift's number field clicked in the same
// frame. Ramp keeps 30 on both blends, and the typing that follows goes to b's Shift.
let (mut app, a, b) = two_blends(json!({"smooth": true, "orientation": "path"}));
app.run("object.blend.options", json!({"ramp": 30, "colorShift": 30})).unwrap();
app.run("select.set", json!({"ids": [a.0]})).unwrap();
let mut p = Panel::new(app, show);
p.click_role("Ramp:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("12");
let shift = p.rect_role("Shift:", Role::SPIN_BUTTON).center();
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.press_at_next_frame(shift);
p.release();
p.key(Key::A, Modifiers::COMMAND);
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
let app = p.app();
let (ramp_a, ramp_b, shift_b) = (spec(&app, a).ease.ramp, spec(&app, b).ease.ramp, spec(&app, b).color_shift);
assert!((ramp_a - 0.3).abs() < 1e-9 && (ramp_b - 0.3).abs() < 1e-9, "Ramp keeps 30 on a and b: {ramp_a} {ramp_b}");
assert!((shift_b - 7.0).abs() < 1e-9, "the click gives the focus to Shift, which takes 7 on b: {shift_b}");
}
#[test]
fn a_click_on_ramp_while_selecting_another_blend_focuses_its_replacement_number_field() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let (mut app, a, b) = two_blends(json!({"smooth": true, "orientation": "path"}));
app.run("object.blend.options", json!({"ramp": 30})).unwrap();
app.run("select.set", json!({"ids": [a.0]})).unwrap();
let mut p = Panel::new(app, show);
p.click_role("Ramp:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("12");
let ramp = p.rect_role("Ramp:", Role::SPIN_BUTTON).center();
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.press_at_next_frame(ramp);
p.release();
p.key(Key::A, Modifiers::COMMAND);
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
let app = p.app();
let (at_a, at_b) = (spec(&app, a).ease.ramp, spec(&app, b).ease.ramp);
assert!((at_a - 0.3).abs() < 1e-9, "a keeps 30 after the draft is dropped: {at_a}");
assert!((at_b - 0.07).abs() < 1e-9, "the same-row click focuses b's Ramp, which takes 7: {at_b}");
}
#[test]
fn a_same_frame_click_on_ramp_while_selecting_another_blend_focuses_its_replacement_number_field() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let (mut app, a, b) = two_blends(json!({"smooth": true, "orientation": "path"}));
app.run("object.blend.options", json!({"ramp": 30})).unwrap();
app.run("select.set", json!({"ids": [a.0]})).unwrap();
let mut p = Panel::new(app, show);
p.click_role("Ramp:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("12");
let ramp = p.rect_role("Ramp:", Role::SPIN_BUTTON).center();
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.click_at_next_frame(ramp);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
let app = p.app();
let (at_a, at_b) = (spec(&app, a).ease.ramp, spec(&app, b).ease.ramp);
assert!((at_a - 0.3).abs() < 1e-9, "a keeps 30 after the draft is dropped: {at_a}");
assert!((at_b - 0.07).abs() < 1e-9, "the same-frame click focuses b's Ramp, which takes 7: {at_b}");
}
#[test]
fn a_secondary_press_on_ramp_while_selecting_another_blend_drops_its_draft_without_taking_focus() {
use craft::ui::contract::Role;
use egui::{Event, Key, Modifiers, PointerButton};
let (mut app, a, b) = two_blends(json!({"smooth": true, "orientation": "path"}));
app.run("object.blend.options", json!({"ramp": 30})).unwrap();
app.run("select.set", json!({"ids": [a.0]})).unwrap();
let mut p = Panel::new(app, show);
p.click_role("Ramp:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("12");
let ramp = p.rect_role("Ramp:", Role::SLIDER).center();
let (before_a, before_b, depth) = {
let app = p.app();
(spec(&app, a), spec(&app, b), undo_depth(&app))
};
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.frame_with(vec![
Event::PointerMoved(ramp),
Event::PointerButton { pos: ramp, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
]);
assert!(!p.focused_role("Ramp:", Role::SPIN_BUTTON), "a secondary press does not focus Ramp's number field");
assert!(!p.focused_role("Ramp:", Role::SLIDER), "a secondary press does not focus Ramp's track");
p.frame_with(vec![Event::PointerButton { pos: ramp, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]);
p.key(Key::Enter, Modifiers::NONE);
assert_eq!(spec(&p.app(), a), before_a, "the secondary press leaves a unchanged");
assert_eq!(spec(&p.app(), b), before_b, "the secondary press drops the draft without committing it to b");
assert_eq!(undo_depth(&p.app()), depth, "dropping the draft adds no undo step");
}
#[test]
fn a_ramp_drag_ends_and_the_track_keeps_the_focus_across_a_selection_change() {
use egui::{Key, Modifiers};
// A Ramp drag on `a`, `b` selected before the release: by the release the drag has ended as one undo step on `a`,
// with no interaction left open. The track keeps the focus, so an arrow key then changes `b`.
let (mut app, a, b) = two_blends(json!({"smooth": true, "orientation": "path"}));
app.run("object.blend.options", json!({"ramp": 30})).unwrap();
app.run("select.set", json!({"ids": [a.0]})).unwrap();
let depth = undo_depth(&app);
let mut p = Panel::new(app, show);
p.drag_hold_role("Ramp:", craft::ui::contract::Role::SLIDER, egui::vec2(60.0, 0.0));
assert!(p.app().session.in_interaction(), "the drag is in progress");
p.app().run("select.set", json!({"ids": [b.0]})).unwrap();
p.frame();
p.release();
assert!(!p.app().session.in_interaction(), "the drag has ended by the release");
let (dragged, before_b) = {
let app = p.app();
(spec(&app, a).ease.ramp, spec(&app, b).ease.ramp)
};
assert!(dragged > 0.3, "the drag changed a: {dragged}");
assert!((before_b - 0.3).abs() < 1e-9, "the drag left b alone: {before_b}");
assert_eq!(undo_depth(&p.app()), depth + 1, "the drag is one undo step");
p.key(Key::ArrowRight, Modifiers::NONE);
let (at_a, at_b) = {
let app = p.app();
(spec(&app, a).ease.ramp, spec(&app, b).ease.ramp)
};
assert!((at_a - dragged).abs() < 1e-9 && at_b > before_b, "the arrow key changes b, not a: {at_a} {at_b}");
}
#[test]
fn an_unfinished_steps_value_stays_with_its_blend_and_document() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
// The same document built twice: the second document's blend has the same id and the same steps as the first's.
let (mut app, id) = blended();
app.run("object.blend.options", json!({"spacing": "steps", "steps": 5})).unwrap();
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
app.run("shape.rectangle", json!({"x": 200, "y": 0, "width": 20, "height": 20})).unwrap();
app.run("select.all", json!({})).unwrap();
let other = NodeId(app.run("object.blend.make", json!({"spacing": "steps", "steps": 5})).unwrap()["id"].as_u64().unwrap());
assert_eq!(other, id, "both documents' blends have the same id");
app.run("document.activate", json!({"index": 0})).unwrap();
let mut p = Panel::new(app, show);
let steps = |p: &mut Panel, index: u64| {
p.app().run("document.activate", json!({"index": index})).unwrap();
spec(&p.app(), id).spacing
};
let unfinished = |p: &mut Panel| {
p.click_role("Steps:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
};
// With the selection and the document unchanged, the value typed so far is kept: 3+1 gives 4.
unfinished(&mut p);
p.frame();
p.type_text("1");
p.key(Key::Enter, Modifiers::NONE);
assert_eq!(spec(&p.app(), id).spacing, BlendSpacing::Steps(4), "an unchanged target keeps the typed value");
p.app().run("object.blend.options", json!({"spacing": "steps", "steps": 5})).unwrap();
// Another document with the same selection drops it.
unfinished(&mut p);
p.app().run("document.activate", json!({"index": 1})).unwrap();
p.frame();
p.type_text("1");
p.key(Key::Enter, Modifiers::NONE);
assert_eq!((steps(&mut p, 0), steps(&mut p, 1)), (BlendSpacing::Steps(5), BlendSpacing::Steps(1)), "the other document takes 1 step");
}
#[test]
fn an_unfinished_steps_value_is_dropped_when_a_targeted_layer_loses_a_blend() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
// Blend `a` on the first artboard and `b` on the second, both at 5 steps, with their layer targeted.
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300, "artboards": 2})).unwrap();
let blend_at = |app: &mut VectorcraftApp, board: usize| {
let at = app.session.active().unwrap().doc.artboards[board].rect;
let ids: Vec<Value> = [0.0, 200.0]
.map(|x| app.run("shape.rectangle", json!({"x": at.x0 + x, "y": at.y0, "width": 20, "height": 20})).unwrap()["id"].clone())
.into();
app.run("select.set", json!({"ids": ids})).unwrap();
NodeId(app.run("object.blend.make", json!({"spacing": "steps", "steps": 5})).unwrap()["id"].as_u64().unwrap())
};
let a = blend_at(&mut app, 0);
let b = blend_at(&mut app, 1);
let layer = app.session.active().unwrap().doc.layers[0].id;
app.run("layer.target", json!({"id": layer.0})).unwrap();
let mut p = Panel::new(app, show);
p.click_role("Steps:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
// Locking the first artboard deselects `a`; the layer stays targeted.
p.app().run("artboard.setProps", json!({"index": 0, "locked": true})).unwrap();
{
let app = p.app();
let sel = &app.session.active().unwrap().selection;
assert_eq!((sel.objects.clone(), sel.subjects().to_vec()), (vec![b], vec![layer]), "only b is selected, under the targeted layer");
}
p.frame();
p.type_text("1");
p.key(Key::Enter, Modifiers::NONE);
let app = p.app();
assert_eq!((spec(&app, a).spacing, spec(&app, b).spacing), (BlendSpacing::Steps(5), BlendSpacing::Steps(1)), "b takes 1 step, not 3+1");
}
#[test]
fn an_unfinished_steps_value_is_dropped_when_the_selected_keys_lose_their_blend() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let mut app = app();
let keys = app.session.active().unwrap().selection.objects.clone();
app.run("object.blend.options", json!({"spacing": "steps", "steps": 5})).unwrap();
app.run("object.blend.make", json!({"createSpine": "never"})).unwrap();
app.run("select.set", json!({"ids": keys.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
let mut p = Panel::new(app, show);
assert_eq!(info(&p)["target"], "blend");
p.click_role("Steps:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("object.blend.release", json!({})).unwrap();
assert_eq!(p.app().session.active().unwrap().selection.objects, keys, "Release keeps the same keys selected");
assert_eq!(info(&p)["target"], "defaults");
p.frame();
p.type_text("1");
p.key(Key::Enter, Modifiers::NONE);
assert_eq!(info(&p)["steps"], 1, "the new-blend defaults take 1 step, not 3+1");
}
#[test]
fn an_unfinished_steps_value_is_dropped_by_file_revert() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let (mut app, id) = blended();
app.run("object.blend.options", json!({"spacing": "steps", "steps": 5})).unwrap();
let dir = vectorcraft_testkit::TempDir::new("blend-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Blend.vectorcraft")})).unwrap();
// An unsaved change for Revert to undo, leaving the blend as saved.
app.run("shape.rectangle", json!({"x": 100, "y": 200, "width": 20, "height": 20})).unwrap();
app.run("select.set", json!({"ids": [id.0]})).unwrap();
let mut p = Panel::new(app, show);
p.click_role("Steps:", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
// The restored document has the same blend and, selected again, the same selection.
p.app().run("file.revert", json!({"confirmed": true})).unwrap();
p.app().run("select.set", json!({"ids": [id.0]})).unwrap();
p.frame();
p.type_text("1");
p.key(Key::Enter, Modifiers::NONE);
assert_eq!(spec(&p.app(), id).spacing, BlendSpacing::Steps(1), "Revert drops the unfinished value");
}
+3 -2
View File
@@ -735,7 +735,7 @@ fn set_aside_import_options(p: &mut Value) {
let ext = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension).unwrap_or_default();
let keys: &[&str] = match ext.as_str() {
"pdf" | "ai" | "ait" => &["page", "crop"],
"dxf" | "dwg" => &["dxf"],
e if crate::dialogs::dxf_import::is_drawing_ext(e) => &["dxf"],
"psd" | "pdd" | "psb" => &["layers", "hiddenLayers", "importSlices"],
_ if crate::dialogs::text_import::is_text(p) => &["text"],
_ => &[],
@@ -778,7 +778,8 @@ fn clicked_at_full_size(app: &VectorcraftApp, p: &Value) -> Value {
return p;
}
let Some(name) = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::file_name) else { return p };
if !matches!(fileio::extension(&name).as_str(), "pdf" | "ai" | "ait" | "dxf" | "dwg") {
let ext = fileio::extension(&name);
if !matches!(ext.as_str(), "pdf" | "ai" | "ait") && !crate::dialogs::dxf_import::is_drawing_ext(&ext) {
return p;
}
let r: Vec<f64> = p.get("rect").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
+24
View File
@@ -113,6 +113,30 @@ pub(crate) fn run_fired(app: &mut crate::VectorcraftApp, ctx: &egui::Context) {
let _ = app.frame_input(take_output(ctx));
}
/// The reply to `req`, which [`crate::control::handle`] answered with `reply` just before, as the app sends it on
/// `answer` ([`crate::VectorcraftApp::settle_control`]): at once, or for a confirm that filed a dialog's held OK, after
/// the frame whose dialog pump accepted or refused that OK. For that frame the app answers a control channel that
/// holds the reply.
pub(crate) fn settled_reply(
app: &mut crate::VectorcraftApp,
ctx: &egui::Context,
req: craft::automation::ControlRequest,
answer: &std::sync::mpsc::Receiver<serde_json::Value>,
reply: craft::automation::Reply,
) -> serde_json::Value {
let (_requests, rx) = std::sync::mpsc::channel();
let previous = app.channel.replace(craft::automation::ControlChannel::new(rx));
let now = app.instant();
app.settle_control(req, reply, None, 0.0, now);
let sent = answer.try_recv().or_else(|_| {
app_frame(app, ctx, egui::RawInput::default());
answer.try_recv()
});
app.channel = previous;
app.held_confirms.clear();
sent.unwrap_or_else(|_| serde_json::json!({"ok": false, "error": "no reply after the frame that pumps the dialogs"}))
}
/// Held by a test that changes the custom dictionary, which the whole process shares, or that needs it to hold still:
/// every change moves the dictionary's generation, and a Check Spelling walk that sees it move checks its scope again
/// from the start.
+46
View File
@@ -161,6 +161,45 @@ fn control_saves_leave_out_the_documents_file_outside_the_read_root() {
let _ = std::fs::remove_dir_all(base);
}
/// A confirm's reply held on a dialog's OK, sent once the app answers it, shows a path outside the read root that the
/// request sent by its file name only, as a reply sent at once does.
#[test]
fn a_held_confirm_hides_the_paths_outside_the_read_root() {
let (mut app, _tx, base) = confined("held-confirm");
let outside = s(base.join("outside/b.svg"));
let params = json!({"fields": [{"field": "file", "value": outside}], "action": "confirm"});
let (mut req, reply) = ControlRequest::new("ui.dialog.set", params);
app.held_confirms.push(crate::control::HeldConfirm::hold(&mut req, None, crate::control::Hiding::default()));
// The control channel answers the held confirm with the app's refusal.
req.reply.send(json!({"ok": false, "error": format!("cannot read {outside}")})).unwrap();
app.poll_held();
let r = reply.try_recv().expect("the reply is sent once the answer has come");
assert_eq!(r["ok"], false, "{r}");
assert!(!r.to_string().contains(&s(base.join("outside"))), "{r}");
assert!(r["error"].as_str().is_some_and(|e| e.contains("b.svg")), "{r}");
assert!(app.held_confirms.is_empty(), "no confirm waits");
let _ = std::fs::remove_dir_all(base);
}
/// A `ui.dialog.set` with an `action` on Preferences replies with the dialog's fields as `ui.inspect`
/// shows them: a folder preference outside the read root is left out.
#[test]
fn a_preferences_set_with_an_action_hides_the_folders_outside_the_read_root() {
let (mut app, tx, base) = confined("prefs-set-action");
let (inside, outside) = (s(base.join("in")), s(base.join("outside")));
crate::prefs_dialog::open(&mut app, None);
// The person types the folder: their request is not confined.
let (fill, _) = ControlRequest::new("ui.dialog.set", json!({"fields": [{"field": "templatesFolder", "value": outside}]}));
let Reply::Done(filled) = crate::control::handle(&mut app, &crate::testing::ui_context(), &fill) else { panic!("deferred") };
assert_eq!(filled["ok"], true, "{filled}");
let params = json!({"dialog": "preferences", "fields": [{"field": "fontsFolder", "value": inside}], "action": "cancel"});
let r = request(&mut app, &tx, "ui.dialog.set", params);
let fields = r["result"]["dialog"]["fields"].as_object().unwrap_or_else(|| panic!("no fields: {r}"));
assert_eq!((fields["fontsFolder"].as_str(), fields.get("templatesFolder")), (Some(inside.as_str()), None), "{r}");
assert!(!r.to_string().contains(&outside), "no path outside the root: {r}");
let _ = std::fs::remove_dir_all(base);
}
/// In one session with a library loaded from outside the read root: the library keeps its file-name
/// id, a reply that names its path shows the file name, a save without a path leaves out the
/// document's file, and a save or export to a path the client gave in the write root keeps that path
@@ -1782,6 +1821,13 @@ fn dialog_set_allows_hidden_controls() {
let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__search", "value": "grid"}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!(crate::prefs_dialog::fields(&app).unwrap()["__search"], "grid");
// With an `action`, Preferences replies `{dialog, result}` as the hosted dialogs do.
let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__search", "value": "rulers", "action": "cancel"}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!(r["result"]["dialog"]["kind"], "preferences", "{r}");
assert_eq!(r["result"]["dialog"]["fields"]["__search"], "rulers", "{r}");
assert_eq!(r["result"].get("result"), Some(&Value::Null), "{r}");
assert!(!crate::prefs_dialog::is_open(&app), "canceled in the same request");
}
/// Save PDF's and Print's OK export and print: `ui.dialog.set` can't add a preset name to turn OK
+7 -7
View File
@@ -77,10 +77,10 @@ fn samples_show_the_text_in_the_family_or_a_generic_sample() {
/// A face with no hinting instructions draws a sample in a context the app has adopted, as the font list and the
/// font picker draw each family's sample in its own face (a document face of the context): a Hebrew letter that is a
/// bar 20 by 700 thousandths of an em, whose blue zones the automatic hinter of skrifa 0.44 never finishes measuring.
/// The face is served to the fixture's context only, so the font database other tests read does not change. The
/// sample is one rasterized glyph from that face. It is drawn on a thread of its own, and the test fails when it has
/// not ended after 300 s.
/// bar 20 by 700 thousandths of an em. The context hints text in both themes, so the sample goes through skrifa's
/// automatic hinter, whose blue-zone search for such a letter ends with the pinned skrifa. The face is served to the
/// fixture's context only, so the font database other tests read does not change. The sample is one rasterized glyph
/// from that face. It is drawn on a thread of its own, and the test fails when it has not ended after 300 s.
#[test]
fn a_face_without_hinting_instructions_draws_its_sample() {
use std::sync::{Arc, Mutex};
@@ -145,9 +145,9 @@ fn a_face_without_hinting_instructions_draws_its_sample() {
let (texts, [hinting, light_hinting, dark_hinting], fixture_has_glyph, nonempty_glyph) =
rx.recv_timeout(std::time::Duration::from_secs(300)).unwrap_or_else(|e| panic!("drawing the sample: {e}"));
assert!(texts.iter().any(|t| t == "\u{5d1}"), "the sample is the letter, in the face: {texts:?}");
assert!(!hinting, "a context the app adopts draws text without hinting");
assert!(!light_hinting, "the light theme draws text without hinting");
assert!(!dark_hinting, "the dark theme draws text without hinting");
assert!(hinting, "a context the app adopts hints text");
assert!(light_hinting, "the light theme hints text");
assert!(dark_hinting, "the dark theme hints text");
assert!(fixture_has_glyph, "the sample's face maps U+05D1");
assert!(nonempty_glyph, "the sample is one rasterized glyph for U+05D1");
}
+22
View File
@@ -217,6 +217,23 @@ impl Panel {
self.after();
}
/// Presses at `pos` in the next frame without a preceding hover frame and keeps the button down until [`Panel::release`].
pub(crate) fn press_at_next_frame(&mut self, pos: Pos2) {
self.frame_with(vec![
Event::PointerMoved(pos),
Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
]);
}
/// Clicks at `pos` with a primary press and release in the next frame, without a preceding hover frame.
pub(crate) fn click_at_next_frame(&mut self, pos: Pos2) {
self.frame_with(vec![
Event::PointerMoved(pos),
Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
]);
}
/// Presses on the control named `name` and keeps the button down until [`Panel::release`].
pub(crate) fn press(&mut self, name: &str) {
let target = self.find_aimed(name);
@@ -510,6 +527,11 @@ impl Panel {
self.fixture.tree().focused_key() == self.look(name).node
}
/// Whether the control of `role` named `name` has the focus, where nodes of other roles share the name.
pub(crate) fn focused_role(&self, name: &str, role: Role) -> bool {
self.fixture.tree().focused_key() == self.look_role(name, role).node
}
/// Whether the row or item named `name` reports itself selected.
pub(crate) fn selected(&self, name: &str) -> bool {
self.fixture.tree().selected_of(self.look(name).node).unwrap_or(false)
@@ -853,6 +853,9 @@ fn ui_dialog_set_with_an_action_gives_the_event() {
let fields = json!({"fields": [{"field": "event", "value": "change"}, {"field": "control", "value": "name"}, {"field": "value", "value": "Ann"}], "action": "confirm"});
let r = run(&mut app, "ui.dialog.set", fields);
assert_eq!(r["ok"], true, "{r}");
// A set with an `action` replies `{dialog, result}`: the dialog as the set left it, and the answer's result.
assert!(r["result"]["dialog"]["fields"].is_object(), "{r}");
assert!(r["result"].get("result").is_some(), "{r}");
assert!(until_window(&mut app));
let r = run(&mut app, "ui.dialog.set", json!({"field": "title", "value": "x"}));
assert_eq!(r["ok"], false, "the title is read only: {r}");
+7 -3
View File
@@ -8,11 +8,15 @@ use vectorcraft_engine::Session;
use crate::VectorcraftApp;
/// Send one control request (it must succeed).
/// Send one control request (it must succeed). A confirm that files a dialog's held OK is answered in the frames the
/// test runs after it, which check what the OK did.
pub(crate) fn control(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: Value) {
let (req, _rx) = ControlRequest::new(method, params);
let Reply::Done(r) = crate::control::handle(app, ctx, &req) else { panic!("not done") };
assert_eq!(r["ok"], true, "{r}");
match crate::control::handle(app, ctx, &req) {
Reply::Done(r) => assert_eq!(r["ok"], true, "{r}"),
Reply::AfterHeldOk { .. } => {}
_ => panic!("not done"),
}
}
/// One whole app frame (`tick` and `ui`, as production runs them) in an 800 × 600 window with
-11
View File
@@ -24,17 +24,6 @@ pub fn ui_fonts() -> UiFonts<'static> {
}
}
/// Turns font hinting off for all text `ctx` draws, in both themes. With hinting on, egui hints a TrueType face that
/// has no hinting instructions (no `fpgm`, no `prep` and no glyph instructions) with skrifa 0.44's automatic hinter,
/// whose blue-zone search never ends for some glyphs, such as a tall narrow Hebrew letter, so the font list stops
/// responding when a row draws such a face. The font list and the samples get their faces through craft-libs, which
/// sets no hinting option per face, so the switch covers every face of the context. Hinting stays off until the
/// skrifa blue-zone exit (storytold/craft-libs#5222) is in the build; the craft-libs pin that brings it removes this
/// function and its call.
pub(crate) fn hinting_off(ctx: &egui::Context) {
ctx.all_styles_mut(|style| style.visuals.text_options.font_hinting = false);
}
#[derive(Clone)]
struct FontSelection {
language: Lang,
+1 -1
View File
@@ -114,7 +114,7 @@ the two can still win that race.
| `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above |
| `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls, Cmd-wheel (Ctrl on Windows and Linux) scrolls sideways and Alt-wheel (Option on the Mac) zooms about the pointer (with the `ctrlWheelScrollsSideways` preference off, Cmd-wheel zooms too); with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it. Over the canvas, the wheel preferences in `docs/mcp.md` change what these keys do |
| `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `outline`: View › Outline for the active document only (each document has its own, a document opens in Preview, and `ui.inspect` shows it as `view.outline`; an error without a document). `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) |
| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section`, `__allArtboards` and `__bleedLinked` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences; Save PDF's and Print's `__savePresetAs`, the preset name, only while Save Preset… asks for it, since OK then saves a preset), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass, Texturizer and Rough Pastels effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `<kind>` dialog cannot set protected field `<field>`", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes |
| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section`, `__allArtboards` and `__bleedLinked` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences; Save PDF's and Print's `__savePresetAs`, the preset name, only while Save Preset… asks for it, since OK then saves a preset), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass, Texturizer and Rough Pastels effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `<kind>` dialog cannot set protected field `<field>`", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes. When the dialog waits for the app to accept or refuse its OK (a color adjustment refuses OK while another document is the active one), `ui.dialog.confirm` and `action: "confirm"` reply once the app has answered: `null` (`result: null` for `action`) when it accepts the OK, and the app's refusal as the error when it refuses it, with the dialog left open. A confirm whose dialog closes first is the error "the dialog closed while its OK waited for the app's answer" |
| `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error |
| `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` |
| `ui.resize` | `{width?, height?}` | request the window's inner size; omitted or null `width` and `height` default to 1440 and 900. Returns `null` |
+1 -1
View File
@@ -378,7 +378,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's
| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) |
| PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | |
| PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) |
| WebP | export (Export for Screens) | yes | yes (lossless by default; `lossless: false` writes lossy WebP at `quality` 0–100, default 90) | lossy files are `VP8 `, with an `ALPH` chunk when some pixels are not opaque; `tests_text.rs` |
| WebP | export (Export for Screens) | yes | yes (lossless by default; `lossless: false` writes lossy WebP at `quality` 0–100, default 90; `embedIcc`, default on, writes the sRGB profile in an `ICCP` chunk) | lossy files are `VP8 `, with an `ALPH` chunk when some pixels are not opaque; `tests_text.rs` |
| JPEG XL `.jxl` | — | yes (first frame; 16-bit and floating-point samples as 8 bits, alpha kept; CMYK refused) | no | decoded with jxl-oxide; the size is checked from the header before decoding; container Exif resolution sizes opened and placed images; tests in `crates/engine/src/cmd/fileio/tests_jxlread.rs` and `crates/engine/tests/import_fuzz.rs` |
| HEIC / HEIF | open, place | yes (HEVC-coded still images: single pictures and grids of tiles, 8 to 10 bits, with an alpha image; image sequences, other codings and grids of cropped tiles are refused) | no | `.heic`, `.heif`; decoded by heic-rs in the engine's default `heif` feature (a build without it refuses the files with a message); the container's rotation, mirror and crop are applied; without an `nclx` box the HEVC stream's video signal type gives the matrix and range; an RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; EXIF resolution tags size the image, or 72 ppi; bounded decoding; `tests_heifread.rs` |
| Layered raster `.pcraft` | open, place | yes (as one image: the full-size composite when the file has one; else the layers combined at the canvas size when the document is RGB at 8 or 16 bits and every visible layer is a Normal raster layer without clipping, layer effects, a vector mask, a frame, advanced blending or a feathered layer mask; else the composite preview, with a warning when it is smaller than the canvas) | no | read with craft-doc; sized by the document's resolution, the preview at the canvas's size (at least 1 ppi); a linked file is read the same way again when it is updated; a missing or damaged full-size composite or preview is an error; `tests_pcraftread.rs` |
+3 -2
View File
@@ -870,8 +870,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
character and paragraph attributes, their links to each other and the stories they form, its character and
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries.
`Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms.
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a
document's `fullName`, `path` and `saved`, and close it with `Document.close`.
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile`,
`Document.exportForScreens` and `app.open`, read a document's `fullName`, `path` and `saved`, and close it with
`Document.close`.
Scripts also have each document's linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem`
and `RasterItem`), and trace them with `trace()`, which gives the Image Trace object as a `PluginItem` with its
`TracingObject` and `TracingOptions`; the tracing options VectorCraft has no setting for are still missing.
+157 -19
View File
@@ -876,11 +876,11 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions
| `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. When some of those commands painted objects and others painted none (a fill while the Shape Builder is the active tool, say), `unpainted` lists the commands that painted none, with a `note`. |
| `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). |
| `type_text` | `{text}` | Remote only. |
| `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields, action?}` (a missing `value` is `null`). The app stores all of them or none, then answers that same dialog with `action` in the same request: `confirm` (OK) or `cancel`. Another connection cannot open a dialog between the two steps. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. `set` cannot change a `__` field other than the dialog's controls held under a `__` name (such as Save PDF's `__section` or the Preferences `__search`): the `__command` and `__params` of a `confirm` or `command` dialog, and every other `__` field that holds what OK acts on, are refused with "the `<kind>` dialog cannot set protected field `<field>`", so OK runs what the dialog was opened for. `action` alone is sent as `ui.dialog.confirm` or `ui.dialog.cancel`. Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "choice", value: "dontSave"}]}` followed by a second call with `{action: "confirm"}` closes without saving, and `{action: "cancel"}` cancels the close or quit. `choice` takes `save`, `dontSave` or `cancel`; while more modified documents wait to be asked about, adding `{field: "applyToAll", value: true}` to `set` gives the same answer for each of them. Give `set` and `action` in separate calls for this question. The second call answers whichever dialog is open when it arrives, so a dialog that another client or the user opens between the two calls is answered instead. |
| `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields, action?}` (a missing `value` is `null`). The app stores all of them or none, then answers that same dialog with `action` in the same request: `confirm` (OK) or `cancel`. Another connection cannot open a dialog between the two steps. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. `set` cannot change a `__` field other than the dialog's controls held under a `__` name (such as Save PDF's `__section` or the Preferences `__search`): the `__command` and `__params` of a `confirm` or `command` dialog, and every other `__` field that holds what OK acts on, are refused with "the `<kind>` dialog cannot set protected field `<field>`", so OK runs what the dialog was opened for. `action` alone is sent as `ui.dialog.confirm` or `ui.dialog.cancel`. Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`; under a read root, Preferences leaves out the folder preferences outside it, as `inspect_ui` does) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "choice", value: "dontSave"}]}` followed by a second call with `{action: "confirm"}` closes without saving, and `{action: "cancel"}` cancels the close or quit. `choice` takes `save`, `dontSave` or `cancel`; while more modified documents wait to be asked about, adding `{field: "applyToAll", value: true}` to `set` gives the same answer for each of them. Give `set` and `action` in separate calls for this question. The second call answers whichever dialog is open when it arrives, so a dialog that another client or the user opens between the two calls is answered instead. |
| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). The app refuses `attributes.openUrl`, `file.export.svg.browser`, `file.saveForWeb.browser` and `file.showPackage` for every control and MCP request, since each opens another app, so the headless error for them does not suggest `--connect`. |
| `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. |
| `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. |
| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. |
| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read), DWG drawings (`.dwg`, `.dws`, `.dwt`). Templates (`.vctemplate`, `.ait`, `.cdt`, `.dwt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. |
| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error; versions 1 to 3 get each live star as a plain path of its outline, without its point count and ratio), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: <reason>` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. |
| `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. |
| `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. |
@@ -1648,8 +1648,8 @@ their own size (`scale: "512w"`).
WebP is lossless by default (`lossless: true`). `{"format": "webp", "lossless": false, "quality": 60}` writes a lossy
WebP file: `quality` runs from 0 to 100 (default 90, VectorCraft's own value), and a higher value keeps more detail in
a larger file. A lossy file keeps the alpha exactly when some pixels are not opaque. A WebP `quality` above 100, or one
that is not a whole number, is refused; a lossless file ignores `quality`. Export for Screens takes both in a WebP row
or in `settings.webp`.
that is not a whole number, is refused; a lossless file ignores `quality`. A WebP file holds the sRGB profile in an
`ICCP` chunk unless `embedIcc` is false. Export for Screens takes these options in a WebP row or in `settings.webp`.
GIF and PNG-8 exports take Save for Web's `transparencyDither` (`none`, the default, `diffusion`, `pattern` or `noise`)
and `transparencyDitherAmount` (0 to 100, default 100) next to `dither` and `ditherAmount`, and they change the file as
@@ -2821,7 +2821,7 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File
object; the same objects left out are not counted for the File-only functions `open`, `read`, `readch`,
`readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not
have; a document's `saveAs`, `exportFile`, `imageCapture` or `exportVariables` counts too, and so do `print` called on
have; a document's `saveAs`, `exportFile`, `exportForScreens`, `imageCapture` or `exportVariables` counts too, and so do `print` called on
`app.activeDocument`, `app.documents[i]`, `documents.add()`, `documents.getByName()` or `app.open()`, or on a
variable that holds one of them, and `SaveOptions.SAVECHANGES` wherever the script reads it, since `close` given
it saves the document to its file), `filesOpened` (files opened in other apps), `network`,
@@ -3434,7 +3434,8 @@ through `$`:
chosen. The chosen artboard stays active when another is inserted before it, even if it was already the active
one. `insert`, `remove` and `setActiveArtboardIndex` throw a `RangeError` for an index outside the list. Reading
an index past the last artboard gives `undefined` from `artboards[i]` and throws `Not found` from
`artboards.index(i)`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws
`artboards.index(i)`. `layers.index(n)` and `artboards.index(n)` on a collection whose document or layer is stale
throw its stale error for any number, a negative or fractional one included, before `Not found`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws
`Stale artboard`. `Layer.blendingMode`, `artworkKnockout` and `sliced` and `GroupItems.createFromFile` throw an
error that says they are not available yet. `GroupItems.createFromFile` on a collection whose document, layer or
group was deleted throws `Stale page item` or `Stale document` first.
@@ -3520,7 +3521,7 @@ through `$`:
https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/),
with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to
776.19; 100 writes one pixel per point whatever the raster effects resolution) for PNG24 and JPEG, `matteColor` (PNG24 and JPEG; only white, an `RGBColor` of 255, 255, 255, is accepted, and another color is an error), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and
`coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and
`coordinatePrecision` (1 to 7), `cssProperties`, `embedRasterImages`, `compressed`, `preserveEditability` and
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `AutoCAD` (also written
`ExportType.AUTOCAD`) takes `new ExportOptionsAutoCAD()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/)
and writes a DXF file, as `document.export {format: dxf}` does, with `exportFileFormat`, `version`
@@ -3545,8 +3546,9 @@ through `$`:
`"ExportType.PNG24"`. The enumerations of the options that keep their defaults (`OutputFlattening`,
`CompressionQuality`, `ColorConversion`, `ColorDestination`, `ColorProfile`, `DownsampleMethod`,
`MonochromeCompression`, `PageMarksTypes`, `PDFChangesAllowedEnum`, `PDFPrintAllowedEnum`, `PDFTrimMarkWeight`,
`PDFXStandard`, `SVGCSSPropertyLocation`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and
`SVGFontType`) are defined too: the default member is accepted, and another member throws as not available yet. A
`PDFXStandard`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and `SVGFontType`) are defined too:
the default member is accepted, and another member throws as not available yet. `SVGCSSPropertyLocation`, which
`cssProperties` uses, is defined as well. A
path whose real file name is not valid UTF-8 throws `Script file path is not valid UTF-8` before anything is written
or opened.
VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the
@@ -3558,7 +3560,7 @@ through `$`:
read and written only where the script's folders allow. `userInteractionLevel` does not change what a command
does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.dxf`, `.svgz` with
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
`compressed`); an SVG to a name that ends with `.svgz` is compressed whatever `compressed` holds. It writes 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 a
DXF of a drawing with placed raster images writes each image it exports beside it as a PNG file, or a JPEG
file with `rasterFormat` `AutoCADRasterFormat.JPEG`; those files must travel with the DXF. When the script's
@@ -3599,6 +3601,50 @@ through `$`:
show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that
`saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name
(`saveAs: …`).
- `Document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, fileNamePrefix?)` runs
`document.exportForScreens` with one format row into `exportFolder`, a `Folder` (or a `File`, read as the folder at
its path) (https://www.indesignjs.de/indesignapi/illustrator/Document.html). `exportFormat` is an
`ExportForScreensType` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html): `SE_JPEG100`,
`SE_JPEG80`, `SE_JPEG50` and `SE_JPEG20` write JPEG at a quality of 100, 80, 50 and 20 and take
`new ExportForScreensOptionsJPEG()`; `SE_PNG24` takes `new ExportForScreensOptionsPNG24()`; `SE_PNG8` takes
`new ExportForScreensOptionsPNG8()`; `SE_SVG` takes `new ExportForScreensOptionsWebOptimizedSVG()`; and `SE_PDF`
takes `new ExportForScreensPDFOptions()` (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). The raster classes map
`antiAliasing`, `scaleType` and `scaleTypeValue` (`SCALEBYFACTOR` as a multiplier from 0.01 to 64, so 2 doubles the
size, `SCALEBYWIDTH` and `SCALEBYHEIGHT` in pixels, `SCALEBYRESOLUTION` in ppi from 0.72 to 4608).
Width and height requests must imply a raster scale from 0.01 to 64 for every exported region; an invalid scale
is rejected before that export command creates its output folder. Earlier artboard, asset or document exports in
the same script call can have written files. JPEG also maps `compressionMethod`, `embedICCProfile` and `progressiveScan` (3 to 5);
PNG24 maps `transparency`, `backgroundBlack` and `interlaced`; PNG8 maps `colorCount` (2 to 256), `interlaced`,
`matte` and `transparency`. With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. The SVG class maps `coordinatePrecision` (1 to 7), `cssProperties`, `fontType`,
`rasterImageLocation`, `svgId`, `svgMinify` and `svgResponsive`. SVG `RasterImageLocation.LINK` throws; `EMBED` and `PRESERVE` embed raster images. The PDF class maps `pdfPreset` (at most 255
bytes; a name in square brackets names a built-in preset as `PDFSaveOptions.pDFPreset` does). `itemToExport` is a
`new ExportForScreensItemToExport()` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html)
with `artboards` (`all`, the default, a range of artboard numbers such as `1-3, 5`, or `""` for none), `assets` (a
list of asset ids, as `assets.list` gives them) and `document` (false by default). `fileNamePrefix` goes before each
file's name. The enumerations `ExportForScreensType`, `ExportForScreensScaleType`, `AntiAliasingMethod`,
`JPEGCompressionMethodType`, `RasterImageLocation`, `SVGCSSPropertyLocation`, `SVGFontType` and `SVGIdType` hold
strings such as `"ExportForScreensType.SE_PNG24"`.
VectorCraft's own rules: the folder is checked as a `File` opened for writing in it is checked, before the command
runs: a folder outside the script's folders throws `Script file access denied`, and a file throws `Script folder is
a file`. A volume root (`/`, `E:\`) is taken when the script's folders and the automation write roots hold it. The command writes only where the script's folders allow. The files go into the folder without
sub-folders, each named `<fileNamePrefix><name><suffix>.<extension>` as `document.exportForScreens` names them (`@2x`
after a raster file at twice the size); a character a file name may not hold, `/` and `\` included, is written as
`-` in the prefix. The export keeps its settings in the document, as an export from the dialog does. The artboards,
the assets and, with `document` true, the bounds of the whole document's art (a PDF of every artboard) are each
their own export, in that order: when a later one throws, the files of the earlier ones stay written. An
`itemToExport` that names nothing throws `nothing to export`. 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. A listed option that is not mapped
(`matteColor`) is accepted at its default and throws at any other value, a property the pages do not list throws an
error that names it, an omitted options object takes the defaults a new one holds, and an options object of
another class throws. `null` in place of the options, `itemToExport` or `fileNamePrefix` throws a TypeError. A bad option value throws an error before anything is written. Each export checks the scale of
each of its items before it writes, and an item too large to draw throws after the files before it are written. A
size gives each region its own scale, so a size that only a later export's items make out of range throws after the
earlier exports' files are written. The warnings of each export go to the console after `exportForScreens: `.
- `Document.placedItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/) lists the document's linked
images and `Document.rasterItems` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/) its embedded ones,
topmost first as `pageItems` lists them, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()`
@@ -3646,7 +3692,10 @@ through `$`:
count the seam fills of an Abutting trace, `usedColorCount` counts the different fill and stroke paints, and
`imageResolution` is the image's pixels per inch as placed, an error for an image placed at different resolutions
across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the
source image and the view, and a value the tracing already has runs no command. Assigning `viewRaster` or
source image and the view, and a value the tracing already has runs no command. `loadFromPreset(name)` runs no
command only when the tracing's preset is `name` and its current parameters equal that preset's. Preset names match
without regard to letter case, and a built-in preset's name with or without brackets, such as `Default` and
`[Default]`, counts as the same preset. Assigning `viewRaster` or
`viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject`
and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. Tracing again throws
`Cannot retrace a tracing containing added artwork`, with nothing changed, when the tracing holds an object its trace
@@ -3844,7 +3893,12 @@ through `$`:
range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest
decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path as it
was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a
global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new
global or spot swatch reads as a `SpotColor` with its `tint`, and with its `spot` when the swatch is a spot color or
Registration). Assigning a `SpotColor` (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/) links the fill or
stroke to its `spot`, a `Spot` of the path's document, at its `tint` (0 to 100; VectorCraft's own defaults are 100
for `new SpotColor()` and 0 for a color object without a `tint`), with `paint.setFill` or `paint.setStroke`. A `SpotColor` read from a color linked to a global process
swatch has no `spot` and does not name the swatch, so assigning it, or a `SpotColor` whose `spot` was never set,
throws an error that says `SpotColor.spot` must be a Spot, and the path keeps its paint. Assigning a `GradientColor` or `PatternColor` throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new
art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the
stroke. A copied solid new-art color keeps its color model. A new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint
it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error.
@@ -3881,6 +3935,59 @@ through `$`:
a default throws an error, since new art then takes that object's appearance. `scaleFactor`
(https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts lists it as read-only) is always 1, since
VectorCraft draws every document at its own size; after an assignment it still reads 1.
- A `Document` also has `swatches`, `spots`, `swatchGroups`, `symbols`, `symbolItems`, `graphicStyles` and `brushes`
(https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/,
https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroups/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/,
https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItems/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyles/
and https://ai-scripting.docsforadobe.dev/jsobjref/Brushes/). Each has `length`, `parent`, `[i]`, `index(key)` and
`getByName(name)`; all but `brushes` have `removeAll()`. `swatches.add()` and `spots.add()` run `swatch.new`,
`swatchGroups.add()` runs `swatch.newGroup`, `symbols.add(sourceArt, registrationPoint?)` runs `symbol.new` with
`keepArt: true` (the default point is `SymbolRegistrationPoint.SYMBOLCENTERPOINT`), and `symbolItems.add(symbol)`
runs `symbol.place`. `swatches.getSelected()` throws that it is not available yet. A `Swatch` (https://ai-scripting.docsforadobe.dev/jsobjref/Swatch/)
has `name` and `color` (`swatch.edit`) and `remove()` (`swatch.delete`); the `color` of a spot swatch or of Registration reads as a
`SpotColor` with its `spot` and a `tint` of 100, and a tint of a spot as that `spot` at its `tint`. A `Spot` (https://ai-scripting.docsforadobe.dev/jsobjref/Spot/) has
`name`, `color`, `colorType`, `spotKind`, `getInternalColor()` and `remove()`. A `SwatchGroup`
(https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/) has `name` (`swatch.renameGroup`), `addSwatch(swatch)`
and `addSpot(spot)` (`swatch.move`), `getAllSwatches()`, `remove()` and `removeAll()`. A `Symbol`
(https://ai-scripting.docsforadobe.dev/jsobjref/Symbol/) has `name` (`symbol.options`), `duplicate()`
(`symbol.duplicate`) and `remove()` (`symbol.delete`); in a script engine that a `.js` or `.mjs` script starts,
the global `Symbol` stays the language's own (an engine that a `.jsx` script starts keeps the artwork `Symbol` for
the scripts that reuse it), and a script reaches artwork symbols through `symbols` and `SymbolItem.symbol`. A `SymbolItem`
(https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/) adds `symbol` to the page item members, which
`symbol.replace` changes. A `GraphicStyle` (https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/) has `name`
(`graphicStyle.rename`), `applyTo(item)` and `mergeTo(item)` (`graphicStyle.apply`, with `add: true` for `mergeTo`)
and `remove()` (`graphicStyle.delete`). A `Brush` (https://ai-scripting.docsforadobe.dev/jsobjref/Brush/) has a
read-only `name` and `applyTo(item)` (`brush.apply`). The enumerations `SymbolRegistrationPoint`, `ColorModel` and
`SpotColorKind` hold strings such as `"ColorModel.SPOT"`.
VectorCraft's own rules: `swatches` lists None, Registration, the other ungrouped swatches and then each color
group's, and `swatchGroups` lists the color groups. `swatches.add()` saves the current fill (a color, gradient or
pattern) or black when the fill is None, and `spots.add()` the current fill, converted to the document's color
space unless it is Lab, or black when it is not a solid color. None and Registration cannot change or be removed,
and `removeAll()` keeps them; the Default Graphic Style cannot be renamed or removed, and
`graphicStyles.removeAll()` keeps it. A color group takes solid
colors only; `SwatchGroup.remove()` deletes the group with its swatches, and its `removeAll()` deletes the swatches
and keeps the group. `spots` lists Registration and the spot colors. A spot's color, set through `Spot.color` or
`Swatch.color`, takes an `RGBColor`, a `CMYKColor` or a `LabColor` in a document of either color space, and the spot
keeps that color space. This is VectorCraft's own rule: the Spot page says a color in another space than the
document's gives an error, and `spots.add()` follows the page by converting the fill. A process swatch's
`Swatch.color` stores a new `RGBColor` in a CMYK document as CMYK, through the profiles that document is assigned. A
process swatch that holds an RGB color in a CMYK document (one made with `keepModel: true`) and is given that same
color back stays RGB, and no undo step is recorded. A spot's `colorType` reads
and takes only `ColorModel.SPOT` (`ColorModel.REGISTRATION` for Registration), a gray spot's `spotKind` is
`SpotColorKind.SPOTCMYK`, and `getInternalColor()` gives the
components on the color classes' scales. `symbols.add` leaves the source art as it is, and removing a symbol turns
its instances into plain art. `applyTo` and `mergeTo` take one page item of the same document that can be edited,
and `Brush.applyTo` a path that is not a guide, a clipping path or a path in a compound path or compound shape, at
any depth. `Brush.applyTo` runs no command only when the path already draws that brush with no brush options and
that brush is the current one; with another brush current, it runs `brush.apply`, which also makes the brush current.
A name is 1 to 1,024 bytes, not blank, with no control characters, and a name a
swatch, spot or color group already has throws for any of the three. Renaming a resource through these objects keeps
the object. After it is removed, renamed or deleted with `vc.run`, removed by `app.undo()` or `app.redo()`, or its
document is reverted, every member throws `Stale Swatch` (`Stale Spot`, `Stale SwatchGroup`, `Stale Symbol`,
`Stale GraphicStyle`, `Stale Brush`), also when a later resource takes its name. A run holds at most 100,000 of
these objects, and a call that would make one more throws with nothing changed. An object of
another document throws `Cross-document placement is not available`. `Document.gradients`, `Document.patterns` and
assigning a `SpotColor` to a swatch's or spot's `color` are not available yet.
- `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type
objects topmost first, as `pageItems` lists them, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and
`removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both
@@ -9314,13 +9421,15 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("`subpath` must be a
an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded.
`path.moveAnchor` to the point the anchor is at, and `path.setHandle` to the point the handle is at on an anchor that
keeps its kind, leave the document as it is and record no undo step.
On a path with rounded Live Corners, `path.moveAnchor` and `path.moveAnchors` (and the arrow keys) move the uncut corner
On a path with Live Corners that store a radius (rounded, or straightened by an earlier move), `path.moveAnchor` and
`path.moveAnchors` (and the arrow keys) move the uncut corner
each moved anchor belongs to by the drag delta and cut the corners again at their radii. The corners stay live; a live
rectangle or polygon becomes a path with live corners. The delta is measured from the drawn anchor, but the recut can
move that anchor again: a grabbed arc end can finish away from a snap target, and `path.moveAnchor` can leave the drawn
anchor away from `(x, y)`. When the recut changes the anchor layout, all selected anchors of that path are remapped
through their uncut outline anchors and its selected segments are cleared. An unchanged layout keeps the selection.
Anchor edits instead make the shape a plain path when it has no rounded corner, when a live rectangle is sheared or
A corner that a move straightens draws no arc but keeps its radius, so a later move that bends it again rounds it again.
Anchor edits instead make the shape a plain path when no corner has a radius, when a live rectangle is sheared or
unevenly scaled, when an arrow-key nudge's selected curved segments bend or hold their anchors, or when a transform of
direct-selected anchors is other than a move. A nudge that changes nothing, including one that the pixel-grid snap of a
pixel-aligned path takes back (objects selected whole beside the anchors included), records no undo step and leaves Live Corners as they are: a live rectangle stays a live
@@ -10368,9 +10477,10 @@ polygon's from its first vertex clockwise; a star's from its first tip; an index
Each corner keeps its own radius and kind (the shape's `live` in queries has `radii` and, when a corner isn't round,
`kinds`); a corner with no radius is one anchor, a cut one two, and Direct-Selected corners stay selected as that
changes. A path that isn't a live shape keeps its uncut outline (`live` `{"shape": "path", "base", "radii"}`) so its
corners stay editable, and is a plain path again once no corner is cut; a polygon stays a live polygon, its corners
keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to both sides: a radius
draws no larger than takes the cut halfway along the corner's shorter side (half the shorter side of a rectangle, the
corners stay editable. A corner with a stored radius keeps the path live while straight and rounds again when it
bends back. The path becomes plain again once no radius or nondefault corner kind is stored. A polygon stays a live
polygon, its corners keeping the radius they shared when `sides` changes. Every corner is a circular arc tangent to
both sides: a radius draws no larger than takes the cut halfway along the corner's shorter side (half the shorter side of a rectangle, the
same limit for its four corners), the corners stay circular through uneven scales (the radius scales by the mean scale,
or keeps its size with Scale Corners off), and a rectangle from a file that kept an uneven scale in its transform
(elliptical corners) gets circular ones in document units when its corners are next set. Dragging a corner widget
@@ -11827,6 +11937,8 @@ with `link: false` or from `dataBase64` it is one group. `at` centres it, `rect`
swaps the selected object (keeping its place and transform), `template` puts it on a new template layer.
When placed editable art names a font family it does not define as a composite font, and the document defines a
composite font of that name, the placed type gets a free name such as "Name 2" so it keeps the font it was laid out in.
A placed live dimension's label options take the same new name, so a redrawn label keeps that font; a document
composite font with the same name and the same definition is reused, and the dimension keeps its own spelling of it.
A DCS file (Desktop Color Separation, version 1.0 or 2.0: an EPS file whose header names one EPS program per printing
plate, <http://www.telegraphics.net/doc/DCS.txt>) is placed only from its `path` with link, as one linked image
([Import DCS files](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/import-dcs-files.html)).
@@ -12733,8 +12845,8 @@ blending, opacity masks, raster effects, clipping) comes back in `warnings`. In
no linked file, and `warnings` carries "an image couldn't be decoded and is missing from the picture" once for all such
images.
DWG drawings open and place (see DXF import) but can't be written: `document.formats` lists `dwg` as readable and
not writable, and exporting to it answers with the hint to export DXF. PICT files open and place (see PICT
DWG drawings open and place (see DXF import) but can't be written: `document.formats` lists `dwg` and `dwt` as
readable and not writable, and exporting to `dwg`, `dws` or `dwt` answers with the hint to export DXF. PICT files open and place (see PICT
import) but can't be written.
```json
@@ -12766,6 +12878,8 @@ vertices are missing, unknown entities) is listed in `warnings`. ASCII and binar
DWG drawings (by content or the `.dwg` extension) open, place and answer `document.dxfInfo` the same way, with the
same `dxf` options: craft-dwg converts the drawing to DXF (acadrust 0.6.6, MPL-2.0) and the DXF reader reads that.
Drawing standards files (`.dws`) are read as DWG drawings, and drawing templates (`.dwt`, format `dwt`) too, except
that a template opens as a new untitled document.
In the desktop app and `vectorcraft-cli` the conversion runs in a copy of the program started with `--dwg-worker`, so
a damaged file stops that copy, not the app; it gives up after 30 minutes. Files over 512 MiB, or whose DXF would
pass 1 GiB, are refused. What the conversion skips (objects of types it can't read) is listed in `warnings`. R1.x and
@@ -17797,6 +17911,30 @@ apart the locked and hidden groups the ids name and the groups inside the groups
stays a layer), but not groups on a locked artboard; an object of a hidden group becomes hidden, and an object of a
locked group becomes locked. Locked and hidden objects stay locked or hidden and are left out of the selection.
`addon.cleanup.releaseAll {scope?, ids?, groups?, clipGroups?, compoundPaths?}` (Object › Plug-ins › Artwork Cleanup ›
Release All Containers…) takes apart every container at every level of nesting as one undo step, so that only the
objects they held are left. `scope` is `"selection"` or `"document"`; by default it is the selection, or the document
while nothing is selected. `ids` names the objects, groups and layers to release in instead of `scope`; giving both is
an error. Duplicate IDs are an error. A null `ids` counts as left out: `scope` applies, and without `scope` the command uses the selection, or the document while nothing is selected; a null `scope`, `groups`, `clipGroups` or `compoundPaths` is an error.
`groups` ungroups groups, `clipGroups` ungroups clipping groups and makes layers stop clipping unless
their clipping path or clipped artwork overlaps a locked artboard (released clipping paths stay as plain paths), and
`compoundPaths` turns compound paths, and paths of several subpaths, into one path per subpath. Each is true by default,
and at least one must be true.
Layers stay. Objects keep the opacity of
the groups and compound paths they were in, and the paths of a compound path take its paint. Objects with live effects
on their appearance or fill and stroke rows, groups with fill or stroke rows of their own, objects with an opacity mask, compound shapes, Live Paint groups, graphs,
dimensions, flares, Objects on Path, generated art, Shaper Groups,
Image Trace objects, paths with Live Corners, blends, envelopes, repeats, intertwines and other live objects stay whole,
including directly selected or named descendants. The entire clipping mask subtree of a clipping group or layer that
stays is left as it is, including directly selected or named descendants. From the selection or the document, locked and hidden objects
and objects on a locked artboard stay whole. With `ids`, the locked and hidden containers it names, or that are in what
it names, are taken apart too and their objects become locked or hidden as the containers were, but containers on a
locked artboard stay whole. The selection keeps what it held, with each object taken apart replaced by the objects
left in its place, and locked and hidden objects left out. With nothing to release, the document, the selection and the
undo history stay as they are. It replies `{scope ("selection", "document" or "ids"), ids, groups, clipGroups,
compoundPaths}`, the last three counting what it released. The dialog previews on the canvas and turns OK off when no
kind is ticked, or when Selection is chosen with nothing selected.
`addon.cleanup.rejoin {gap?, ids?}` welds the selected open paths whose ends lie within `gap` (0 to 6 pt, 0.1 by
default) back into paths. Each end joins one other end: where several are in reach, the one the path turns least to go
on into. Pieces may run either way, and a chain whose ends meet closes. Each new path takes the place and paint of its
+1 -1
View File
@@ -210,7 +210,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the `pathItems` of layers, groups and compound paths make paths inside them; the rest of the script document model (text lines, gradient stops and the other classes) and batch work remain | 18–27 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the `pathItems` of layers, groups and compound paths make paths inside them; the rest of the script document model (text lines, gradient stops and the other classes) and batch work remain | 18–27 |
| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
+14 -2
View File
@@ -42,6 +42,7 @@ Native saves on Unix flush the destination directory after writing or replacing
## Feature submission evidence
- Command dialogs can keep the uid of the document they edit. Their preview, confirmation, and cancellation do not change another active document. Tests cover confirmation in the original and another document, unscoped dialogs, and invalid document ids.
- A control-channel confirm of a dialog that holds its OK (`ui.dialog.confirm`, or `ui.dialog.set` with `action: "confirm"`) replies once the app accepts or refuses the OK, with the app's answer, and a set with an `action` that the app accepts replies `{dialog, result}`, while a refused one replies with the app's error alone. Tests: `crates/ui-egui/src/control/tests.rs`, `crates/ui-egui/src/tests/automation.rs`. Scores and estimates unchanged.
Document Info › Objects reports total enclosed area (`pathArea` in square points) for eligible closed paths and compound paths according to their fill rule, subtracting holes and excluding guides and open paths, with duplicate nested compound geometry avoided. The Document Info panel inserts a formatted `Path Area` row in the document's active units (`Unit::format_area`) right after `Path Length` whenever the total area is positive. The area pass runs only for a request that covers the Objects category: `document.info` with another `category`, or with `pathArea: false`, skips it and gives `pathArea` as null, and the panel asks for the area only while it shows Objects or All Categories, so edits made with another category shown do not work it out again. Focused tests: `cmd::docinfo::tests::info_gives_the_paths_total_area`, `info_path_area_counts_selected_compound_members_once` and `info_works_out_the_path_area_only_for_the_objects_category` (vectorcraft-engine), `panels::doc_info::tests::the_path_area_is_worked_out_only_while_objects_is_shown` (vectorcraft-ui-egui) and `units::tests::format_area_formats_and_trims_cleanly` (vectorcraft-doc). Scores and estimates unchanged.
@@ -865,7 +866,7 @@ since 2026-10-01.
- **A Shift-click inside a selected group** (VectorCraft's own rule): with Direct Selection, a Shift-click on the fill of a path inside a selected group deselects that path, and the group's other objects stay selected (`select.remove`); a Shift-drag from there moves nothing. A Shift-click on one of the path's anchors deselects only that anchor, and the path's other anchors and the group's other objects stay selected. Tests: `direct::tests::a_shift_press_inside_a_selected_group_deselects_the_path`, `selection_commands::remove_and_anchor_toggle_open_a_selected_group`, `selection::tests::expand_to_selects_a_member_in_place_of_its_selected_group`.
- **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of every selected path is selected (the paths selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. When another selected path has only some corners picked, a Shift-click on a widget of a path selected whole deselects that corner and keeps the other picks. The other corners' widgets then show as not picked; a Shift-click on another corner's anchor or widget adds that corner, and a Shift-click on a picked widget deselects its corner. Corner widgets are chosen by clicking one and Shift-clicking the others ([a tutorial on rounded corners](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`.
- **Picking corner widgets (#1232):** with Direct Selection, every corner's widget shows while some corners are picked: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked picks its corner alone, a Shift-click adds or removes a corner across selected paths, and a double-click on a picked widget opens Corners for the picked corners of its path ([Live Corners help page, archived](https://web.archive.org/web/2019/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, a plain click on a picked widget keeps the picks (while every corner of every selected path is picked, it picks that corner alone, and a double-click then opens Corners for that corner), a drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, and over a widget that is not picked, a selected anchor's handle end or a nearer anchor takes the press. Tests: `corners::tests::a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners`, `corners::tests::widgets_are_picked_across_paths`, `corners::tests::a_handle_end_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_nearer_anchor_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_shift_click_toggles_a_rounded_corner_whole`, `corners::tests::a_path_with_hidden_widgets_keeps_its_picks`, `tests::corner_widgets_pick_corners_across_paths_through_the_session`.
- **Anchor edits keep Live Corners (#10545):** moving an anchor of a path with rounded corners (Direct Selection drag, arrow keys, `path.moveAnchor`) moves its uncut corner by the drag delta and recuts it at its radius. A grabbed arc end can finish away from a snap target. A live rectangle or polygon becomes a path with live corners. When the anchor layout changes, the path's whole anchor selection is remapped and its segment selection is cleared. An anchor edit makes the shape a plain path when there is no rounded corner, a live rectangle is sheared or unevenly scaled, an arrow-key nudge bends selected curved segments or holds their anchors, or direct-selected anchors receive a transform other than a move. A nudge that changes nothing, including one that the pixel-grid snap of pixel-aligned paths takes back (with objects selected whole too), records no undo step and leaves Live Corners as they are: a live rectangle stays a live rectangle. These are VectorCraft's own rules. Tests: `tests::livecorners::moving_an_anchor_keeps_the_corners_live`, `tests::livecorners::dragging_selected_anchors_keeps_the_corners_live`, `tests::livecorners::moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path`, `tests::livecorners::a_recut_remaps_the_whole_anchor_selection`, `tests::livecorners::a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same`, `tests::livecorners::an_unchanged_corner_layout_keeps_the_selection`.
- **Anchor edits keep Live Corners (#10545):** moving an anchor of a path with rounded corners (Direct Selection drag, arrow keys, `path.moveAnchor`) moves its uncut corner by the drag delta and recuts it at its radius. A grabbed arc end can finish away from a snap target. A live rectangle or polygon becomes a path with live corners. When the anchor layout changes, the path's whole anchor selection is remapped and its segment selection is cleared. A corner that a move straightens keeps its radius and rounds again when a later move bends it. An anchor edit makes the shape a plain path when no anchor stores a radius above 0 (a straightened corner's stored radius keeps the path live), a live rectangle is sheared or unevenly scaled, an arrow-key nudge bends selected curved segments or holds their anchors, or direct-selected anchors receive a transform other than a move. A nudge that changes nothing, including one that the pixel-grid snap of pixel-aligned paths takes back (with objects selected whole too), records no undo step and leaves Live Corners as they are: a live rectangle stays a live rectangle. These are VectorCraft's own rules. Tests: `tests::livecorners::moving_an_anchor_keeps_the_corners_live`, `tests::livecorners::dragging_selected_anchors_keeps_the_corners_live`, `tests::livecorners::moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path`, `tests::livecorners::a_recut_remaps_the_whole_anchor_selection`, `tests::livecorners::a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same`, `tests::livecorners::an_unchanged_corner_layout_keeps_the_selection`, `corners::tests::a_straightened_corner_rounds_again_when_it_bends_back`.
- **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF.
- **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`).
- **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html).
@@ -1118,19 +1119,21 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: `Document.exportForScreens` writes the artboards, assets or whole document of an `ExportForScreensItemToExport` into a folder as JPEG, PNG-24, PNG-8, SVG or PDF with a file name prefix, with the option classes and enumerations the reference pages https://www.indesignjs.de/indesignapi/illustrator/Document.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html and https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html describe, and writes only where the script's `File` objects may (`docs/mcp.md`). With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. Raster width and height requests outside an effective scale of 0.01 to 64 pixels per point are rejected before the underlying export command writes output; files written by earlier exports in the same script call remain. SVG embeds raster images and rejects `RasterImageLocation.LINK`. `crates/engine/src/tests/script_screens.rs`.
- Scripts: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.rs`.
- Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`.
- Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`.
- Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`.
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. `remove()` also refuses a shown source image. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error, and so does a `groupItems.removeAll()` or `compoundPathItems.removeAll()` that would leave an image at the bottom of such a group. `crates/engine/src/tests/script_dom_tracing.rs`.
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Loading the built-in preset the tracing already has, by its name with or without brackets (`[Default]`), with unchanged options does not trace again. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. `remove()` also refuses a shown source image. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error, and so does a `groupItems.removeAll()` or `compoundPathItems.removeAll()` that would leave an image at the bottom of such a group. `crates/engine/src/tests/script_dom_tracing.rs`.
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font, fill and stroke colors, stroke weight) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops are not there yet. `crates/engine/src/tests/script_text.rs`.
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
- Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). A path's fill or stroke takes a `SpotColor` of a spot at a tint (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`, `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
@@ -2568,6 +2571,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge.
- DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`).
- DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build and R1.x and R2.x drawings return an error that says to save the drawing as DXF. DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged).
- `.dws` drawing standards files and `.dwt` drawing templates, which are DWG files, open and place as DWG drawings, are listed in the open and place dialogs, and go through the DXF Import Options; a `.dwt` opens as a new untitled document (`a_dwt_template_opens_untitled_and_a_dws_opens_as_its_drawing`, `a_dwt_or_dws_drawing_places_as_a_dwg_does`, `dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf`; scores and estimates unchanged).
- Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md).
- `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`).
- `.cmx` exchange files with 32-bit coordinates open and place: `craft-cdr` reads their color, pen, line type, dash and outline tables and each page's instructions, and the importer maps pages, layers (a layer that holds nothing is left out), groups and curves, with uniform fills and outlines, as it maps a `.cdr` drawing's. Text, images, rectangles, ellipses, clipping paths, other fills, arrowheads and lenses are named in the warnings, and big-endian files and files with 16-bit coordinates are refused with a message (`craft-cdr` `storytold/craft-libs@9b28b56bc7` `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`, `crates/engine/tests/import_fuzz.rs`).
@@ -3029,6 +3033,14 @@ alike in being hidden and in being locked, and the objects of a group Deep Ungro
state. Tests: `simplify_named_locked_and_hidden_paths`, `deep_ungroup_named_locked_and_hidden_groups` and
`rejoin_named_locked_and_hidden_pieces` in `cmd::addons::cleanup::tests`.
Release All Containers… (`addon.cleanup.releaseAll`) takes apart the groups, clipping groups and compound paths of the
kinds asked for in the selection, the objects named or the whole document, at every level of nesting, as one undo step;
layers stay, and stop clipping when clipping groups are released unless their clipping path or clipped artwork overlaps
a locked artboard; paths of several subpaths split into one path per subpath. Objects with an opacity mask, groups with
fill or stroke rows of their own, live objects, paths with Live Corners and artwork on a locked artboard stay whole. Its dialog previews on the canvas and picks
where to release and which kinds (VectorCraft's own tool). Tests: `cmd::addons::cleanup::release::tests` in
`vectorcraft-engine` and `addons::cleanup::release::tests` in `vectorcraft-ui-egui`.
## Path Precision Tools add-on (2026-10-30)
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools,
+1 -1
View File
@@ -617,7 +617,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | unknown |
| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool (also in the Pen tool's group in both shipped toolbars, after the Quick Pen; the All Tools drawer lists it under Draw; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point); an Alt-drag away from paths selects the points inside a marquee | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | unknown |
| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its three tools (Anchor Eraser Brush, Extend Path, Measure & Inspect), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and runs Add Points at / Split at Crossings; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | unknown |
| Artwork Cleanup add-on (VectorCraft addition): Object › Plug-ins › Artwork Cleanup opens its panel, which checks the selection or the document for 16 kinds of issue, lists them with counts, and shows or fixes the picked rows or all of them, each fix one undo step; Simplify Anchors (Keep Shape), Rejoin Path Pieces and Deep Ungroup open their options first | done | `addon.cleanup.*`, `crates/ui-egui/src/addons/cleanup.rs` and its tests; not a feature of the reference app, so it is not scored | unknown |
| Artwork Cleanup add-on (VectorCraft addition): Object › Plug-ins › Artwork Cleanup opens its panel, which checks the selection or the document for 16 kinds of issue, lists them with counts, and shows or fixes the picked rows or all of them, each fix one undo step; Simplify Anchors (Keep Shape), Rejoin Path Pieces and Deep Ungroup open their options first; Release All Containers… takes apart the groups, clipping masks and compound paths of the kinds asked for in the selection or the document as one undo step, leaving objects with an opacity mask, live objects and paths with Live Corners whole | done | `addon.cleanup.*`, `crates/ui-egui/src/addons/cleanup.rs` and its tests; not a feature of the reference app, so it is not scored | unknown |
| Artwork Cleanup add-on text tools (VectorCraft addition): the panel's Text row, which the panel can hide, and Object › Plug-ins › Artwork Cleanup set the alignment of point type keeping its place, break type into lines (Shift-click: paragraphs), words or glyphs, split type at the cursor, reset a text transform (Alt-click: and its horizontal scale), combine point type, remove line or paragraph breaks and replace missing fonts, each one undo step | done | `addon.cleanup.*` text commands, `crates/ui-egui/src/addons/cleanup.rs` and its tests; a VectorCraft addition, so it is not scored | unknown |
| Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | unknown |
| Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | unknown |