mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 20:43:18 -05:00
Merge main into feat/scripts-print-printer
This commit is contained in:
commit
19c1a69b32
25 files changed
+1230
-39
No files matched your search
@@ -855,7 +855,7 @@ pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, s
|
||||
/// write a resolution and a number of bytes.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
|
||||
pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
|
||||
@@ -602,6 +602,53 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
|
||||
}
|
||||
|
||||
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a clipped PSD
|
||||
/// file with many more pixels keeps its corners when the image is tiny: the new image's transform
|
||||
/// is the old one scaled down to the new pixel size, which is invertible however small it is.
|
||||
#[test]
|
||||
fn replacing_a_tiny_distorted_image_by_a_large_clipped_psd_keeps_its_corners() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-replace-tiny-distorted");
|
||||
let plane = vec![255u8; 2000 * 2000];
|
||||
let zero = vec![0u8; 2000 * 2000];
|
||||
let big = psd(1, 3, (2000, 2000), 8, 3, &[], &triangle_resources(), &[], &raw(&[&plane, &zero, &zero]));
|
||||
let cut = write_file(&dir, "big.psd", &big);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
|
||||
let r = s
|
||||
.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": [100, 100, 0.001, 0.001]}))
|
||||
.unwrap();
|
||||
let old = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [old.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[100, 100], [100.001, 100.0001], [100.0009, 100.001], [99.9998, 100.0008]]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(old).unwrap().is_distorted_image(), "the old image is distorted");
|
||||
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "replace": true})).unwrap();
|
||||
let image = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
|
||||
assert!(image.is_distorted_image());
|
||||
assert_eq!(image.image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// Place with Replace of a clipped PSD file's image changed by Perspective Distort or Free Distort
|
||||
/// by a DCS file keeps the image's corners: the DCS file's image fills them.
|
||||
#[test]
|
||||
fn replacing_a_distorted_clipped_psd_by_a_dcs_file_keeps_its_corners() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-replace-distorted-dcs");
|
||||
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
|
||||
let dcs = write_file(&dir, "pic.eps", &crate::tests::dcs::two_plates());
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": dcs, "replace": true})).unwrap();
|
||||
let new = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
|
||||
assert!(new.is_distorted_image(), "the DCS file's image takes the corners");
|
||||
assert_eq!(new.image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective
|
||||
/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners,
|
||||
/// a clip group of the old file's clipping path loses it when the new file names none, and a later
|
||||
|
||||
@@ -456,6 +456,30 @@ fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A file placed with Replace over an image changed by Perspective Distort or Free Distort takes
|
||||
/// its corners, and its slices cover what the corners put their part of the pixels on.
|
||||
#[test]
|
||||
fn slices_placed_over_a_distorted_image_follow_its_corners() {
|
||||
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 10, 10])], &[]));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
|
||||
s.execute("file.place", &json!({"name": "a.png", "dataBase64": b64(&png), "at": [100, 100]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[100, 100], [160, 104], [150, 140], [96, 136]]})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "replace": true})).unwrap();
|
||||
assert_eq!(r["slices"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let image = d.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
|
||||
assert!(image.is_distorted_image());
|
||||
let vectorcraft_doc::NodeKind::Image(im) = &image.kind else { panic!("an image") };
|
||||
// The top left quarter of the 20 × 20 px canvas.
|
||||
let (w, h) = (f64::from(im.width) / 2.0, f64::from(im.height) / 2.0);
|
||||
let want = image.image_map().unwrap().map_rect_bbox(Rect::new(0.0, 0.0, w, h)).unwrap();
|
||||
let got = slices(&s)[0].0;
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
|
||||
assert!(near(got.x0, want.x0) && near(got.y0, want.y0) && near(got.x1, want.x1) && near(got.y1, want.y1), "{got:?} vs {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_files_are_placed_without_their_slices() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
|
||||
|
||||
@@ -1314,7 +1314,7 @@ fn refill_distorted(
|
||||
/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points
|
||||
/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front
|
||||
/// of it, and one past it to the far side. `None` when a point maps to no finite page point.
|
||||
fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
pub(super) fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
let [[a, b, c], [d, e, f], [g, h, i]] = map.0;
|
||||
let apply = |p: vectorcraft_geom::Point| {
|
||||
let w = g * p.x + h * p.y + i;
|
||||
|
||||
@@ -57,7 +57,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, Homography, Point, Rect, shapes};
|
||||
use vectorcraft_pdf::CropTo;
|
||||
|
||||
use super::fileio::{self, Format, RasterImage};
|
||||
@@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 12
Line truncated
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
|
||||
|
||||
/// The transform that puts new art with the natural box `natural` where `old` is: an image's scale
|
||||
/// and rotation relative to its 100% size (its resolution's) and its centre are kept (with
|
||||
/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by
|
||||
/// `image_xf`), also for an image alone in a clip group when the new art is a raster or DCS image, clipped by
|
||||
/// its file's clipping path or not (`new_image`); other objects keep their centre.
|
||||
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine {
|
||||
let image = replace_measured(d, old, new_image);
|
||||
@@ -663,7 +663,7 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
|
||||
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
|
||||
let full = Affine::scale_non_uniform(sx, sy);
|
||||
let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0);
|
||||
if im.xf.determinant().abs() > 1e-12 {
|
||||
if Homography::affine_is_invertible(im.xf) {
|
||||
return im.xf * full.inverse() * Affine::translate(centre - natural.center());
|
||||
}
|
||||
}
|
||||
@@ -672,8 +672,8 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
|
||||
}
|
||||
|
||||
/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as
|
||||
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an
|
||||
/// image (`new_image`), except a DCS file's plates; else `old` itself.
|
||||
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is a
|
||||
/// raster or DCS image (`new_image`), except a DCS file's plates; else `old` itself.
|
||||
fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node {
|
||||
match &old.kind {
|
||||
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
|
||||
@@ -687,6 +687,60 @@ fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Nod
|
||||
}
|
||||
}
|
||||
|
||||
/// What Replace does when the image it measures, `old`, is distorted and the art placed is a
|
||||
/// raster image or a DCS file's image (`art`): the transform that puts the new pixels on `old`'s
|
||||
/// transform scaled to their size, as Update Links scales it, the corners the new image takes, and
|
||||
/// the map from the art's natural box to the page through those corners, which a PSD file's slices
|
||||
/// follow. `None` for other art, for an image with no pixels, and for corners the new pixels can't
|
||||
/// fill ([`Node::set_image_corners`]).
|
||||
fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homography)> {
|
||||
let NodeKind::Image(im) = &old.kind else { return None };
|
||||
let q = old.image_quad()?;
|
||||
let (pixels, width, height) = match art {
|
||||
Art::Image(img, _) => {
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
(Affine::scale_non_uniform(sx, sy), img.width, img.height)
|
||||
}
|
||||
Art::Dcs(a) => (a.xf, a.img.width, a.img.height),
|
||||
_ => return None,
|
||||
};
|
||||
if width == 0 || height == 0 || !Homography::affine_is_invertible(pixels) {
|
||||
return None;
|
||||
}
|
||||
let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height));
|
||||
let new = ImageObject { key: String::new(), width, height, xf, link: None, placement: Default::default(), pixels: None };
|
||||
let mut probe = Node::new(old.id, NodeKind::Image(Box::new(new)));
|
||||
probe.set_image_corners(q).ok()?;
|
||||
let page = probe.image_map()?.checked_then_after(&Homography::from_affine(pixels.inverse()))?;
|
||||
Some((xf * pixels.inverse(), q, page))
|
||||
}
|
||||
|
||||
/// Placed raster `node` (an image, or an image in a clip group of its file's clipping path, as
|
||||
/// [`build`] makes them) with the image's corners at `q`: the pixels fill them, and the clipping
|
||||
/// path is drawn through them as the pixels are. `None` when the corners can't hold the image.
|
||||
fn with_corners(mut node: Node, q: [Point; 4]) -> Option<Node> {
|
||||
match &mut node.kind {
|
||||
NodeKind::Image(_) => node.set_image_corners(q).ok()?,
|
||||
NodeKind::Group { children, clip: true } => {
|
||||
let [path, image] = &mut children[..] else { return None };
|
||||
let image = Arc::make_mut(image);
|
||||
let NodeKind::Image(im) = &image.kind else { return None };
|
||||
if !Homography::affine_is_invertible(im.xf) {
|
||||
return None;
|
||||
}
|
||||
// The clipping path in the image's pixels, which its transform placed on the page.
|
||||
let to_pixels = im.xf.inverse();
|
||||
image.set_image_corners(q).ok()?;
|
||||
let map = image.image_map()?;
|
||||
let NodeKind::Path { path: p, .. } = &mut Arc::make_mut(path).kind else { return None };
|
||||
p.transform(to_pixels);
|
||||
*p = super::links::warped(p, &map)?;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(node)
|
||||
}
|
||||
|
||||
/// `rect` fitted with `natural`'s aspect, centred.
|
||||
fn fit(natural: Rect, r: Rect) -> Affine {
|
||||
let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b);
|
||||
@@ -846,19 +900,24 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
loaded.natural = Rect::from_origin_size(Point::ORIGIN, size);
|
||||
}
|
||||
let natural = loaded.natural;
|
||||
// Replace keeps the transform of the image it measures (`replace_measured`), which a
|
||||
// distortion's corners do not follow. Type, and any other object it measures, is placed by the
|
||||
// bounds of what it replaces, so a distorted image there is not refused.
|
||||
// Replace keeps the transform of the image it measures (`replace_measured`). When that image
|
||||
// is distorted, a raster placed in its place takes its corners ([`distorted_replace`]); other
|
||||
// art is refused. Type, and any other object it measures, is placed by the bounds of what it
|
||||
// replaces, so a distorted image there is not refused.
|
||||
let mut distorted = None;
|
||||
let new_image = matches!(loaded.art, Art::Image(..) | Art::Dcs(..));
|
||||
if let Some(o) = old_node
|
||||
&& !is_text
|
||||
{
|
||||
let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
|
||||
let image = replace_measured(&st.doc, o, new_image);
|
||||
if image.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(PLACE, image.id));
|
||||
let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?;
|
||||
distorted = Some((image.id, fit));
|
||||
}
|
||||
}
|
||||
let m = match (old_node, rect) {
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
|
||||
(Some(_), _) if let Some((_, (m, ..))) = distorted => m,
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, new_image),
|
||||
(None, Some(r)) => fit(natural, r),
|
||||
// Its artboard's bottom-left corner on the target's.
|
||||
(None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)),
|
||||
@@ -908,13 +967,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
if let Art::Dcs(a) = &loaded.art {
|
||||
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
|
||||
}
|
||||
// A PSD file's slices move and scale with its art; one that would leave the canvas is left out.
|
||||
// A PSD file's slices move and scale with its art, through a distorted image's corners when
|
||||
// it takes them; one that would leave the canvas is left out.
|
||||
let read_count = read_slices.len();
|
||||
let slices: Slices = read_slices
|
||||
.into_iter()
|
||||
.filter_map(|(r, o)| {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
|
||||
let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c));
|
||||
let placed = match distorted {
|
||||
Some((_, (_, _, page))) => page.map_rect_bbox(r)?,
|
||||
None => {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
|
||||
corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c))
|
||||
}
|
||||
};
|
||||
super::slices::slice_rect_ok(placed).then_some((placed, o))
|
||||
})
|
||||
.collect();
|
||||
@@ -924,7 +989,10 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
|
||||
}
|
||||
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
|
||||
let node = transformed(build(d, loaded, link), m);
|
||||
let mut node = transformed(build(d, loaded, link), m);
|
||||
if let Some((old_image, (_, q, _))) = distorted {
|
||||
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
|
||||
}
|
||||
let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default();
|
||||
let (into, index) = match old {
|
||||
Some(old) => {
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul
Line truncated
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -195,6 +195,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
if s.script_frames && !answers.is_empty() {
|
||||
return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"));
|
||||
}
|
||||
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
|
||||
let fuel = max_fuel(p)?;
|
||||
let installed = switch_or(p, "installed", false, "script.run")?;
|
||||
let mut checked_real = None;
|
||||
@@ -241,6 +242,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
fuel,
|
||||
locale,
|
||||
answers,
|
||||
actions,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -442,6 +444,7 @@ impl Session {
|
||||
fuel,
|
||||
locale,
|
||||
answers: vec![],
|
||||
actions: vec![],
|
||||
};
|
||||
let runs = self.script_runs;
|
||||
self.script_start(request).map_err(|e| {
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's
|
||||
//! run, as the VBScript reference's `DoScript` method of the Application object describes it
|
||||
//! (<https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf>).
|
||||
//!
|
||||
//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps
|
||||
//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app
|
||||
//! they are the Actions panel's.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the reference does not state:
|
||||
//! - The action and its set are matched by their exact names; a name that matches no action, or
|
||||
//! more than one, throws before any step runs.
|
||||
//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins
|
||||
//! the run's transaction and its one undo step for each changed document, it is counted as a host
|
||||
//! call, it reads and writes files only where the script may, and a step that fails is put back
|
||||
//! and throws an error that names the step and the action, while the steps before it stay done.
|
||||
//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine
|
||||
//! does not have (a View menu step, or one that plays an action), and a stop throw before any step
|
||||
//! runs, as does such a command among those an `action.batch` step plays. An action cannot play
|
||||
//! another action, so it cannot play itself.
|
||||
//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it
|
||||
//! changes nothing.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostError, HostMember};
|
||||
|
||||
use super::{Host, Link, command, current, refused_to_scripts};
|
||||
|
||||
/// The most actions a run's request may carry.
|
||||
pub const MAX_ACTIONS: usize = 4096;
|
||||
/// The most steps one action may have, after a `command.batch` step gives its own steps.
|
||||
pub const MAX_ACTION_STEPS: usize = 10_000;
|
||||
/// The most steps the actions of one request may have in all.
|
||||
pub const MAX_ALL_STEPS: usize = 100_000;
|
||||
/// The most bytes of the request's actions, as JSON.
|
||||
pub const MAX_ACTIONS_BYTES: usize = 16 << 20;
|
||||
/// The longest name of an action or a set, in bytes.
|
||||
pub const MAX_NAME_BYTES: usize = 1024;
|
||||
/// The longest command id of a step, in bytes.
|
||||
const MAX_ID_BYTES: usize = 256;
|
||||
/// The command id of a stop, which waits for the person in the Actions panel.
|
||||
pub const STOP_STEP: &str = "action.stop";
|
||||
|
||||
/// An action a run can play: its set's name, its name and the steps playback runs.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Playable {
|
||||
set: String,
|
||||
name: String,
|
||||
steps: Vec<Step>,
|
||||
}
|
||||
|
||||
/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a
|
||||
/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and
|
||||
/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Step {
|
||||
place: String,
|
||||
id: String,
|
||||
params: Value,
|
||||
bytes: u64,
|
||||
artboard: Option<u64>,
|
||||
}
|
||||
|
||||
/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the
|
||||
/// step's place in the action (1 for the first; default its place in the list), within the limits
|
||||
/// above. A `command.batch` step gives its own steps, each at the batch's place and its own.
|
||||
pub fn parse(v: Option<&Value>) -> Result<Vec<Playable>, String> {
|
||||
let Some(v) = v else { return Ok(Vec::new()) };
|
||||
let Value::Array(list) = v else { return Err("`actions` must be a list".into()) };
|
||||
if list.len() > MAX_ACTIONS {
|
||||
return Err(format!("`actions` holds more than {MAX_ACTIONS} actions"));
|
||||
}
|
||||
if let Some(place) = super::too_deep(v) {
|
||||
return Err(format!("`actions{place}` is nested more than 64 levels deep"));
|
||||
}
|
||||
if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) {
|
||||
return Err("`actions` is larger than 16 MiB".into());
|
||||
}
|
||||
let mut all = 0usize;
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for (i, a) in list.iter().enumerate() {
|
||||
let at = format!("`actions[{i}]`");
|
||||
let Value::Object(a) = a else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(a, &["set", "name", "steps"], &at)?;
|
||||
let set = name_of(a, "set", &at)?;
|
||||
let name = name_of(a, "name", &at)?;
|
||||
let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) };
|
||||
let mut steps = Vec::new();
|
||||
for (j, s) in given.iter().enumerate() {
|
||||
let at = format!("{at}.steps[{j}]");
|
||||
let Value::Object(s) = s else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(s, &["command", "params", "step"], &at)?;
|
||||
let place = match s.get("step") {
|
||||
None => (j + 1).to_string(),
|
||||
Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) {
|
||||
Some(n) => n.to_string(),
|
||||
None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")),
|
||||
},
|
||||
};
|
||||
let (id, params) = command_of(s, &at)?;
|
||||
match params.get("commands") {
|
||||
Some(Value::Array(inner)) if id == "command.batch" => {
|
||||
// The batch's `artboard`, for its steps that act on the active artboard, as
|
||||
// `command.batch` reads it.
|
||||
let artboard = params.get("artboard").and_then(Value::as_u64);
|
||||
for (k, c) in inner.iter().enumerate() {
|
||||
let at = format!("{at}.params.commands[{k}]");
|
||||
let Value::Object(c) = c else { return Err(format!("{at} must be an object")) };
|
||||
let (id, params) = command_of(c, &at)?;
|
||||
if id == "command.batch" {
|
||||
return Err(format!("{at} is a command.batch inside a command.batch"));
|
||||
}
|
||||
steps.push(step(format!("{place}.{}", k + 1), id, params, artboard));
|
||||
}
|
||||
}
|
||||
_ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")),
|
||||
_ => steps.push(step(place, id, params, None)),
|
||||
}
|
||||
if steps.len() > MAX_ACTION_STEPS {
|
||||
return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps"));
|
||||
}
|
||||
}
|
||||
all += steps.len();
|
||||
if all > MAX_ALL_STEPS {
|
||||
return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all"));
|
||||
}
|
||||
out.push(Playable { set, name, steps });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Playable {
|
||||
/// The steps the action runs.
|
||||
pub fn len(&self) -> usize {
|
||||
self.steps.len()
|
||||
}
|
||||
|
||||
/// Whether the action runs no step.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.steps.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn only_keys(o: &Map<String, Value>, keys: &[&str], at: &str) -> Result<(), String> {
|
||||
match o.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn name_of(o: &Map<String, Value>, key: &str, at: &str) -> Result<String, String> {
|
||||
match o.get(key) {
|
||||
Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()),
|
||||
Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")),
|
||||
_ => Err(format!("{at}.{key} must be a string")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A step's `command` and `params` (default `{}`).
|
||||
fn command_of(o: &Map<String, Value>, at: &str) -> Result<(String, Value), String> {
|
||||
let id = match o.get("command") {
|
||||
Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(),
|
||||
_ => return Err(format!("{at}.command must be a command id")),
|
||||
};
|
||||
let params = match o.get("params") {
|
||||
None => json!({}),
|
||||
Some(p @ Value::Object(_)) => p.clone(),
|
||||
Some(_) => return Err(format!("{at}.params must be an object")),
|
||||
};
|
||||
Ok((id, params))
|
||||
}
|
||||
|
||||
fn step(place: String, id: String, params: Value, artboard: Option<u64>) -> Step {
|
||||
let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64);
|
||||
Step { place, id, params, bytes, artboard }
|
||||
}
|
||||
|
||||
/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters
|
||||
/// as U+FFFD.
|
||||
fn shown(text: &str) -> String {
|
||||
const MAX: usize = 80;
|
||||
let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect();
|
||||
if text.chars().nth(MAX).is_some() {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The members of `app` this module adds.
|
||||
pub(super) fn app_members(link: &Link) -> Vec<super::dom::Described> {
|
||||
let l = link.clone();
|
||||
let play = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
do_script(&h, &a)
|
||||
});
|
||||
let info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]);
|
||||
let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)];
|
||||
members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name)));
|
||||
members
|
||||
}
|
||||
|
||||
fn arg(a: &[Data], i: usize) -> &Data {
|
||||
a.get(i).unwrap_or(&Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.doScript(action, set, dialogs?)`, its arguments after `this`.
|
||||
fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
if a.len() > 4 {
|
||||
return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into()));
|
||||
}
|
||||
let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else {
|
||||
return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into()));
|
||||
};
|
||||
if action.is_empty() || set.is_empty() {
|
||||
return Err(HostError::Error("doScript needs the action's name and its set's name".into()));
|
||||
}
|
||||
if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES {
|
||||
return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes")));
|
||||
}
|
||||
if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) {
|
||||
return Err(HostError::Type("doScript's dialogs must be true or false".into()));
|
||||
}
|
||||
let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
|
||||
let p = match found.as_slice() {
|
||||
[p] => *p,
|
||||
[] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
|
||||
[] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))),
|
||||
_ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))),
|
||||
};
|
||||
if p.steps.is_empty() {
|
||||
return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name))));
|
||||
}
|
||||
// Every step is checked before the first runs, so a step that cannot run leaves the documents as
|
||||
// they were.
|
||||
for s in &p.steps {
|
||||
if let Some((place, id)) = refused_step(s) {
|
||||
let name = shown(&p.name);
|
||||
return Err(HostError::Error(if id == STOP_STEP {
|
||||
format!("step {place} of “{name}” is a stop, which a script cannot wait at")
|
||||
} else {
|
||||
format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id))
|
||||
}));
|
||||
}
|
||||
}
|
||||
for s in &p.steps {
|
||||
// A run asked to stop runs no further step; the realm ends it at its next instruction and
|
||||
// puts the documents back.
|
||||
if h.session.borrow().script_stop.is_set() {
|
||||
break;
|
||||
}
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
h.session.borrow_mut().set_replaying(outer);
|
||||
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 {
|
||||
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)),
|
||||
other => other,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The place and command of the first command step `s` would run that a script may not run: the
|
||||
/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the
|
||||
/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the
|
||||
/// engine does not have are refused.
|
||||
fn refused_step(s: &Step) -> Option<(String, String)> {
|
||||
let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none();
|
||||
if refused(&s.id) {
|
||||
return Some((s.place.clone(), s.id.clone()));
|
||||
}
|
||||
if s.id != "action.batch" {
|
||||
return None;
|
||||
}
|
||||
let commands = s.params.get("commands").and_then(Value::as_array)?;
|
||||
commands.iter().enumerate().find_map(|(k, c)| {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned()))
|
||||
})
|
||||
}
|
||||
|
||||
/// `params` of step `id`, with the active artboard of the active document added as a
|
||||
/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for
|
||||
/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to
|
||||
/// Selected Art. The active artboard is the index `start` gives for the document (its index as the
|
||||
/// run started, which the view keeps), past the last artboard the last one, as the view shows it
|
||||
/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While
|
||||
/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its
|
||||
/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh
|
||||
/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the
|
||||
/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork
|
||||
/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the
|
||||
/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch`
|
||||
/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past
|
||||
/// the last artboard the last one, and none in a document without artboards, as `command.batch`
|
||||
/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit
|
||||
/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept.
|
||||
pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value {
|
||||
let mut params = params.clone();
|
||||
let Some(st) = s.active() else { return params };
|
||||
let n = st.doc.artboards.len();
|
||||
let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) {
|
||||
(Some(_), _) if n == 0 => return params,
|
||||
(Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)),
|
||||
(None, Some((_, i))) => (*i).min(n.saturating_sub(1)),
|
||||
(None, None) => super::dom::active_artboard(st),
|
||||
};
|
||||
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
|
||||
let fit_art = id == "artboard.fitToArt";
|
||||
let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"artboard"
|
||||
} else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"index"
|
||||
} else {
|
||||
return params;
|
||||
};
|
||||
let Some(p) = params.as_object_mut() else { return params };
|
||||
if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) {
|
||||
return params;
|
||||
}
|
||||
let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() };
|
||||
let kept: Vec<usize> = match start.picks {
|
||||
Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => {
|
||||
list.iter().copied().filter(|i| *i < n).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if kept.len() >= 2 {
|
||||
p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept));
|
||||
} else if picks.is_empty() {
|
||||
p.insert(key.into(), json!(active));
|
||||
} else if fit_art {
|
||||
p.insert("indices".into(), json!(picks));
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// What [`on_active_artboard`] reads besides the session: the index of each open document's active
|
||||
/// artboard as the run started, by document uid; the Artboard tool's selection as the run started,
|
||||
/// with its document's uid; and the `artboard` a step's recorded `command.batch` names.
|
||||
pub(crate) struct Start<'a> {
|
||||
pub active: &'a [(u64, usize)],
|
||||
pub picks: Option<&'a (u64, Vec<usize>)>,
|
||||
pub batch: Option<u64>,
|
||||
}
|
||||
@@ -310,7 +310,7 @@ fn method(link: &Link, f: Member) -> HostMember {
|
||||
}
|
||||
|
||||
/// A member of a class with what `reflect` tells of it.
|
||||
type Described = (String, HostMember, MemberInfo);
|
||||
pub(super) type Described = (String, HostMember, MemberInfo);
|
||||
|
||||
/// A property's or a method's result's type for `reflect`.
|
||||
fn typed(data_type: &str) -> MemberInfo {
|
||||
@@ -318,7 +318,7 @@ fn typed(data_type: &str) -> MemberInfo {
|
||||
}
|
||||
|
||||
/// A method's result's type and its arguments' names and types, for `reflect`.
|
||||
fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect();
|
||||
MemberInfo { arguments, ..typed(data_type) }
|
||||
}
|
||||
@@ -326,7 +326,7 @@ fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
|
||||
/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
let message = format!("{class}.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
@@ -588,7 +588,7 @@ struct Frame {
|
||||
}
|
||||
|
||||
/// The index of the active artboard of `st`, as the view keeps it.
|
||||
fn active_artboard(st: &DocState) -> usize {
|
||||
pub(super) fn active_artboard(st: &DocState) -> usize {
|
||||
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
|
||||
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
|
||||
}
|
||||
@@ -2691,6 +2691,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(save_open::application_members(l));
|
||||
application.extend(print::application_members(l));
|
||||
application.extend(super::actions::app_members(l));
|
||||
let preset = {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
//! only after the run's changes are kept, for the frontend to send once the person approves them
|
||||
//! ([`printing`]).
|
||||
|
||||
pub mod actions;
|
||||
pub mod console;
|
||||
pub mod dialogs;
|
||||
pub mod dollar;
|
||||
@@ -211,6 +212,8 @@ pub(crate) struct Request {
|
||||
pub locale: String,
|
||||
/// The answers to the dialogs of a run with nobody to ask, in order.
|
||||
pub answers: Vec<DialogAnswer>,
|
||||
/// The actions `app.doScript` can play.
|
||||
pub actions: Vec<actions::Playable>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -811,6 +814,15 @@ struct Host {
|
||||
args: RefCell<(Data, u64)>,
|
||||
/// The run's state of the script object model (`app`).
|
||||
dom: dom::State,
|
||||
/// The actions `app.doScript` can play.
|
||||
actions: Vec<actions::Playable>,
|
||||
/// The index of each open document's active artboard as the run starts, by document uid. The
|
||||
/// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it.
|
||||
active_artboards: Vec<(u64, usize)>,
|
||||
/// The artboards the Artboard tool had selected in the active document as the run starts (two or
|
||||
/// more), with that document's uid. The run gives the tool fresh state, which drops them, so the
|
||||
/// steps `app.doScript` plays read them here.
|
||||
artboard_picks: Option<(u64, Vec<usize>)>,
|
||||
/// The documents open when the run began as the person last left them, each with its own file
|
||||
/// and the file it was read from ([`crate::DocState::as_person_left`],
|
||||
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
|
||||
@@ -2098,6 +2110,9 @@ impl Session {
|
||||
if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() {
|
||||
return Err(EngineError::Other(NO_RECOVERY_COPY.to_string()));
|
||||
}
|
||||
// The Artboard tool's selection, which the fresh tool state below drops.
|
||||
let picks = cmd::artboard_tool_picks(self);
|
||||
let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks));
|
||||
self.reset_tool();
|
||||
let open: Vec<u64> = self.docs.iter().map(|d| d.uid).collect();
|
||||
self.script_high_water.retain(|uid, _| open.contains(uid));
|
||||
@@ -2217,6 +2232,9 @@ impl Session {
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
dom: dom::State::new(heap_bytes),
|
||||
actions: request.actions,
|
||||
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
|
||||
artboard_picks,
|
||||
run_docs: RefCell::new(
|
||||
self.docs
|
||||
.iter()
|
||||
|
||||
@@ -49,7 +49,7 @@ mod css;
|
||||
mod curvature_circle;
|
||||
mod cut;
|
||||
mod dashalign;
|
||||
mod dcs;
|
||||
pub(super) mod dcs;
|
||||
mod delete_keeps_joined;
|
||||
mod distort;
|
||||
mod docsetup;
|
||||
@@ -175,6 +175,7 @@ mod repeat_edit;
|
||||
mod save;
|
||||
mod saveoptions;
|
||||
mod scalestrokes;
|
||||
mod script_actions;
|
||||
mod script_console;
|
||||
mod script_dialogs;
|
||||
mod script_dollar;
|
||||
|
||||
@@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// Cyan solid on the top row, PANTONE 185 C at 50% on the left column.
|
||||
fn two_plates() -> Vec<u8> {
|
||||
pub(crate) fn two_plates() -> Vec<u8> {
|
||||
single_file(
|
||||
&[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))],
|
||||
"%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n",
|
||||
@@ -267,6 +267,33 @@ fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_cor
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a DCS file puts
|
||||
/// the file's image between the corners and draws its clipping path through them.
|
||||
#[test]
|
||||
fn place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners() {
|
||||
let dir = temp_dir("replace-distorted-clip");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let mut s = session();
|
||||
let png = crate::tests_links::png(4, 4, [255, 0, 0]);
|
||||
let r = s.execute("file.place", &json!({ "name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100] })).unwrap();
|
||||
let old = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap();
|
||||
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "replace": true })).unwrap();
|
||||
let group = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let id = NodeId(r["image"].as_u64().unwrap());
|
||||
let node = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(node.is_distorted_image());
|
||||
assert_eq!(node.image_corners().unwrap(), corners);
|
||||
let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") };
|
||||
let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") };
|
||||
let anchors: Vec<_> = path.anchors().map(|(_, _, a)| a.p).collect();
|
||||
// The left half of the 2 × 2 pixels, where the corners put it.
|
||||
let map = node.image_map().unwrap();
|
||||
let want = [(0.0, 0.0), (1.0, 0.0), (1.0, 2.0), (0.0, 2.0)].map(|(x, y)| map.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
|
||||
assert!(anchors.len() == want.len() && want.iter().all(|w| anchors.iter().any(|a| a.distance(*w) < 1e-6)), "{anchors:?} vs {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_link_clips_an_image_whose_file_gained_a_clipping_path() {
|
||||
let dir = temp_dir("update-gained-clip");
|
||||
|
||||
@@ -812,6 +812,47 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() {
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Place with Replace of a distorted image by an image file keeps its corners, in one undo step:
|
||||
/// the new file's pixels fill them, the new image is linked to that file, and its transform is the
|
||||
/// old image's scaled to the new pixel size. Undo brings the old image back between the same
|
||||
/// corners.
|
||||
#[test]
|
||||
fn place_with_replace_keeps_a_distorted_images_corners() {
|
||||
let dir = Folder::new("distorted-place-replace");
|
||||
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
|
||||
write(&photo, &png(20, 10, RED));
|
||||
write(&other, &png(60, 20, BLUE));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// Around the artboard's center, where `centre_colour` looks.
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).cloned();
|
||||
let before = node(&s, id).unwrap().image_corners().unwrap();
|
||||
let old_xf = image(&s, id).xf;
|
||||
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let undo = undo_len(&s);
|
||||
|
||||
let r = s.execute("file.place", &json!({"path": other, "replace": true})).unwrap();
|
||||
let new = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert!(node(&s, id).is_none(), "the old image is replaced");
|
||||
let n = node(&s, new).unwrap();
|
||||
assert!(n.is_distorted_image());
|
||||
assert_eq!(n.image_corners().unwrap(), before);
|
||||
let im = image(&s, new);
|
||||
assert_eq!((im.width, im.height), (60, 20));
|
||||
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str()));
|
||||
let want = old_xf * vectorcraft_geom::Affine::scale_non_uniform(20.0 / 60.0, 10.0 / 20.0);
|
||||
assert!(im.xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{:?} against {want:?}", im.xf);
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, new).is_none());
|
||||
assert_eq!(node(&s, id).unwrap().image_corners().unwrap(), before);
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Unembed into a folder keeps a distorted image's corners, in one undo step.
|
||||
#[test]
|
||||
fn unembed_to_a_folder_keeps_a_distorted_images_corners() {
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
//! `app.doScript`: a script plays an action of `script.run`'s `actions`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions}))
|
||||
}
|
||||
|
||||
fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec<Value> {
|
||||
let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The error message a `try` around `call` logs, or `"ok"`.
|
||||
fn caught(s: &mut Session, call: &str, actions: &Value) -> String {
|
||||
let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}");
|
||||
log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
fn doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn objects(s: &Session) -> usize {
|
||||
s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum()
|
||||
}
|
||||
|
||||
fn undo_labels(s: &Session) -> Vec<String> {
|
||||
s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect()
|
||||
}
|
||||
|
||||
fn rect(x: i64) -> Value {
|
||||
json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}})
|
||||
}
|
||||
|
||||
/// One set, `Set`, with the actions given as (name, steps).
|
||||
fn set(actions: &[(&str, Vec<Value>)]) -> Value {
|
||||
Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_script_plays_every_step_as_one_undo_step_with_the_script() {
|
||||
let mut s = doc();
|
||||
let before = undo_labels(&s);
|
||||
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
|
||||
let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions);
|
||||
assert_eq!(out, vec![Value::Null], "doScript returns undefined");
|
||||
assert_eq!(objects(&s), 3);
|
||||
let after = undo_labels(&s);
|
||||
assert_eq!(after.len(), before.len() + 1, "{after:?}");
|
||||
assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL));
|
||||
// The steps of a recorded `command.batch` run one by one, each counted as a host call.
|
||||
let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]);
|
||||
let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap();
|
||||
assert_eq!(objects(&s), 6);
|
||||
let r0 = run_with(&mut s, "1;", &batch).unwrap();
|
||||
assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_throw_puts_back_what_the_action_did() {
|
||||
let mut s = doc();
|
||||
let before = (objects(&s), undo_labels(&s));
|
||||
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
|
||||
let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string();
|
||||
assert!(e.contains("late"), "{e}");
|
||||
assert_eq!((objects(&s), undo_labels(&s)), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_step_is_put_back_and_the_steps_before_it_stay() {
|
||||
let mut s = doc();
|
||||
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
|
||||
let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]);
|
||||
let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions);
|
||||
assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}");
|
||||
assert_eq!(objects(&s), 1, "the first step stays done and the third never runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_matched_exactly_and_must_be_one_action() {
|
||||
let mut s = doc();
|
||||
let actions = json!([
|
||||
{"set": "Set", "name": "One", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Empty", "steps": []},
|
||||
]);
|
||||
assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps");
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”");
|
||||
assert_eq!(objects(&s), 0);
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok");
|
||||
assert_eq!(objects(&s), 1);
|
||||
assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet");
|
||||
assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arguments_throw_and_change_nothing() {
|
||||
let mut s = doc();
|
||||
let actions = set(&[("One", vec![rect(0)])]);
|
||||
for (call, want) in [
|
||||
("app.doScript()", "TypeError"),
|
||||
("app.doScript(1, 'Set')", "TypeError"),
|
||||
("app.doScript('One', {})", "TypeError"),
|
||||
("app.doScript('One', 'Set', 'yes')", "TypeError"),
|
||||
("app.doScript('One', 'Set', 1)", "TypeError"),
|
||||
("app.doScript('One', 'Set', false, 4)", "TypeError"),
|
||||
("app.doScript('', 'Set')", "Error"),
|
||||
("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"),
|
||||
] {
|
||||
let m = caught(&mut s, call, &actions);
|
||||
assert!(m.starts_with(&format!("{want}:")), "{call}: {m}");
|
||||
}
|
||||
assert_eq!(objects(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_a_script_may_not_run_stop_the_action_before_any_step() {
|
||||
let mut s = doc();
|
||||
s.prefs.show_external_script_warning = true;
|
||||
let steps = [
|
||||
(json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"),
|
||||
(json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"),
|
||||
(json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"),
|
||||
(json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"),
|
||||
(json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"),
|
||||
(json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"),
|
||||
];
|
||||
for (bad, want) in steps {
|
||||
let actions = set(&[("Loop", vec![rect(0), bad.clone()])]);
|
||||
let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions);
|
||||
assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}");
|
||||
assert_eq!(objects(&s), 0, "{bad}: no step ran");
|
||||
}
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
// A refused command inside a recorded batch is refused too.
|
||||
let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]);
|
||||
let m = caught(&mut s, "app.doScript('B', 'Set')", &batch);
|
||||
assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}");
|
||||
assert_eq!(objects(&s), 0);
|
||||
// So is one among the commands a Batch step plays on each file, before the steps ahead of it run.
|
||||
let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}});
|
||||
let batch = set(&[("F", vec![rect(0), files])]);
|
||||
let m = caught(&mut s, "app.doScript('F', 'Set')", &batch);
|
||||
assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}");
|
||||
assert_eq!(objects(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_action_step_keeps_the_scripts_file_gate() {
|
||||
let mut s = doc();
|
||||
let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}});
|
||||
let actions = set(&[("Export", vec![export])]);
|
||||
let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions);
|
||||
assert!(m.contains("Script file access denied"), "{m}");
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_action_is_held_to_the_host_call_limit() {
|
||||
let mut s = doc();
|
||||
// Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the
|
||||
// steps of one call cannot pass the limit.
|
||||
let calls = |s: &mut Session, steps: usize| {
|
||||
let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]);
|
||||
run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap()
|
||||
};
|
||||
let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001));
|
||||
assert!(many >= one + 2000, "{one} {many}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_action_lists_are_refused_before_the_script_runs() {
|
||||
let mut s = doc();
|
||||
let step = || json!({"command": "select.none"});
|
||||
let cases = [
|
||||
(json!({}), "`actions` must be a list"),
|
||||
(json!([1]), "`actions[0]` must be an object"),
|
||||
(json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"),
|
||||
(json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"),
|
||||
(
|
||||
json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]),
|
||||
"a command.batch inside a command.batch",
|
||||
),
|
||||
(json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"),
|
||||
(Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"),
|
||||
(json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"),
|
||||
];
|
||||
for (actions, want) in cases {
|
||||
let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{want}: {e}");
|
||||
}
|
||||
let many: Vec<Value> = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect();
|
||||
let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string();
|
||||
assert!(e.contains("more than 100000 steps in all"), "{e}");
|
||||
assert_eq!(objects(&s), 0, "no run started");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() {
|
||||
let mut s = doc();
|
||||
let first = set(&[("One", vec![rect(0)])]);
|
||||
log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first);
|
||||
assert_eq!(objects(&s), 0);
|
||||
// The next run has no actions: the function kept from the first run finds none.
|
||||
let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }";
|
||||
assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]);
|
||||
let two = set(&[("One", vec![rect(0), rect(30)])]);
|
||||
assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]);
|
||||
assert_eq!(objects(&s), 2);
|
||||
}
|
||||
|
||||
/// Makes artboard `index` of the active document the view's active one, as the app does before each
|
||||
/// command.
|
||||
fn make_active(s: &mut Session, index: usize) {
|
||||
let id = s.active().unwrap().doc.artboards[index].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(id);
|
||||
}
|
||||
|
||||
/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected
|
||||
/// Art, acts on the active artboard's index as the run started; after the script deletes that
|
||||
/// artboard, the last one. A step that names its artboard keeps it.
|
||||
#[test]
|
||||
fn steps_act_on_the_artboard_active_as_they_run() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let was = boards(&s);
|
||||
make_active(&mut s, 2);
|
||||
let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}});
|
||||
let mut first = align(json!(0));
|
||||
first["params"].as_object_mut().unwrap().remove("artboard");
|
||||
let actions = set(&[
|
||||
("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]),
|
||||
("Align 1", vec![align(json!(0))]),
|
||||
("Fit", vec![json!({"command": "artboard.fitToSelection"})]),
|
||||
]);
|
||||
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions);
|
||||
let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
|
||||
assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was");
|
||||
assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other");
|
||||
log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it");
|
||||
}
|
||||
|
||||
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
|
||||
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
|
||||
#[test]
|
||||
fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
make_active(&mut s, 1);
|
||||
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
|
||||
let mut own = align.clone();
|
||||
own["params"]["artboard"] = json!(1);
|
||||
let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}});
|
||||
let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]);
|
||||
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
log_with(&mut s, "app.doScript('First', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[0].x0, "the batch's artboard 0");
|
||||
log_with(&mut s, "app.doScript('Past', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one");
|
||||
log_with(&mut s, "app.doScript('Own', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it");
|
||||
}
|
||||
|
||||
/// The active artboard a step gets is the index it had as the run started: after a step deletes an
|
||||
/// artboard before it, the artboard now at that index, as the view shows it.
|
||||
#[test]
|
||||
fn steps_keep_the_active_artboards_index() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
|
||||
let uid = s.active().unwrap().uid;
|
||||
let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None };
|
||||
let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({}));
|
||||
assert_eq!(add(&s), json!({"artboard": 1}));
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1");
|
||||
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
|
||||
assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one");
|
||||
}
|
||||
|
||||
/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its
|
||||
/// `indices` fits those.
|
||||
#[test]
|
||||
fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let mut art = Vec::new();
|
||||
for b in &was {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
|
||||
}
|
||||
make_active(&mut s, 1);
|
||||
let actions = set(&[
|
||||
("Fit", vec![json!({"command": "artboard.fitToArt"})]),
|
||||
("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]),
|
||||
]);
|
||||
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
|
||||
assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art");
|
||||
log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions);
|
||||
assert_eq!(boards(&s), art, "the step's own indices");
|
||||
}
|
||||
|
||||
/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it
|
||||
/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps
|
||||
/// still get the active one.
|
||||
#[test]
|
||||
fn paste_and_fit_steps_keep_the_artboard_tools_selection() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
|
||||
make_active(&mut s, 1);
|
||||
let start = script::actions::Start { active: &[], picks: None, batch: None };
|
||||
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
|
||||
assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1}));
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
|
||||
assert_eq!(add(&s, id), json!({}), "{id}");
|
||||
}
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]}));
|
||||
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
|
||||
assert_eq!(add(&s, "object.align"), json!({"artboard": 1}));
|
||||
assert_eq!(add(&s, "shape.rectangle"), json!({}));
|
||||
}
|
||||
|
||||
/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays,
|
||||
/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to
|
||||
/// Artwork Bounds step fits them.
|
||||
#[test]
|
||||
fn a_run_keeps_the_artboard_tools_selection_for_its_steps() {
|
||||
// Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2.
|
||||
let setup = || {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let mut art = Vec::new();
|
||||
for b in &was {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
|
||||
}
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
make_active(&mut s, 1);
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
(s, was, art)
|
||||
};
|
||||
let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]);
|
||||
let (mut s, ..) = setup();
|
||||
let before = objects(&s);
|
||||
log_with(&mut s, "app.doScript('Paste', 'Set');", &actions);
|
||||
assert_eq!(objects(&s), before + 2, "one copy on each selected artboard");
|
||||
let (mut s, was, art) = setup();
|
||||
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
|
||||
let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art");
|
||||
// A kept artboard past the last one is left out; with fewer than two left, the active one applies.
|
||||
let (mut s, ..) = setup();
|
||||
s.reset_tool();
|
||||
let uid = s.active().unwrap().uid;
|
||||
let kept = (uid, vec![0, 2]);
|
||||
let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None };
|
||||
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
|
||||
assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]}));
|
||||
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
|
||||
s.execute("artboard.delete", &json!({"index": 2})).unwrap();
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
|
||||
}
|
||||
@@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
|
||||
fuel: script::DEFAULT_FUEL,
|
||||
locale: "en_US".into(),
|
||||
answers: Vec::new(),
|
||||
actions: Vec::new(),
|
||||
};
|
||||
s.script_start(request).unwrap();
|
||||
assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1]));
|
||||
|
||||
@@ -1044,9 +1044,10 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
|
||||
("object.cropImage", json!({})),
|
||||
("imageTrace.make", json!({})),
|
||||
("object.mesh.create", json!({})),
|
||||
// Vector art has no pixels to put between the corners.
|
||||
(
|
||||
"file.place",
|
||||
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
|
||||
json!({"replace": true, "name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(b"<svg xmlns='http://www.w3.org/2000/svg' width='9' height='9'><rect width='9' height='9'/></svg>")}),
|
||||
),
|
||||
] {
|
||||
let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
|
||||
@@ -93,9 +93,10 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \
|
||||
getIsFileOpen open PPDFileList printPresetsList printerList redraw selection selection= textFonts toString \
|
||||
typename userInteractionLevel userInteractionLevel=",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= open PPDFileList printPresetsList printerList redraw \
|
||||
selection selection= textFonts toString typename unloadAction unloadAction= userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
|
||||
@@ -166,6 +166,8 @@ impl VectorcraftApp {
|
||||
}
|
||||
let mut params = params;
|
||||
self.add_active_artboard(id, &mut params);
|
||||
// A script's `app.doScript` plays the Actions panel's actions.
|
||||
panels::actions::add_script_actions(self, id, &mut params);
|
||||
// Edit Symbol from the Symbols panel in a document without artboards centers the symbol's
|
||||
// art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit
|
||||
// steps too.
|
||||
|
||||
@@ -194,11 +194,12 @@ impl Rows<'_> {
|
||||
self.range(key, label, range, 1, UnitKind::Percent)
|
||||
}
|
||||
|
||||
/// A length in points, shown in the general unit.
|
||||
/// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says.
|
||||
fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param {
|
||||
// Stored in points; a pixel is a point, as the rulers count it.
|
||||
let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0);
|
||||
self.range(key, label, range, 1, UnitKind::Pixels).length(crate::fields::bare_points(lengths, self.bare_points))
|
||||
let shown = super::three_d_classic::length_unit(self.unit);
|
||||
self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points))
|
||||
}
|
||||
|
||||
fn flag(&self, key: &str, label: &'static str) -> Param {
|
||||
|
||||
@@ -494,6 +494,41 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() {
|
||||
assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent)));
|
||||
}
|
||||
|
||||
/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their
|
||||
/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit.
|
||||
#[test]
|
||||
fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
|
||||
use craft::ui::patterns::form_dialogs::DialogFields;
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use vectorcraft_doc::Unit;
|
||||
let app = VectorcraftApp::new(Session::new(), crate::Services::default());
|
||||
let unit = |general: Unit, effect: &str, page: &str, key: &str| {
|
||||
let mut data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new());
|
||||
data.unit = general;
|
||||
let mut fields = DialogFields::new();
|
||||
fields.set("__page", FieldValue::Text(page.into()));
|
||||
super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit)
|
||||
};
|
||||
let mut checked = 0;
|
||||
for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] {
|
||||
for key in ["depth", "bevelWidth", "bevelHeight"] {
|
||||
assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}");
|
||||
checked += 1;
|
||||
}
|
||||
let others = [
|
||||
(REVOLVE, "rotation", "offset"),
|
||||
(CLASSIC_EXTRUDE, "object", "depth"),
|
||||
(CLASSIC_EXTRUDE, "object", "bevelHeight"),
|
||||
(CLASSIC_REVOLVE, "object", "offset"),
|
||||
];
|
||||
for (effect, page, key) in others {
|
||||
assert_eq!(unit(general, effect, page, key), Some(Some(shown)), "{effect} {key} in {general:?}");
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, 21);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_all_keeps_map_art_and_its_options() {
|
||||
let mut h = drawn(SQUARE, CLASSIC_EXTRUDE);
|
||||
|
||||
@@ -50,9 +50,13 @@ const MAP_SYMBOL: &str = "mapSymbol";
|
||||
/// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters.
|
||||
pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]];
|
||||
|
||||
/// The unit of the general-unit length rows.
|
||||
fn length_unit(unit: Unit) -> UnitKind {
|
||||
crate::canvas::rulers::unit_kind(unit)
|
||||
/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when
|
||||
/// that counts the same number (points, or pixels at 72 per inch), and points otherwise.
|
||||
pub(super) fn length_unit(unit: Unit) -> UnitKind {
|
||||
match crate::canvas::rulers::unit_kind(unit) {
|
||||
UnitKind::Pixels => UnitKind::Pixels,
|
||||
_ => UnitKind::Points,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the rows show: the 3D and Materials panel marks its fields with `__panel`.
|
||||
|
||||
@@ -58,7 +58,7 @@ pub use playback::{
|
||||
deserialize_playback, play, play_action, play_at, playback_drawn, playback_held, playback_options, playback_shown, tick_playback,
|
||||
waiting_at_stop,
|
||||
};
|
||||
pub(crate) use playback::{KnownCommands, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands};
|
||||
pub(crate) use playback::{KnownCommands, add_script_actions, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands};
|
||||
pub use recording::{START_RECORDING, STOP_RECORDING, record, stop};
|
||||
pub(crate) use recording::{after_journaled_edit, after_recorded_command, before_recorded_command};
|
||||
|
||||
|
||||
@@ -39,6 +39,72 @@ fn playback_steps(action: &Action) -> Vec<PlayStep> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// For command `id` `script.run`, or the script of `script.startup.run`'s `then`: gives its
|
||||
/// `params` the panel's actions as `actions`, which the script's `app.doScript` plays, unless the
|
||||
/// caller gave them: every action of every set, in panel order, with its steps as playback runs
|
||||
/// them ([`playback_steps`]) and each step's place in the action. An action that `actions` cannot
|
||||
/// hold (a step that is not a command, a name that is too long, or one past the limits of
|
||||
/// [`vectorcraft_engine::script::actions`]) is left out.
|
||||
pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) {
|
||||
use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, Playable, parse};
|
||||
let target = match id {
|
||||
"script.run" => Some(params),
|
||||
"script.startup.run" => params.get_mut("then"),
|
||||
_ => None,
|
||||
};
|
||||
let Some(p) = target.and_then(Value::as_object_mut) else { return };
|
||||
if p.contains_key("actions") {
|
||||
return;
|
||||
}
|
||||
let list = &app.ui.actions;
|
||||
let (mut held, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize);
|
||||
for set in list.sets() {
|
||||
for a in model::members(list, set).into_iter().filter_map(|i| list.action(i)) {
|
||||
if held.len() >= MAX_ACTIONS {
|
||||
break;
|
||||
}
|
||||
// The commands of a recorded `command.batch` step go back into one batch step, so that an
|
||||
// error names a failing command by the batch's place and its own (`3.2`).
|
||||
let mut played: Vec<Value> = Vec::new();
|
||||
for s in playback_steps(a) {
|
||||
let params = match s.command.get("params") {
|
||||
None | Some(Value::Null) => json!({}),
|
||||
Some(p) => p.clone(),
|
||||
};
|
||||
let one = json!({"command": s.command.get("command").cloned().unwrap_or(Value::Null), "params": params});
|
||||
let place = s.row + 1;
|
||||
if a.steps.get(s.row).is_none_or(|step| step.command != "command.batch") {
|
||||
let mut one = one;
|
||||
one["step"] = json!(place);
|
||||
played.push(one);
|
||||
continue;
|
||||
}
|
||||
match played.last_mut() {
|
||||
Some(last) if last["command"] == "command.batch" && last["step"] == place => {
|
||||
if let Some(Value::Array(inner)) = last.pointer_mut("/params/commands") {
|
||||
inner.push(one);
|
||||
}
|
||||
}
|
||||
_ => played.push(json!({"command": "command.batch", "params": {"commands": [one]}, "step": place})),
|
||||
}
|
||||
}
|
||||
let one = Value::Array(vec![json!({"set": set, "name": a.name, "steps": played})]);
|
||||
let Ok(parsed) = parse(Some(&one)) else { continue };
|
||||
let count = parsed.first().map_or(0, Playable::len);
|
||||
let size = serde_json::to_vec(&one).map_or(usize::MAX, |b| b.len());
|
||||
if steps + count > MAX_ALL_STEPS || bytes.saturating_add(size) > MAX_ACTIONS_BYTES {
|
||||
continue;
|
||||
}
|
||||
steps += count;
|
||||
bytes += size;
|
||||
if let Value::Array(mut one) = one {
|
||||
held.append(&mut one);
|
||||
}
|
||||
}
|
||||
}
|
||||
p.insert("actions".into(), Value::Array(held));
|
||||
}
|
||||
|
||||
/// The steps of `action` whose command `known` does not hold, in order, as (step index, the index
|
||||
/// of the command in a `command.batch` step, command id). A `command.batch` step's own commands are
|
||||
/// checked one by one, as playback runs them ([`included_commands`]); a command of one with no
|
||||
|
||||
@@ -637,6 +637,79 @@ fn an_error_counts_excluded_steps() {
|
||||
assert_eq!(x(&app), 0.0, "the failing batch changes nothing");
|
||||
}
|
||||
|
||||
/// A script's `app.doScript` plays the panel's actions with their included steps; an action whose
|
||||
/// step `script.run`'s `actions` cannot hold is left out, and a caller's own list is kept.
|
||||
#[test]
|
||||
fn a_script_plays_the_panels_actions() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let rect = |x: i64| ("shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}));
|
||||
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
|
||||
let batch = json!({"commands": [{"command": "select.none"}, bad]});
|
||||
let actions = vec![
|
||||
action("Draw", &[rect(0), rect(20), rect(40)]),
|
||||
action("Odd", &[rect(0), ("select.none", json!(5))]),
|
||||
action("Batched", &[("select.none", json!({})), ("command.batch", batch)]),
|
||||
];
|
||||
push_set(&mut app, "Mine", actions);
|
||||
let draw = model::members(&app.ui.actions, "Mine")[0];
|
||||
app.ui.actions.set_step(draw, 1, false).unwrap();
|
||||
let objects =
|
||||
|app: &VectorcraftApp| app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::<usize>());
|
||||
let undo = app.session.active().map_or(0, |d| d.history.undo.len());
|
||||
app.session.script_frames = false;
|
||||
let source = "app.doScript('Draw', 'Mine'); try { app.doScript('Odd', 'Mine'); } catch (e) { vc.log(e.message); }";
|
||||
let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
|
||||
assert_eq!(r["log"], json!(["the set “Mine” has no action “Odd”"]));
|
||||
assert_eq!(objects(&app), 2, "the excluded step does not run");
|
||||
assert_eq!(app.session.active().map_or(0, |d| d.history.undo.len()), undo + 1);
|
||||
// A failing command of a recorded batch is named by the batch's place and its own.
|
||||
let source = "try { app.doScript('Batched', 'Mine'); } catch (e) { vc.log(e.message); }";
|
||||
let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
|
||||
let m = r["log"][0].as_str().unwrap_or_default();
|
||||
assert!(m.starts_with("action step 2.2 of “Batched” (`object.move`) failed:"), "{m}");
|
||||
let r =
|
||||
app.run("script.run", json!({"source": "try { app.doScript('Draw', 'Mine'); } catch (e) { vc.log(e.message); }", "actions": []})).unwrap();
|
||||
assert_eq!(r["log"], json!(["there is no action set “Mine”"]));
|
||||
assert_eq!(objects(&app), 2);
|
||||
}
|
||||
|
||||
/// The script that `script.startup.run` runs after the startup scripts (its `then`) plays the
|
||||
/// panel's actions too, as File › Scripts runs a script with Run Startup Scripts on.
|
||||
#[test]
|
||||
fn the_script_after_the_startup_scripts_plays_the_panels_actions() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
push_set(&mut app, "Mine", vec![action("Draw", &[("shape.rectangle", json!({"x": 0, "y": 10, "width": 10, "height": 10}))])]);
|
||||
app.session.script_frames = false;
|
||||
let then = json!({"source": "try { app.doScript('Draw', 'Mine'); vc.log('ok'); } catch (e) { vc.log(e.message); }", "name": "t.js"});
|
||||
let r = app.run("script.startup.run", json!({"reason": "menu", "then": then})).unwrap();
|
||||
assert_eq!(r["then"]["log"], json!(["ok"]), "{r}");
|
||||
}
|
||||
|
||||
/// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's
|
||||
/// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art.
|
||||
#[test]
|
||||
fn a_script_plays_the_actions_on_the_active_artboard() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("paint.setStroke", json!({"none": true})).unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
|
||||
let batch = json!({"commands": [align]});
|
||||
push_set(&mut app, "Mine", vec![action("Align", &[("command.batch", batch)]), action("Fit", &[("artboard.fitToSelection", json!({}))])]);
|
||||
let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let was = boards(&app);
|
||||
app.view_mut().unwrap().artboard = 1;
|
||||
app.session.script_frames = false;
|
||||
let source = "app.doScript('Align', 'Mine'); app.doScript('Fit', 'Mine');";
|
||||
app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
|
||||
let art = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
|
||||
assert_eq!(art.x0, was[1].x0, "aligned to artboard 2, the active one");
|
||||
assert_eq!(boards(&app), [was[0], art], "Fit to Selected Art resizes artboard 2 and leaves artboard 1");
|
||||
}
|
||||
|
||||
/// A step of a recorded `command.batch` that fails is named by the batch's place in the action
|
||||
/// and its own command.
|
||||
#[test]
|
||||
|
||||
+29
-3
@@ -3224,6 +3224,29 @@ other files through `$`:
|
||||
`importVariables` and `exportVariables` take a `File`, not a path, which must be a file the script may read, or
|
||||
write, through its `File` objects; the files of the open documents do not count. A value that changes nothing runs
|
||||
no command.
|
||||
- `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method
|
||||
of the scripting reference
|
||||
https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf
|
||||
describes it, and returns `undefined` once every step has run. The actions come from `script.run`'s `actions`; the
|
||||
app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own
|
||||
steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and
|
||||
Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to
|
||||
Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run
|
||||
started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one
|
||||
past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to
|
||||
Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that
|
||||
names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's
|
||||
own rules: the action and its set are matched by their exact names, and a name that matches no action or more than
|
||||
one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have
|
||||
(a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any
|
||||
step runs, as does such a command among the commands a Batch step (`action.batch`) plays on each file, so an
|
||||
action cannot play itself.
|
||||
Each step then runs as `vc.run` runs a command: it joins the run's one undo step for each changed document, counts
|
||||
as a host call, and reads and writes files only where the script may. A step that fails is put back and throws an
|
||||
error that gives the step's place, the action's name and the step's command, and the steps before it stay done; an
|
||||
uncaught error later puts them back with the rest of the run. `dialogs` must be `true` or `false` (default
|
||||
`false`); no step opens a dialog, so it changes nothing. `app.loadAction` and `app.unloadAction` throw an error
|
||||
that says they are not available yet when they are read or assigned.
|
||||
- `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/)
|
||||
with `typename`, `length`, `parent`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`, and each
|
||||
`Tag` (https://ai-scripting.docsforadobe.dev/jsobjref/Tag/) has `typename`, `name`, `value`, `parent` (its page
|
||||
@@ -9009,9 +9032,12 @@ the corners where they are records none. Image info (`image.info`) gives a disto
|
||||
Info (`links.info`) gives its scale and rotation there.
|
||||
|
||||
Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`) and Place with Replace
|
||||
(`file.place` with `replace`) of anything but a text file refuse a
|
||||
distorted image with an error that names the distortion; Place with Replace does not refuse a clipping group that holds
|
||||
a distorted image of a DCS file's plates. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is
|
||||
(`file.place` with `replace`) of a file that is not text, a raster image or a DCS file refuse a distorted image with an error that names the distortion; Place with Replace does not
|
||||
refuse a clipping group that holds a distorted image of a DCS file's plates. Place with Replace of a distorted image by
|
||||
a raster image or a DCS file puts the new image's pixels between the old image's corners, in one undo step; the new
|
||||
image's transform is the old one scaled to the new pixel size, the clipping path a PSD, PSB or DCS file names is
|
||||
drawn through the corners, and each slice a PSD or PSB file brings in covers the box around its part of the pixels
|
||||
where the corners put it. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is
|
||||
given and lists each distorted image it leaves as it is in `skipped`, with its `id` and the error as `reason`; with
|
||||
nothing else to convert, it returns that error. Update Links (`links.update`) and Relink
|
||||
(`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or
|
||||
|
||||
@@ -1125,6 +1125,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
|
||||
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`.
|
||||
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
|
||||
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
|
||||
- Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`.
|
||||
@@ -1324,8 +1325,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`).
|
||||
- The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image and the placed file is not text, a raster image or a DCS file, so it does not refuse when the replaced object is a DCS file's plates); Update Links, Relink and Place with Replace of a raster image or a DCS file put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::place_with_replace_keeps_a_distorted_images_corners`, `dcs::place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners`, `cmd::fileio::tests_psdslices::slices_placed_over_a_distorted_image_follow_its_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) put the corners of a type object's box and of a symbol instance's box exactly where the warp takes them, alone or with other objects; the object stays type or a symbol instance and is drawn through the warp, after any perspective projection it had, as type and symbols in perspective are, with the images in a symbol's art and their linked masks drawn in perspective between the corners the projection gives them; and corners that would fold its box over, carry it past the warp's horizon or lie too close together for a perspective map are refused with an error that names it, as is a perspective warp of type that Edit Text shows flat. VectorCraft's own rule (engine `xform::distort_puts_the_corners_of_type_and_symbol_instances_on_the_handles`, `distort_moves_type_and_symbol_instances_with_a_path_as_one`, `distort_refuses_corners_type_and_symbol_instances_cannot_follow`, `distort_refuses_type_being_edited_flat`; effects `group::tests::a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`).
|
||||
- Object › Create Object Mosaic on an image changed by Perspective Distort or Free Distort places each tile's cell of pixels between the image's corners, so the tiles are four-sided shapes that follow the perspective, in one undo step; a new size scales them from the top left of the image's bounds, and the spacing and Use Ratio measure a pixel by the mean length of the image's two sides along each axis (VectorCraft's own rule; engine `object_mosaic_tiles_of_a_distorted_image_follow_its_corners`).
|
||||
- The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`).
|
||||
- With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`).
|
||||
|
||||
Reference in new issue
Block a user