mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 14:03:16 -05:00
Merge feat/scripts-api-d10-print-options into feat/print-per-job-settings
Takes the script File design with native slots, Document.fullName, path, saved and close, and Check Script's reading of bracketed document chains. PrintJobOptions.bitmapResolution stays mapped to advanced.bitmapResolution, and the print option classes keep main's reflect rules for unmapped properties.
This commit is contained in:
commit
6c8bf23132
98 files changed
+5242
-458
No files matched your search
Generated
-15
@@ -10759,18 +10759,3 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
@@ -8,7 +8,6 @@ version = "0.25.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
@@ -89,7 +88,6 @@ vectorcraft-apischema = { path = "crates/apischema" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
peniko = "0.6"
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
@@ -159,10 +157,8 @@ egui = "0.37"
|
||||
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
clipboard-win = "5.4"
|
||||
webbrowser = "1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "deny"
|
||||
@@ -213,8 +209,5 @@ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed1817
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
@@ -163,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -5,6 +5,10 @@ dist = "../../dist/web"
|
||||
public_url = "./"
|
||||
filehash = true
|
||||
|
||||
[tools]
|
||||
# Binaryen 123 crashes while optimizing the release bundle; keep the optimizer explicit.
|
||||
wasm_opt = "version_133"
|
||||
|
||||
[serve]
|
||||
addresses = ["127.0.0.1"]
|
||||
port = 8766
|
||||
|
||||
+15
-11
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::ControlFlow;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -403,6 +404,8 @@ thread_local! {
|
||||
thread_local! {
|
||||
/// How many objects' drawn art [`drawn`] evaluated on this thread.
|
||||
static DRAWN_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many times [`has_own_effects`] read an object's effects on this thread.
|
||||
static OWN_EFFECTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect
|
||||
@@ -527,7 +530,7 @@ fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
/// kept alone.
|
||||
fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>)> {
|
||||
let f = DRAWN_ART.get()?;
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) {
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !draws_effects(symbols, n) {
|
||||
return None;
|
||||
}
|
||||
let doc = symbols.document();
|
||||
@@ -568,7 +571,7 @@ fn evaluates(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide, .. } => !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(),
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => !n.appearance.items.is_empty() || has_own_effects(n),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -1188,23 +1191,24 @@ pub(crate) fn clip_region_inputs() -> (u64, bool) {
|
||||
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
let mut found = false;
|
||||
clip.walk(&mut |n| found |= has_own_effects(n));
|
||||
found
|
||||
clip.try_walk(&mut |n| if has_own_effects(n) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }).is_break()
|
||||
}
|
||||
|
||||
/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it.
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. The walk starts
|
||||
/// at `n`, so its own effects are read once, here, and it ends at the first object with an effect.
|
||||
fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| {
|
||||
found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
});
|
||||
found
|
||||
n.try_walk(&mut |c| {
|
||||
let has = has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
if has { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
|
||||
})
|
||||
.is_break()
|
||||
}
|
||||
|
||||
/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes?
|
||||
fn has_own_effects(n: &Node) -> bool {
|
||||
#[cfg(test)]
|
||||
OWN_EFFECTS_READ.with(|c| c.set(c.get() + 1));
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible))
|
||||
}
|
||||
|
||||
@@ -3652,6 +3652,48 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
|
||||
}
|
||||
|
||||
/// A hover over empty canvas past many plain paths reads each path's effects once, and the layer's
|
||||
/// once.
|
||||
#[test]
|
||||
fn hovers_past_plain_paths_read_each_paths_effects_once() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let paths = 100;
|
||||
for i in 0..paths {
|
||||
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
}
|
||||
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
|
||||
let before = reads();
|
||||
assert!(hit_test(&d, Point::new(900.0, 900.0), HitOptions::default()).is_none());
|
||||
let read = reads() - before;
|
||||
assert_eq!(read, paths + 1, "each path's effects and the layer's are read once");
|
||||
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
|
||||
}
|
||||
|
||||
/// Whether a compound clipping path, or a compound path, has a live effect is settled by the first
|
||||
/// object found with one: the members after it are not read.
|
||||
#[test]
|
||||
fn an_effect_on_a_compound_path_is_found_without_reading_its_members() {
|
||||
set_clip_region(moved_clip_region);
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let members: Vec<_> = (0..100)
|
||||
.map(|i| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(i as f64, 0.0, i as f64 + 5.0, 5.0)), Default::default())))
|
||||
.collect();
|
||||
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance.effects.push(test_move());
|
||||
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
|
||||
let before = reads();
|
||||
assert!(has_effects(&mask));
|
||||
assert_eq!(reads() - before, 1, "the clipping path's own effect ends the search");
|
||||
let symbols = d.symbol_boxes();
|
||||
let before = reads();
|
||||
assert!(draws_effects(&symbols, &mask));
|
||||
assert_eq!(reads() - before, 1, "the compound path's own effect ends the search");
|
||||
}
|
||||
|
||||
/// The pointer resting over empty canvas past many paths reads their anchors for their culling
|
||||
/// boxes on the first hover only: the next hovers use the boxes the paths keep.
|
||||
#[test]
|
||||
|
||||
@@ -308,16 +308,8 @@ fn resolve_kids(
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> Vec<(usize, Arc<Node>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
let mut out = vec![];
|
||||
for (i, c) in kids.iter().enumerate() {
|
||||
let o = old.and_then(|old| match old.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
});
|
||||
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
|
||||
continue;
|
||||
}
|
||||
for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) {
|
||||
let mut c = c.clone();
|
||||
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
|
||||
out.push((i, c));
|
||||
|
||||
@@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize};
|
||||
pub use metadata::{CopyrightStatus, DocMetadata};
|
||||
pub use node::Knockout;
|
||||
pub use node::Scaling;
|
||||
pub use node::changed_nodes;
|
||||
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use orient::OrientedBox;
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes};
|
||||
use crate::text::TextObject;
|
||||
|
||||
mod attributes;
|
||||
mod changed;
|
||||
mod clip;
|
||||
mod extras;
|
||||
mod ids;
|
||||
@@ -25,6 +26,9 @@ mod ops;
|
||||
mod wire;
|
||||
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
#[cfg(test)]
|
||||
pub(crate) use changed::COUNTERPART_LOOKUPS;
|
||||
pub use changed::changed_nodes;
|
||||
pub use clip::{ClipPaint, Uniter};
|
||||
pub use extras::{Extras, ExtrasMut, NodeExtras};
|
||||
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{Arc, Node, NodeId};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread.
|
||||
pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same
|
||||
/// list before an edit), with their positions in `after`. A node's counterpart is the node at the
|
||||
/// same position when it has the same id, else the node in `before` with its id, else `None` (the
|
||||
/// node is new). A node that is the same node as the one at its position in `before` is skipped
|
||||
/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node.
|
||||
pub fn changed_nodes<'a>(before: &'a [Arc<Node>], after: &'a [Arc<Node>]) -> impl Iterator<Item = (usize, &'a Arc<Node>, Option<&'a Arc<Node>>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &'a Arc<Node>>> = None;
|
||||
after.iter().enumerate().filter_map(move |(i, a)| {
|
||||
if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1));
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
return None;
|
||||
}
|
||||
Some((i, a, b))
|
||||
})
|
||||
}
|
||||
@@ -947,3 +947,37 @@ fn try_walk_ends_at_the_break() {
|
||||
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
|
||||
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
|
||||
}
|
||||
|
||||
/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one
|
||||
/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are
|
||||
/// the same nodes in the same places are passed over by their pointers.
|
||||
#[test]
|
||||
fn changed_nodes_looks_up_only_the_nodes_that_changed() {
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let before: Vec<Arc<Node>> = (0..1000).map(leaf).collect();
|
||||
let mut after = before.clone();
|
||||
let mut edited = (*after[500]).clone();
|
||||
edited.name = Some("edited".into());
|
||||
after[500] = Arc::new(edited);
|
||||
after.push(leaf(5000));
|
||||
COUNTERPART_LOOKUPS.with(|c| c.set(0));
|
||||
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
|
||||
assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]);
|
||||
assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2);
|
||||
}
|
||||
|
||||
/// A node that moved to another place in the list is paired with itself by its id and left out
|
||||
/// when it is the same node; a changed node that moved is paired with its old node, and a node
|
||||
/// that is gone from the list gives nothing.
|
||||
#[test]
|
||||
fn changed_nodes_pairs_moved_nodes_by_id() {
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)];
|
||||
let mut edited = (*before[0]).clone();
|
||||
edited.locked = true;
|
||||
let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)];
|
||||
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
|
||||
assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]);
|
||||
assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list");
|
||||
assert_eq!(changed_nodes(&[], &after).count(), 3);
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two;
|
||||
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
|
||||
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
|
||||
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
|
||||
//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected
|
||||
//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the
|
||||
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
|
||||
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
|
||||
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
|
||||
@@ -89,6 +90,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
size
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.match",
|
||||
"Match Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
|
||||
has_multi,
|
||||
match_objects
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.groupOverlapping",
|
||||
"Group Overlapping Objects",
|
||||
@@ -177,6 +187,14 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
|
||||
})
|
||||
}
|
||||
|
||||
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
|
||||
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
|
||||
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let on = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, cmd)?;
|
||||
s.note_journal("scaleStrokes", json!(on));
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// The box of object `id` as `object.setBounds` measures it.
|
||||
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
|
||||
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
|
||||
@@ -277,7 +295,7 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.swap";
|
||||
let size = switch_or(p, "size", false, C)?;
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
|
||||
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
|
||||
@@ -290,7 +308,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.replace";
|
||||
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let keep = switch_or(p, "keep", false, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
|
||||
@@ -341,7 +359,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let proportional = switch_or(p, "proportional", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
|
||||
if let Some(w) = width {
|
||||
q["width"] = json!(w);
|
||||
@@ -359,6 +377,158 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": xfs.len() }))
|
||||
}
|
||||
|
||||
/// The source Match Objects matches `roots` (the selected roots, in stacking order) to, from its
|
||||
/// `source` param: the selected root that is the key object or holds it, the frontmost or the backmost.
|
||||
fn match_source(s: &Session, p: &Value, roots: &[NodeId], cmd: &str) -> Result<NodeId> {
|
||||
let st = s.doc()?;
|
||||
let key = st.selection.key.and_then(|k| st.doc.ancestry(k)).and_then(|up| roots.iter().copied().find(|id| up.contains(id)));
|
||||
let picked = match choice(p, cmd, "source", &["key", "top", "bottom"])? {
|
||||
Some("key") => Some(key.ok_or_else(|| bad(cmd, "no key object: set one with select.key"))?),
|
||||
Some("bottom") => roots.first().copied(),
|
||||
Some(_) => roots.last().copied(),
|
||||
None => key.or_else(|| roots.last().copied()),
|
||||
};
|
||||
picked.ok_or_else(|| bad(cmd, "select at least two objects"))
|
||||
}
|
||||
|
||||
/// Whether `targets` (in stacking order) are directly above `source` in its layer or group, in that order.
|
||||
fn stacked_above(d: &vectorcraft_doc::Document, source: NodeId, targets: &[NodeId]) -> bool {
|
||||
let paths = d.index_paths(targets.iter().copied().chain([source]));
|
||||
let Some((&at, up)) = paths.get(&source).and_then(|p| p.split_last()) else { return false };
|
||||
targets.iter().enumerate().all(|(i, id)| paths.get(id).and_then(|p| p.split_last()) == Some((&(at + 1 + i), up)))
|
||||
}
|
||||
|
||||
fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.match";
|
||||
let size = choice(p, C, "size", &["none", "width", "height", "both"])?.unwrap_or("none");
|
||||
let rotate = switch_or(p, "rotate", false, C)?;
|
||||
let stacking = switch_or(p, "stacking", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
|
||||
if size == "none" && !rotate && !stacking {
|
||||
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
|
||||
}
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let source = match_source(s, p, &roots, C)?;
|
||||
let targets: Vec<NodeId> = roots.iter().copied().filter(|id| *id != source).collect();
|
||||
if targets.is_empty() {
|
||||
return Err(bad(C, "select at least two objects"));
|
||||
}
|
||||
// Only sizing measures the source; a stacking or rotate match doesn't need its bounds.
|
||||
let (w, h) = if size == "none" {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
let sb = box_of(s, source)?;
|
||||
(sb.rect.width(), sb.rect.height())
|
||||
};
|
||||
let wanted = match size {
|
||||
"width" if w < LEAST => return Err(bad(C, "the source object has no width")),
|
||||
"height" if h < LEAST => return Err(bad(C, "the source object has no height")),
|
||||
"both" if w < LEAST || h < LEAST => return Err(bad(C, "the source object has no width or no height")),
|
||||
"width" => Some(json!({ "width": w, "proportional": true })),
|
||||
"height" => Some(json!({ "height": h, "proportional": true })),
|
||||
"both" => Some(json!({ "width": w, "height": h })),
|
||||
_ => None,
|
||||
};
|
||||
let angle = s.doc()?.doc.bbox_angle(&[source]);
|
||||
let mut xfs = Vec::with_capacity(targets.len());
|
||||
for &id in &targets {
|
||||
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
|
||||
let Some(b) = s.transform_box(&[id]) else {
|
||||
if wanted.is_some() {
|
||||
return Err(bad(C, format!("object {} has no bounds to size", id.0)));
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
return Err(bad(C, format!("object {} has no bounds to rotate", id.0)));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let mut xf = Affine::IDENTITY;
|
||||
if let Some(q) = &wanted {
|
||||
let mut q = q.clone();
|
||||
q["reference"] = json!(reference);
|
||||
q["strokes"] = json!(strokes);
|
||||
xf = object_bounds_transform(s, &q, id)?;
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
// Rotation uses the reference point that sizing keeps in place.
|
||||
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
|
||||
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
|
||||
}
|
||||
if wanted.is_some() {
|
||||
let sc = scaling(s, &json!({ "strokes": strokes }));
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let measure = |xf| {
|
||||
d.node(id).and_then(|n| {
|
||||
let mut n = n.clone();
|
||||
transform_node(&mut n, xf, sc, true);
|
||||
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
|
||||
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
|
||||
})
|
||||
};
|
||||
let misses = |measured: Option<Rect>| {
|
||||
measured.is_none_or(|r| match size {
|
||||
"width" => (r.width() - w).abs() > 1e-6,
|
||||
"height" => (r.height() - h).abs() > 1e-6,
|
||||
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
|
||||
})
|
||||
};
|
||||
// The sized and turned object, measured in its final frame, must have the size asked for.
|
||||
if misses(measure(xf)) {
|
||||
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
|
||||
}
|
||||
}
|
||||
xfs.push((id, xf));
|
||||
}
|
||||
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
|
||||
xfs.retain(|(_, xf)| !still(xf));
|
||||
let restack = stacking && !stacked_above(&s.doc()?.doc, source, &targets);
|
||||
let (mut placed, mut left) = (vec![], vec![]);
|
||||
if restack {
|
||||
let d = &s.doc()?.doc;
|
||||
// In a clip group or a clipping layer the bottom child is the clipping path: it stays there.
|
||||
let is_clip =
|
||||
|id: &NodeId| d.position(*id).is_some_and(|(_, idx, _)| idx == 0) && d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(Node::clips);
|
||||
if targets.iter().any(is_clip) {
|
||||
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
|
||||
}
|
||||
let parent = d.parent_of(source);
|
||||
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
placed = targets.iter().map(|i| (*i, d.parent_of(*i))).collect::<Vec<(NodeId, Option<NodeId>)>>();
|
||||
left = crate::cmd::intertwine::groups_of(d, &targets);
|
||||
}
|
||||
let count = json!({ "source": source.0, "count": targets.len() });
|
||||
if xfs.is_empty() && !restack {
|
||||
return Ok(count);
|
||||
}
|
||||
let q = json!({ "strokes": strokes, "patterns": patterns });
|
||||
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
|
||||
let mut sc = scaling(s, &q);
|
||||
sc.patterns = transform_patterns(s, &q, &ids)?;
|
||||
s.edit("Match Objects", |d, _| {
|
||||
for (id, xf) in &xfs {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
transform_node(n, *xf, sc, true);
|
||||
}
|
||||
}
|
||||
if restack {
|
||||
let moved = d.remove_many(&targets)?;
|
||||
d.insert_beside(vec![(source, moved.into_iter().map(Arc::unwrap_or_clone).collect())], false)?;
|
||||
// Targets moved out of an Intertwine group leave it as ordinary art.
|
||||
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
|
||||
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
|
||||
/// open where each one starts are compared with it.
|
||||
@@ -505,7 +675,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending");
|
||||
let distribute = switch_or(p, "distribute", false, C)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
|
||||
@@ -343,6 +343,394 @@ fn size_gives_each_object_a_width_and_height() {
|
||||
assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Three rectangles from the back, all selected: `a` 20 × 10 at the origin, `b` 40 × 40 at
|
||||
/// (100, 100) and `c` 10 × 30 at (200, 0).
|
||||
fn three(s: &mut Session) -> (NodeId, NodeId, NodeId) {
|
||||
let a = rect(s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(s, 100.0, 100.0, 40.0, 40.0);
|
||||
let c = rect(s, 200.0, 0.0, 10.0, 30.0);
|
||||
select(s, &[a, b, c]);
|
||||
(a, b, c)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_gives_the_others_the_key_objects_size() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r, json!({"source": b.0, "count": 2}));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
// About each center; the key object stays.
|
||||
assert!(near(bounds(&s, a), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (185.0, -5.0, 40.0, 40.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 20.0, 10.0)));
|
||||
// The width, with the height in proportion, about the top-left corner.
|
||||
s.execute("addon.arrange.match", &json!({"size": "width", "reference": 0})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 40.0, 120.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "height", "reference": 8})).unwrap();
|
||||
assert!(near(bounds(&s, a), (-60.0, -30.0, 80.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
// No key object: the frontmost, c.
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
assert!(near(bounds(&s, a), (5.0, -10.0, 10.0, 30.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (115.0, 105.0, 10.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "bottom", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(a.0));
|
||||
assert!(near(bounds(&s, b), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (195.0, 10.0, 20.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// "top" names the frontmost even while a key object is set.
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "top", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_to_the_sources_angle() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "size": "both"})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
for (id, center) in [(a, (10.0, 5.0)), (c, (205.0, 15.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
assert!((o.rect.width() - 40.0).abs() < 1e-6 && (o.rect.height() - 40.0).abs() < 1e-6, "{id:?} sized {:?}", o.rect);
|
||||
let at = o.center();
|
||||
assert!((at.x - center.0).abs() < 1e-6 && (at.y - center.1).abs() < 1e-6, "{id:?} turned about its center: {at:?}");
|
||||
}
|
||||
// Turned back to the angle of an unturned source.
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, d]);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "source": "top"})).unwrap();
|
||||
assert!(s.transform_box(&[a]).unwrap().angle.abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
|
||||
for size in ["width", "height", "both"] {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[target]);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let source = rect(&mut s, 100.0, 0.0, 10.5, 10.5);
|
||||
select(&mut s, &[source]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let wanted = s.transform_box(&[source]).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": size, "rotate": true})).unwrap();
|
||||
assert_eq!(r, json!({"source": source.0, "count": 1}));
|
||||
let measured = s.transform_box(&[target]).unwrap();
|
||||
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
|
||||
for angle in [0, 30] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.rotate", &json!({"angle": angle})).unwrap();
|
||||
select(&mut s, &[b]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[target]).is_none());
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert!((s.doc().unwrap().doc.bbox_angle(&[source]) - f64::from(angle)).abs() < 1e-6);
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let result = s.execute("addon.arrange.match", &json!({"rotate": true}));
|
||||
if angle == 0 {
|
||||
assert_eq!(result.unwrap(), json!({"source": source.0, "count": 1}));
|
||||
} else {
|
||||
let error = result.unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("object {} has no bounds to rotate", target.0)), "{error}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_puts_the_others_directly_above_the_source() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[d, a, c]);
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(layer_order(&s), [a, c, d, b], "in the order they had, above the key object");
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 10.0, 30.0)), "nothing else changes");
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "already above it: no step");
|
||||
// An object in another layer goes into the source's.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let e = rect(&mut s, 0.0, 200.0, 10.0, 10.0);
|
||||
select(&mut s, &[b, e]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b, e]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_makes_no_step_when_everything_matches() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 100.0, 20.0, 10.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true})).unwrap();
|
||||
assert_eq!(r["count"], json!(1));
|
||||
assert_eq!(steps(&s), n, "the same size and angle: no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_about_their_reference_point() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "reference": 0})).unwrap();
|
||||
// Each top-left corner stays where it was.
|
||||
for (id, corner) in [(a, (0.0, 0.0)), (c, (200.0, 0.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
let at = o.to_doc() * vectorcraft_geom::reference_point(o.rect, 0);
|
||||
assert!((at.x - corner.0).abs() < 1e-6 && (at.y - corner.1).abs() < 1e-6, "{id:?} turned about its top-left corner: {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_scales_strokes_as_asked() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(weight(&s, a), 2.0, "off by default (the preference)");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": true})).unwrap();
|
||||
assert!((weight(&s, a) - 4.0).abs() < 1e-9, "{}", weight(&s, a));
|
||||
assert!(near(bounds(&s, a), (-5.0, -5.0, 20.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Running `cmd` with Scale Strokes & Effects on doubles the 2 pt stroke of a 10 pt square, and
|
||||
/// replaying its journal entry after the preference is turned off scales the stroke the same way.
|
||||
fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": true})).unwrap();
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", weight(&s));
|
||||
let (id, q) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(id, cmd);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": false})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
s.replay(&id, &q).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_leaves_a_clipping_path_in_place() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let mask = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
|
||||
select(&mut s, &[art, mask]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let x = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[mask, x]);
|
||||
s.execute("select.key", &json!({"id": x.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"stacking": true})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_refuses_a_target_with_no_width() {
|
||||
let mut s = session();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "width"}), json!({"size": "both"})]);
|
||||
// Its height can still take the source's.
|
||||
s.execute("addon.arrange.match", &json!({"size": "height"})).unwrap();
|
||||
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[line]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2, "cap": "butt"})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 2.0, 100.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})).unwrap();
|
||||
let measured = s.transform_box(&[line]).unwrap().rect;
|
||||
let wanted = s.transform_box(&[b]).unwrap().rect;
|
||||
assert!((measured.width() - wanted.width()).abs() < 1e-6, "{measured:?}");
|
||||
assert!((measured.height() - wanted.height()).abs() < 1e-6, "{measured:?}");
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.setBounds", &json!({"width": 4})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_takes_a_member_out_of_its_intertwine_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let g = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.intertwine.arrange", &json!({"at": [30, 30], "order": "front", "member": a.0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().extras().intertwine.is_some(), "a is drawn over b in their overlap");
|
||||
let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, c]);
|
||||
s.execute("select.key", &json!({"id": c.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.parent_of(a), Some(g), "a left the Intertwine group");
|
||||
let e = d.node(a).unwrap().extras();
|
||||
assert!(e.intertwine.is_none() && e.intertwine_tiers.is_empty(), "a keeps no Intertwine areas");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "undo puts a back in its group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_needs_no_bounds_on_the_source() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
select(&mut s, &[b, g]);
|
||||
s.execute("select.key", &json!({"id": g.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [g, b], "b goes directly above the empty group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[source, b]);
|
||||
let parent = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(source), Some(parent));
|
||||
let c = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
|
||||
let d = rect(&mut s, 120.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[c, d]);
|
||||
let target = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[source, target]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let error = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err().to_string();
|
||||
assert!(error.contains("can't be intertwined"), "{error}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_size_of_each_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let (a, _, _) = three(&mut s);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.match",
|
||||
&[
|
||||
json!({}),
|
||||
json!({"size": "none"}),
|
||||
json!({"size": "area"}),
|
||||
json!({"size": 1}),
|
||||
json!({"rotate": 1}),
|
||||
json!({"stacking": "yes"}),
|
||||
json!({"size": "both", "reference": 9}),
|
||||
json!({"size": "both", "reference": 1.5}),
|
||||
json!({"size": "both", "source": "left"}),
|
||||
json!({"size": "both", "scaleStrokes": "no"}),
|
||||
json!({"size": "both", "patterns": 0}),
|
||||
],
|
||||
);
|
||||
let e = s.execute("addon.arrange.match", &json!({"source": "key", "rotate": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("no key object"), "{e}");
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.match"), "one object selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused() {
|
||||
let mut s = session();
|
||||
@@ -389,6 +777,7 @@ fn off_without_a_selection() {
|
||||
"addon.arrange.swap",
|
||||
"addon.arrange.replace",
|
||||
"addon.arrange.size",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.sort",
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
|
||||
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
|
||||
@@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
|
||||
}
|
||||
let Some(children) = n.children() else { return false };
|
||||
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
children.iter().enumerate().any(|(i, c)| {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
};
|
||||
stale_in(doc, c, b)
|
||||
})
|
||||
changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b))
|
||||
}
|
||||
|
||||
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
|
||||
|
||||
@@ -39,6 +39,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
doc_move
|
||||
),
|
||||
cmd!(
|
||||
"document.setSaved",
|
||||
"Set Saved State",
|
||||
[],
|
||||
None,
|
||||
"{index?: the document (default: the current one), saved: true or false} records the document as saved (true: Close asks nothing until the next edit) or as having unsaved changes (false), without saving it or adding an undo step; a document already in that state is left as it is",
|
||||
has_doc,
|
||||
doc_set_saved
|
||||
),
|
||||
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → path (the document's file; null when automation read roots are in force and the file is outside them), layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
|
||||
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
|
||||
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
|
||||
@@ -257,6 +266,26 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
|
||||
}
|
||||
|
||||
fn doc_set_saved(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.setSaved";
|
||||
let i = opt_u64(p, C, "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?;
|
||||
let saved = match p.get("saved") {
|
||||
None | Some(Value::Null) => return Err(bad(C, "missing `saved`: true or false")),
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(_) => return Err(bad(C, "`saved` must be true or false")),
|
||||
};
|
||||
let uid = s.documents().get(i).map(|d| d.uid).ok_or_else(|| bad(C, "no such document"))?;
|
||||
let st = s.document_mut(uid).ok_or_else(|| bad(C, "no such document"))?;
|
||||
if st.is_dirty() == saved {
|
||||
if saved {
|
||||
st.mark_saved();
|
||||
} else {
|
||||
st.mark_unsaved();
|
||||
}
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n = s.documents().len();
|
||||
let from = match p.get("from") {
|
||||
|
||||
@@ -125,6 +125,13 @@ pub use screens::{
|
||||
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list,
|
||||
preset_rows as screen_preset_rows,
|
||||
};
|
||||
pub(crate) use svg::{lost_artboards_warning as svg_lost_artboards_warning, preserves_editing as svg_preserves_editing};
|
||||
|
||||
/// Does a save in `format` (a format id) with options `p` write a legacy version 7 `.ai` file,
|
||||
/// which holds the artboards its own options pick? An unknown version counts as one.
|
||||
pub(crate) fn saves_legacy_ai(format: &str, p: &serde_json::Value) -> bool {
|
||||
format == "ai" && formats::format(format).is_none_or(|f| legacy_ai::wanted("file.saveAs", f, p).unwrap_or(true))
|
||||
}
|
||||
pub use svg::options_map as svg_options;
|
||||
/// Atomic file writes (a temporary file renamed over the target: a failed write never damages the
|
||||
/// file it replaces), for the apps' own writers too.
|
||||
@@ -141,7 +148,9 @@ mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
|
||||
pub(crate) use access::{READ_TOO_LARGE, check_images_in, check_scripts_of, with_read_limit, with_readable_settings_folder};
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
|
||||
@@ -267,14 +267,76 @@ pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)
|
||||
}
|
||||
|
||||
/// The most a file read during a script command holds, the limit an importer reads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES;
|
||||
/// The error of a file past [`SCRIPT_OPEN_MAX_BYTES`].
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn regular_write_target(path: &str) -> Result<()> {
|
||||
if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static READ_LIMIT: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
pub(crate) const READ_TOO_LARGE: &str = "File exceeds scoped read limit";
|
||||
|
||||
pub(crate) fn with_read_limit<T>(max: usize, f: impl FnOnce() -> T) -> T {
|
||||
struct Restore(Option<usize>);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
READ_LIMIT.with(|limit| limit.set(self.0));
|
||||
}
|
||||
}
|
||||
let _restore = Restore(READ_LIMIT.with(|limit| limit.replace(Some(limit.get().map_or(max, |outer| outer.min(max))))));
|
||||
f()
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
may_read(path)?;
|
||||
// A device or pipe may never end: only a regular file is read to its end.
|
||||
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
// A script command reads at most `SCRIPT_OPEN_MAX_BYTES`, and a scoped limit
|
||||
// (`with_read_limit`) at most its own count, whichever is smaller.
|
||||
let script = crate::file_access::in_script_command().then_some(SCRIPT_OPEN_MAX_BYTES);
|
||||
let scoped = READ_LIMIT.with(std::cell::Cell::get);
|
||||
let Some(cap) = [script, scoped].into_iter().flatten().min() else {
|
||||
return std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")));
|
||||
};
|
||||
let too_large = |bytes: u64| {
|
||||
if script.is_some_and(|max| bytes > max as u64) {
|
||||
Some(EngineError::Other(format!("{path}: {SCRIPT_OPEN_TOO_LARGE}")))
|
||||
} else if scoped.is_some_and(|max| bytes > max as u64) {
|
||||
Some(EngineError::Other(READ_TOO_LARGE.into()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let file = std::fs::File::open(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let meta = file.metadata().map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
if !meta.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
if let Some(e) = too_large(meta.len()) {
|
||||
return Err(e);
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(cap as u64 + 1).read_to_end(&mut bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
match too_large(bytes.len() as u64) {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first `max` bytes of the file at `path` (all of it when it is shorter). Anything but a
|
||||
@@ -680,6 +742,28 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
#[test]
|
||||
fn scoped_read_limit_bounds_reads_and_restores_the_previous_limit() {
|
||||
let path = std::env::temp_dir().join(format!("vc-access-read-limit-{}", std::process::id()));
|
||||
std::fs::write(&path, b"12345").unwrap();
|
||||
let path_text = path.to_str().unwrap();
|
||||
assert_eq!(read_file(path_text).unwrap(), b"12345");
|
||||
with_read_limit(5, || {
|
||||
assert_eq!(read_file(path_text).unwrap(), b"12345");
|
||||
with_read_limit(4, || {
|
||||
assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE);
|
||||
with_read_limit(6, || assert!(read_file(path_text).is_err()));
|
||||
});
|
||||
assert_eq!(read_file(path_text).unwrap(), b"12345");
|
||||
std::fs::write(&path, b"123456").unwrap();
|
||||
assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE);
|
||||
});
|
||||
assert_eq!(read_file(path_text).unwrap(), b"123456");
|
||||
let _ = std::panic::catch_unwind(|| with_read_limit(0, || panic!("test unwind")));
|
||||
assert_eq!(read_file(path_text).unwrap(), b"123456");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
/// An error about a path the client did not give, under roots that don't let it be read: the
|
||||
/// path is named by its file name (after a `/` or a `\`), or as [`UNNAMED`] when it ends in no
|
||||
/// name or its name is not valid text, and every root and the reason stay whole. A path inside the
|
||||
|
||||
@@ -88,7 +88,9 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
if files.len() > 1 {
|
||||
for (p, _) in &files {
|
||||
super::may_write(p)?;
|
||||
super::access::regular_write_target(p)?;
|
||||
}
|
||||
distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?;
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
write_file(p, bytes)?;
|
||||
@@ -108,6 +110,18 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
Ok(merge(out, extra))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator<Item = &'a str>) -> Result<()> {
|
||||
let mut targets = std::collections::HashSet::new();
|
||||
for path in paths {
|
||||
let real = crate::file_access::resolve(path).map_err(EngineError::Other)?;
|
||||
if !targets.insert(real) {
|
||||
return Err(EngineError::Other("output destinations resolve to the same file".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `a` with the fields of `b`.
|
||||
pub(crate) fn merge(mut a: Value, b: Value) -> Value {
|
||||
if let (Some(a), Value::Object(b)) = (a.as_object_mut(), b) {
|
||||
|
||||
@@ -818,7 +818,7 @@ pub fn read_for_open_asking(
|
||||
(linked_pages(name, bytes, path.as_deref(), &opts)?, None)
|
||||
} else {
|
||||
match super::importer::pick(name, bytes, p)? {
|
||||
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None),
|
||||
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, opts.color_mode),
|
||||
// The color mode `p` asks for converts the colors after the policies did, through the
|
||||
// profiles the document keeps.
|
||||
None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode),
|
||||
@@ -1096,6 +1096,21 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
source(p, "document.open")?
|
||||
}
|
||||
};
|
||||
let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
|
||||
let (options, aliases) = (given(&["page", "cropTo"]), given(&["pages", "crop"]));
|
||||
if crate::file_access::in_script_command() && (options || aliases) {
|
||||
// An importer plug-in receives only the params, so it cannot apply the pages or the crop
|
||||
// box; `linkPages` reads the file with the built-in reader before any importer.
|
||||
let link_pages = p.get("linkPages").and_then(Value::as_bool) == Some(true);
|
||||
let built_in = link_pages || super::importer::pick(src.name, &src.bytes, p)?.is_none();
|
||||
let pdf = built_in
|
||||
&& (!options
|
||||
|| (detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait"))
|
||||
&& !vectorcraft_pdf::is_postscript(&src.bytes)));
|
||||
if !pdf {
|
||||
return Err(bad("document.open", "PDF open options require a PDF file"));
|
||||
}
|
||||
}
|
||||
// A relative path is the file in the working directory: its folder is where relative links
|
||||
// are found (a bare file name has no folder of its own).
|
||||
let path = src.path.map(super::absolute_path);
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct LoadOptions {
|
||||
pub pages: Option<String>,
|
||||
/// The box each page's artboard (or placed frame) gets.
|
||||
pub crop: CropTo,
|
||||
/// Whether the options explicitly request the crop box.
|
||||
pub explicit_crop_box: bool,
|
||||
/// The password of an encrypted PDF.
|
||||
pub password: Option<String>,
|
||||
/// The colour mode the document opens in, its colours converted as Document Color Mode does
|
||||
@@ -67,6 +69,7 @@ impl Default for LoadOptions {
|
||||
Self {
|
||||
pages: None,
|
||||
crop: CropTo::default(),
|
||||
explicit_crop_box: false,
|
||||
password: None,
|
||||
color_mode: None,
|
||||
grays: Grays::default(),
|
||||
@@ -147,6 +150,7 @@ impl LoadOptions {
|
||||
Ok(Self {
|
||||
pages,
|
||||
crop,
|
||||
explicit_crop_box: crop == CropTo::Crop && crop_to.or(crop_alias).is_some(),
|
||||
password,
|
||||
color_mode,
|
||||
grays,
|
||||
@@ -173,14 +177,14 @@ impl LoadOptions {
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
|
||||
/// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes,
|
||||
/// its editor's artboards, with the bleed round them (its crop box takes the bleed in).
|
||||
/// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default,
|
||||
/// with the bleed around them. An explicit crop-box request uses its crop box.
|
||||
fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result<ImportOptions> {
|
||||
let pages = match &self.pages {
|
||||
None => None,
|
||||
Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?),
|
||||
};
|
||||
let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data();
|
||||
let is_ai = !self.explicit_crop_box && self.crop == CropTo::Crop && opened.has_illustrator_data();
|
||||
Ok(ImportOptions {
|
||||
pages,
|
||||
crop: if is_ai { CropTo::Trim } else { self.crop },
|
||||
|
||||
@@ -85,6 +85,7 @@ pub struct SavePlan {
|
||||
/// Where to write. `None` when no path is known (never saved, converted from an older version,
|
||||
/// restored by Data Recovery, or a format other than the document's own): the caller asks for one or takes the bytes.
|
||||
pub path: Option<String>,
|
||||
pub path_given: bool,
|
||||
pub format: &'static Format,
|
||||
/// The format's options (only those its encoder reads).
|
||||
pub options: Map<String, Value>,
|
||||
@@ -348,7 +349,8 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
}
|
||||
}
|
||||
let lossy_source = super::lossy_source(st, p);
|
||||
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source, kept })
|
||||
let path_given = str_param(p, "path").is_some_and(|g| !g.is_empty());
|
||||
Ok(SavePlan { mode, path, path_given, format, options, name, folder, modified, notes, lossy_source, kept })
|
||||
}
|
||||
|
||||
/// The native save options, which a save also takes beside the path.
|
||||
@@ -602,6 +604,7 @@ pub struct SaveJob {
|
||||
stamped: Option<i64>,
|
||||
/// The artboards also saved to files of their own (`separateArtboards`).
|
||||
boards: Vec<usize>,
|
||||
redact_paths: bool,
|
||||
}
|
||||
|
||||
/// Writes the file at a path with what the filler it is given writes into it
|
||||
@@ -963,7 +966,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
};
|
||||
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
|
||||
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards, redact_paths: false })
|
||||
}
|
||||
|
||||
impl SaveJob {
|
||||
@@ -1070,14 +1073,20 @@ impl SaveJob {
|
||||
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
|
||||
return Ok(stopped);
|
||||
}
|
||||
// Every path is checked against the file access in force before the first file is
|
||||
// written. A refused file goes to `write` first, which refuses it with the error the
|
||||
// caller gives (naming the path as the caller does), so none of the files is written.
|
||||
// Every path is checked against the file access in force, and as a write target, before
|
||||
// the first file is written. A refused file is not handed to `write`, so a writer that does
|
||||
// not check the file access writes none of the files; the error is the file access's own
|
||||
// refusal, as the writers that check it give.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1
|
||||
&& let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err())
|
||||
{
|
||||
write(p, bytes)?;
|
||||
if files.len() > 1 {
|
||||
let named = |e, p: &str| if self.redact_paths { super::access::naming_in_error(e, p) } else { e };
|
||||
for (p, _) in &files {
|
||||
super::may_write(p).map_err(|e| named(e, p))?;
|
||||
}
|
||||
for (p, _) in &files {
|
||||
super::access::regular_write_target(p).map_err(|e| named(e, p))?;
|
||||
}
|
||||
super::export_names::distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?;
|
||||
}
|
||||
for (i, (p, bytes)) in files.iter().enumerate() {
|
||||
if i == 0 {
|
||||
@@ -1239,9 +1248,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8])
|
||||
/// A save command: plan, then write with the file system (a native file as it is encoded).
|
||||
pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> {
|
||||
let plan = save_plan(s, mode, p)?;
|
||||
let job = save_job(s, plan)?;
|
||||
let mut job = save_job(s, plan)?;
|
||||
let uid = s.doc()?.uid;
|
||||
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
|
||||
let given = job.plan.path_given;
|
||||
job.redact_paths = !given;
|
||||
// Without a path, the files written are the document's own file and those beside it.
|
||||
let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
|
||||
super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })
|
||||
@@ -1383,7 +1393,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; an access-rule, file-type or destination-collision failure found before writing leaves every file unchanged; a later write failure can leave earlier files written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-U
Line truncated
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -172,14 +172,19 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Docu
|
||||
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
|
||||
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
|
||||
/// Editing Capabilities).
|
||||
pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
|
||||
pub(crate) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
|
||||
let n = doc.artboards.len();
|
||||
let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing);
|
||||
(n > 1 && !preserved).then(|| {
|
||||
(n > 1 && !preserves_editing(doc, p)).then(|| {
|
||||
format!("{label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all.")
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a save of `doc` as SVG with options `p` (flat or nested in `svg`) embeds the native
|
||||
/// document (Preserve Editing Capabilities), which keeps every artboard.
|
||||
pub(crate) fn preserves_editing(doc: &Document, p: &Value) -> bool {
|
||||
plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing)
|
||||
}
|
||||
|
||||
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
|
||||
/// outside the read roots of the request being served (the open document keeps it).
|
||||
fn native_attachment(doc: &Document) -> Vec<u8> {
|
||||
|
||||
@@ -114,7 +114,17 @@ pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
|
||||
/// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this
|
||||
/// computer's when `None`).
|
||||
pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value {
|
||||
let fonts: Vec<Value> = missing_fonts(&st.doc)
|
||||
let fonts = missing_font_rows(&st.doc);
|
||||
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
|
||||
if let Some(dir) = fonts_next_to_document(st, rules) {
|
||||
out["fontsNextToDocument"] = json!(dir);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `text.missingFonts`'s `fonts` rows for `d` ([`missing_fonts`]).
|
||||
pub fn missing_font_rows(d: &Document) -> Vec<Value> {
|
||||
missing_fonts(d)
|
||||
.into_iter()
|
||||
.map(|m| {
|
||||
json!({
|
||||
@@ -122,26 +132,26 @@ pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Valu
|
||||
"resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `text.missingFonts`'s `fontsNextToDocument` for the open document `st`, where searches go by
|
||||
/// `rules` (this computer's when `None`).
|
||||
pub fn fonts_next_to_document(st: &DocState, rules: Option<&findfiles::Rules>) -> Option<String> {
|
||||
// File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder
|
||||
// is made absolute against the working folder when the document's path is relative. It is
|
||||
// offered when a search may start there, as far as the rules tell without listing a folder.
|
||||
if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) {
|
||||
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
|
||||
let system;
|
||||
let rules = match rules {
|
||||
Some(rules) => rules,
|
||||
None => {
|
||||
system = findfiles::Rules::system();
|
||||
&system
|
||||
}
|
||||
};
|
||||
if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) {
|
||||
out["fontsNextToDocument"] = json!(dir);
|
||||
let dir = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir())?;
|
||||
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
|
||||
let system;
|
||||
let rules = match rules {
|
||||
Some(rules) => rules,
|
||||
None => {
|
||||
system = findfiles::Rules::system();
|
||||
&system
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()).then_some(dir)
|
||||
}
|
||||
|
||||
fn missing(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes};
|
||||
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json,
|
||||
@@ -226,15 +226,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
|
||||
/// mask art holds such instances (`masked`).
|
||||
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
|
||||
masked.push(a.id);
|
||||
}
|
||||
@@ -423,15 +415,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
/// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the
|
||||
/// walk stops: [`keep_pixel_aligned`] visits what it holds.
|
||||
fn changed_aligned(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<std::collections::HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) {
|
||||
out.push(a.id);
|
||||
} else if let Some(children) = a.children() {
|
||||
|
||||
@@ -25,12 +25,12 @@
|
||||
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
|
||||
//! the objects that move up the path after it; Expand).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
@@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool {
|
||||
/// The Objects on Path groups among `after` and inside them that are not the same nodes as before
|
||||
/// (`before`: the same list before the edit), outer ones first.
|
||||
fn changed_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if is_objects_on_path(a) {
|
||||
out.push(a.id);
|
||||
}
|
||||
|
||||
@@ -1231,12 +1231,24 @@ fn queue(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------- queries ----------
|
||||
|
||||
/// The colour mode an image file stores its pixels in.
|
||||
fn color_mode(bytes: &[u8]) -> &'static str {
|
||||
match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
|
||||
Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale",
|
||||
Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK",
|
||||
_ => "RGB",
|
||||
/// The colour mode an image file stores its pixels in. A PNG, JPEG, TIFF, PSD, GIF or BMP file's
|
||||
/// header says it and a WebP file is always RGB, so their pixels are not decoded; the Control bar
|
||||
/// and the Properties panel ask `image.info` again after every change, each step of a drag
|
||||
/// included. A file in another format is decoded.
|
||||
pub(crate) fn color_mode(bytes: &[u8]) -> &'static str {
|
||||
use craft_image_codecs::{ChannelLayout as L, RasterColorType as T};
|
||||
match craft_image_codecs::inspect_raster(bytes) {
|
||||
Ok(Some(i)) => match i.color_type {
|
||||
T::Bitmap | T::Gray | T::GrayAlpha => "Grayscale",
|
||||
T::Cmyk | T::CmykAlpha => "CMYK",
|
||||
_ => "RGB",
|
||||
},
|
||||
_ if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::WebP) => "RGB",
|
||||
_ => match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
|
||||
Some(L::Gray | L::GrayA) => "Grayscale",
|
||||
Some(L::Cmyk | L::CmykA) => "CMYK",
|
||||
_ => "RGB",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.arrange.grid",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.offset",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.replace",
|
||||
|
||||
@@ -1185,6 +1185,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
|
||||
let plan = SavePlan {
|
||||
mode: SaveMode::Copy,
|
||||
path: st.path.clone(),
|
||||
path_given: false,
|
||||
format: native,
|
||||
options: serde_json::Map::from_iter([("pdfCompatible".into(), json!(false))]),
|
||||
name: format!("{file}{DOC_EXT}"),
|
||||
|
||||
@@ -6,12 +6,9 @@ use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::Arc,
|
||||
};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_tools::builder::{self as b, BuilderMap};
|
||||
@@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc<Node>], spec: &ShaperSpec, map: &Build
|
||||
}
|
||||
|
||||
fn changed_shaper_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().shaper.is_some() {
|
||||
out.push(a.id);
|
||||
}
|
||||
|
||||
@@ -501,7 +501,7 @@ pub(crate) fn finish_recording_writes(succeeded: bool) -> Vec<String> {
|
||||
|
||||
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
|
||||
/// existing folder's links followed and the rest appended.
|
||||
fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
pub(crate) fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
if path.is_empty() {
|
||||
return Err("automation path rejected: path is empty".into());
|
||||
}
|
||||
@@ -1211,14 +1211,17 @@ mod tests {
|
||||
};
|
||||
let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg")));
|
||||
let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok()));
|
||||
// The open document's file is the only grant: no folder scope covers it.
|
||||
let documents = ScriptGate { write: ScriptScope::default(), documents: vec![kept.clone()], ..gate.clone() };
|
||||
let document_write = || with_script_gate(documents.clone(), || check_write(&kept).is_ok());
|
||||
assert_eq!(check(&kept), (true, true));
|
||||
assert!(document_write(), "an open document's file is written");
|
||||
let mut perms = std::fs::metadata(&out).unwrap().permissions();
|
||||
perms.set_readonly(true);
|
||||
std::fs::set_permissions(&out, perms.clone()).unwrap();
|
||||
assert_eq!(check(&kept), (false, true), "a read-only file is read but not written");
|
||||
assert!(check(&fresh).0, "a new file next to it is written");
|
||||
let documents = ScriptGate { documents: vec![kept.clone()], ..gate.clone() };
|
||||
assert!(!with_script_gate(documents, || check_write(&kept).is_ok()), "also when it is an open document's file");
|
||||
assert!(!document_write(), "also when it is an open document's file");
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(&out, perms).unwrap();
|
||||
|
||||
@@ -94,10 +94,16 @@ use vectorcraft_js::{
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod print;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
mod variables;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use print::postscript_name;
|
||||
#[cfg(test)]
|
||||
pub(crate) use save_open::with_extension;
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
|
||||
/// What [`after_command`] compares with, taken before each command a script runs
|
||||
@@ -114,8 +120,6 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
|
||||
mod colors;
|
||||
mod defaults;
|
||||
mod paths;
|
||||
mod print;
|
||||
mod save_open;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
@@ -2934,8 +2938,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document
|
||||
.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "close"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
document.extend(save_open::document_members(l));
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
//! - A property the help pages list that is not mapped accepts the default its help page gives
|
||||
//! and throws an error that says it is not available yet at any other value.
|
||||
//! - `fitToPage` set to true wins over the scale factors and the tiling mode.
|
||||
//! With no scale or tiling assigned, false clears a base fit mode and preserves other base scaling modes.
|
||||
//! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range
|
||||
//! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange`
|
||||
//! replaces the range of the settings `print` starts from, which prints when those settings
|
||||
@@ -65,8 +66,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, Membe
|
||||
|
||||
use super::save_open::{exactly, file_path, plain, refused};
|
||||
use super::{
|
||||
Answer, Described, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, arg, command, current, float, get, given, later, method, named, num, on_doc,
|
||||
returns, text, this_doc, typed, whole, with_doc,
|
||||
Answer, Described, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, arg, class, command, current, float, get, given, later, method, named, num,
|
||||
on_doc, returns, text, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::cmd::flatten::FlattenOptions;
|
||||
|
||||
@@ -116,8 +117,8 @@ const PDF_OVERPRINT: &[&str] = &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"];
|
||||
const POSTSCRIPT_IMAGE_COMPRESSION: &[&str] = &["IMAGECOMPRESSIONNONE", "JPEG", "RLE"];
|
||||
const POSTSCRIPT_LEVEL: &[&str] = &["PSLEVEL1", "PSLEVEL2", "PSLEVEL3"];
|
||||
|
||||
/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` comes from
|
||||
/// [`super::save_open::ENUMS`].
|
||||
/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` and `PageMarksTypes`
|
||||
/// come from [`super::save_open::ENUMS`].
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("PrintColorProfile", PRINT_COLOR_PROFILE),
|
||||
("PrintColorIntent", PRINT_COLOR_INTENT),
|
||||
@@ -129,7 +130,6 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("PrintingBounds", PRINTING_BOUNDS),
|
||||
("PrintFontDownloadMode", PRINT_FONT_DOWNLOAD_MODE),
|
||||
("FontSubstitutionPolicy", FONT_SUBSTITUTION_POLICY),
|
||||
("PageMarksTypes", PAGE_MARKS_TYPES),
|
||||
("PostScriptImageCompressionType", POSTSCRIPT_IMAGE_COMPRESSION),
|
||||
("PrinterPostScriptLevelEnum", POSTSCRIPT_LEVEL),
|
||||
];
|
||||
@@ -151,6 +151,20 @@ enum Kind {
|
||||
File,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
/// What `reflect` tells of a property that takes this.
|
||||
fn info(self) -> MemberInfo {
|
||||
match self {
|
||||
Kind::Bool => typed("boolean"),
|
||||
Kind::Number(min, max) => MemberInfo { min: Some(min), max: Some(max), ..typed("number") },
|
||||
Kind::Whole(min, max) => MemberInfo { min: Some(min as f64), max: Some(max as f64), ..typed("number") },
|
||||
Kind::Text => typed("string"),
|
||||
Kind::Choice(name, ..) | Kind::Child(name) => typed(name),
|
||||
Kind::File => typed("File"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The default a property reads as before it is assigned.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Start {
|
||||
@@ -275,11 +289,11 @@ const COORDINATE: Class = Class {
|
||||
fields: &[
|
||||
f("emulsion", Kind::Bool, Start::Bool(false)),
|
||||
f("fitToPage", Kind::Bool, Start::Bool(false)),
|
||||
f("horizontalScale", Kind::Number(1.0, 10_000.0), Start::Num(100.0)),
|
||||
f("horizontalScale", Kind::Number(1.0, MAX_PRINT_SCALE), Start::Num(100.0)),
|
||||
f("orientation", choice("PrintOrientation", PRINT_ORIENTATION, PRINT_ORIENTATION), Start::Member("PORTRAIT")),
|
||||
f("position", choice("PrintPosition", PRINT_POSITION, PRINT_POSITION), Start::Member("TRANSLATECENTER")),
|
||||
f("tiling", choice("PrintTiling", PRINT_TILING, PRINT_TILING), Start::Member("TILESINGLEFULLPAGE")),
|
||||
f("verticalScale", Kind::Number(1.0, 10_000.0), Start::Num(100.0)),
|
||||
f("verticalScale", Kind::Number(1.0, MAX_PRINT_SCALE), Start::Num(100.0)),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -495,6 +509,7 @@ fn property(link: &Link, class: usize, field: usize) -> HostMember {
|
||||
/// What a `PrintOptions` asks `file.print` for.
|
||||
#[derive(Default)]
|
||||
struct Job {
|
||||
clear_fit: bool,
|
||||
preset: Option<String>,
|
||||
file: Option<Data>,
|
||||
level: Option<u64>,
|
||||
@@ -509,6 +524,7 @@ struct Job {
|
||||
paper_size: bool,
|
||||
/// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says.
|
||||
source: bool,
|
||||
custom: bool,
|
||||
/// `printArea` is assigned: the artboards print even when the base settings ignore them.
|
||||
print_area: bool,
|
||||
/// The groups of `settings`: the top level and each nested object by its key.
|
||||
@@ -647,6 +663,9 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) {
|
||||
if let Some(range) = job.range.as_ref().filter(|_| value("printAllArtboards").is_none()) {
|
||||
s.insert("range".into(), json!(range));
|
||||
}
|
||||
if job.range.is_none() && value("printAllArtboards").is_none() {
|
||||
s.insert("artboards".into(), json!("all"));
|
||||
}
|
||||
}
|
||||
"printArea" => job.print_area = true,
|
||||
_ => {}
|
||||
@@ -659,6 +678,7 @@ fn map_color(h: &Host, slot: usize, job: &mut Job) {
|
||||
let source = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "SOURCEPROFILE");
|
||||
job.profile = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v));
|
||||
job.source = source;
|
||||
job.custom = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "CUSTOMPROFILE");
|
||||
let g = job.group("color");
|
||||
for (k, v) in &set {
|
||||
if *k == "intent" {
|
||||
@@ -716,11 +736,12 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(
|
||||
Some(t)
|
||||
} else if scaled {
|
||||
Some("custom")
|
||||
} else if fit.is_some() || tiling.is_some() {
|
||||
} else if tiling.is_some() {
|
||||
Some("none")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
job.clear_fit = fit == Some(false) && scaling.is_none();
|
||||
if let Some(scaling) = scaling {
|
||||
job.top.insert("scaling".into(), json!(scaling));
|
||||
}
|
||||
@@ -834,6 +855,10 @@ fn map_postscript(h: &Host, slot: usize, job: &mut Job) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn postscript_name(path: &str, windows: bool) -> bool {
|
||||
super::save_open::filename_for_suffix(path, windows).to_lowercase().ends_with(".ps")
|
||||
}
|
||||
|
||||
/// `document.print(options?)`: `file.print` of the document to the file `jobOptions.file` names,
|
||||
/// with the assigned options over the document's print settings.
|
||||
fn doc_print(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -849,13 +874,13 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some(file) = job.file.take() else { return Err(HostError::Error(NO_PRINTER.into())) };
|
||||
check_names(h, doc, &mut job)?;
|
||||
let path = file_path(&file, "print")?;
|
||||
// The format follows the name `jobOptions.file` gives, not the real path a link leads to.
|
||||
let postscript = job.level.is_some() || postscript_name(path, cfg!(windows));
|
||||
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
|
||||
let mut p = Map::new();
|
||||
if let Some(preset) = job.preset.take() {
|
||||
p.insert("preset".into(), json!(preset));
|
||||
}
|
||||
// The format follows the name `jobOptions.file` gives, not the real path a link leads to.
|
||||
let postscript = job.level.is_some() || crate::cmd::fileio::extension(path) == "ps";
|
||||
p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" }));
|
||||
// PostScript prints at the level the options read as: an unassigned `postScriptLevel` is `PSLEVEL2`.
|
||||
if postscript {
|
||||
@@ -865,7 +890,7 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
|
||||
if !settings.is_empty() {
|
||||
p.insert("settings".into(), Value::Object(settings));
|
||||
}
|
||||
p.insert("path".into(), json!(plain(real)));
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, &Value::Object(p))))?;
|
||||
// What the job lost or how its options apply: one Script Console line each.
|
||||
let warnings = match &printed {
|
||||
@@ -888,21 +913,29 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
|
||||
/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or
|
||||
/// a control character, throws.
|
||||
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
|
||||
let (count, saved_ignore) = with_doc(h, doc, |_, st| {
|
||||
let (count, saved_ignore, saved_fit, mut base_profile) = with_doc(h, doc, |_, st| {
|
||||
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
|
||||
(st.doc.artboards.len(), mode == Some("ignore"))
|
||||
let fit = st.doc.print_setup.as_ref().and_then(|v| v.get("scaling")).and_then(Value::as_str) == Some("fit");
|
||||
let profile = st.doc.print_setup.as_ref().and_then(|v| v.get("color")).and_then(|v| v.get("profile")).and_then(Value::as_str);
|
||||
(st.doc.artboards.len(), mode == Some("ignore"), fit, profile.unwrap_or("").to_string())
|
||||
});
|
||||
if let Some(range) = &job.range {
|
||||
vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut base_ignore = saved_ignore;
|
||||
let mut base_fit = saved_fit;
|
||||
if let Some(name) = job.preset.take() {
|
||||
let n = plain_name("PrintOptions.printPreset", "print preset", &name)?;
|
||||
let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?;
|
||||
base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore);
|
||||
base_fit = matches!(preset.scaling, vectorcraft_pdf::PrintScaling::Fit);
|
||||
base_profile.clone_from(&preset.color.profile);
|
||||
job.preset = Some(n.to_string());
|
||||
}
|
||||
if job.clear_fit && base_fit {
|
||||
job.top.insert("scaling".into(), json!("none"));
|
||||
}
|
||||
// An assigned `printArea` prints by artboard when the base settings ignore the artboards: the
|
||||
// assigned `artboardRange` when there is one, otherwise every artboard.
|
||||
if job.print_area && base_ignore && !job.top.contains_key("artboards") {
|
||||
@@ -927,6 +960,8 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos
|
||||
if !job.source {
|
||||
job.group("color").insert("profile".into(), json!(profile.name));
|
||||
}
|
||||
} else if job.custom && base_profile.trim().is_empty() {
|
||||
return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into()));
|
||||
}
|
||||
if let Some(name) = job.paper.take() {
|
||||
let n = plain_name("PrintPaperOptions.name", "paper", &name)?;
|
||||
@@ -967,6 +1002,10 @@ const PRINT: &str = "file.print";
|
||||
/// only `id` passes the fence, and only for this one command.
|
||||
fn unfenced(h: &Host, id: &'static str, params: &Value) -> Answer {
|
||||
h.session.borrow_mut().script_unfenced = Some(id);
|
||||
#[cfg(test)]
|
||||
if crate::script::PANIC_WHILE_UNFENCED.with(std::cell::Cell::get) {
|
||||
panic!("a command past the fence failed");
|
||||
}
|
||||
let r = command(h, id, params);
|
||||
h.session.borrow_mut().script_unfenced = None;
|
||||
r
|
||||
@@ -997,17 +1036,6 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![("print", method(l, doc_print), returns("undefined", &[("options", "PrintOptions")]))])
|
||||
}
|
||||
|
||||
/// The type `reflect` gives for a property of the kind `kind`.
|
||||
fn kind_type(kind: Kind) -> &'static str {
|
||||
match kind {
|
||||
Kind::Bool => "boolean",
|
||||
Kind::Number(..) | Kind::Whole(..) => "number",
|
||||
Kind::Text => "string",
|
||||
Kind::Choice(name, ..) | Kind::Child(name) => name,
|
||||
Kind::File => "File",
|
||||
}
|
||||
}
|
||||
|
||||
/// The option classes: each `new Name()` gives a new option object with nothing assigned.
|
||||
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
CLASSES
|
||||
@@ -1023,10 +1051,10 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
let mut members = vec![("typename".to_string(), super::typename_of(c.name), typed("string"))];
|
||||
// `reflect` leaves out a property that is not mapped: it takes only its default.
|
||||
members.extend(c.fields.iter().enumerate().map(|(i, field)| {
|
||||
let info = MemberInfo { unavailable: !field.mapped, ..typed(kind_type(field.kind)) };
|
||||
let info = MemberInfo { unavailable: !field.mapped, ..field.kind.info() };
|
||||
(field.name.to_string(), property(link, index, i), info)
|
||||
}));
|
||||
HostClass { construct: Some(construct), ..super::class(c.name, None, members, None) }
|
||||
HostClass { construct: Some(construct), ..class(c.name, None, members, None) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Saving, exporting and opening documents in the script object model: `Document.saveAs`,
|
||||
//! `Document.exportFile`, `app.open` and `app.userInteractionLevel`, with the option classes the
|
||||
//! `Document.exportFile`, `Document.fullName`, `Document.path`, `Document.saved`,
|
||||
//! `Document.close`, `app.open` and `app.userInteractionLevel`, with the option classes the
|
||||
//! help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Application/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/>,
|
||||
@@ -27,10 +28,35 @@
|
||||
//! and when one of those files may not be written, none of them is.
|
||||
//! - An option the classes here map is applied; a listed option that is not mapped is accepted at
|
||||
//! the default its help page gives and throws an error that says it is not available yet at any
|
||||
//! other value; a property the help pages do not list is left out. With `pDFPreset` named, a
|
||||
//! `PDFSaveOptions` option still at a new object's default keeps the preset's value.
|
||||
//! other value; a property the help pages do not list throws an error that names it, unless it is
|
||||
//! `undefined`. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
|
||||
//! keeps the preset's value. A `pDFPreset` in square brackets names the built-in preset of the
|
||||
//! name inside them; the default preset's name and `[PDF/X-4:2008]` name VectorCraft Default and
|
||||
//! PDF/X-4:2010.
|
||||
//! - `artboardRange` is a string, or a number read as `String(number)`. With
|
||||
//! `saveMultipleArtboards` true, a `.ai` save also writes each artboard of the range (all when it
|
||||
//! is empty) to a file of its own, `<name>-<artboard name>.ai`. An EPS save of a range of two or
|
||||
//! more artboards writes the file at the path and `<name>_<artboard name>.eps` for each of them, and an EPS
|
||||
//! save of one artboard writes only the file at the path, holding that artboard. Without
|
||||
//! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of
|
||||
//! artboard numbers throws.
|
||||
//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no
|
||||
//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`.
|
||||
//! `fullName` and `path` of a document whose file the automation read roots do not allow throw
|
||||
//! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`.
|
||||
//! Assigning its current value runs no command.
|
||||
//! - `Document.close` with unsaved changes closes without them with
|
||||
//! `SaveOptions.DONOTSAVECHANGES`, and saves them to the document's file first with
|
||||
//! `SaveOptions.SAVECHANGES`, which throws for a document that has no file (a converted or
|
||||
//! recovered one included). `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws, since a
|
||||
//! script cannot show the prompt.
|
||||
//! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record:
|
||||
//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only.
|
||||
//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property
|
||||
//! but `typename` and `parent` throws the same error, unless it is `undefined`.
|
||||
//! Page and crop options require PDF content, including PDF-compatible `.ai` and `.ait` files.
|
||||
//! Built-in file reads by script commands reject files over 8 MiB and cap the read at 8 MiB plus one byte.
|
||||
//! - Optional arguments use defaults when omitted or `undefined`; explicit `null` throws a type error.
|
||||
//! - Each method sends command warnings to the Script Console with its name as the prefix.
|
||||
//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The
|
||||
//! commands a script runs never show a dialog, so the level does not change what they do, and it
|
||||
//! never allows a file the script's grants do not.
|
||||
@@ -42,8 +68,8 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{
|
||||
Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, given, method, named, num, on_doc,
|
||||
property, returns, text, this_doc, typed, whole,
|
||||
Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, class, command, current, doc_ref, get, given, method, named,
|
||||
num, on_doc, property, returns, text, this_doc, typed, whole,
|
||||
};
|
||||
|
||||
/// The most a scale factor of an export takes, in percent.
|
||||
@@ -84,6 +110,77 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]),
|
||||
("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]),
|
||||
("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]),
|
||||
("SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"]),
|
||||
// The enumerations of the options that keep their defaults (`Default::Member`).
|
||||
("OutputFlattening", &["PRESERVEAPPEARANCE", "PRESERVEPATHS"]),
|
||||
(
|
||||
"CompressionQuality",
|
||||
&[
|
||||
"AUTOMATICJPEG2000HIGH",
|
||||
"AUTOMATICJPEG2000LOSSLESS",
|
||||
"AUTOMATICJPEG2000LOW",
|
||||
"AUTOMATICJPEG2000MAXIMUM",
|
||||
"AUTOMATICJPEG2000MEDIUM",
|
||||
"AUTOMATICJPEG2000MINIMUM",
|
||||
"AUTOMATICJPEGHIGH",
|
||||
"AUTOMATICJPEGLOW",
|
||||
"AUTOMATICJPEGMAXIMUM",
|
||||
"AUTOMATICJPEGMEDIUM",
|
||||
"AUTOMATICJPEGMINIMUM",
|
||||
"JPEG2000HIGH",
|
||||
"JPEG2000LOSSLESS",
|
||||
"JPEG2000LOW",
|
||||
"JPEG2000MAXIMUM",
|
||||
"JPEG2000MEDIUM",
|
||||
"JPEG2000MINIMUM",
|
||||
"JPEGHIGH",
|
||||
"JPEGLOW",
|
||||
"JPEGMAXIMUM",
|
||||
"JPEGMEDIUM",
|
||||
"JPEGMINIMUM",
|
||||
"None",
|
||||
"ZIP4BIT",
|
||||
"ZIP8BIT",
|
||||
],
|
||||
),
|
||||
("ColorConversion", &["COLORCONVERSIONREPURPOSE", "COLORCONVERSIONTODEST", "None"]),
|
||||
(
|
||||
"ColorDestination",
|
||||
&[
|
||||
"COLORDESTINATIONDOCCMYK",
|
||||
"COLORDESTINATIONDOCRGB",
|
||||
"COLORDESTINATIONPROFILE",
|
||||
"COLORDESTINATIONWORKINGCMYK",
|
||||
"COLORDESTINATIONWORKINGRGB",
|
||||
"None",
|
||||
],
|
||||
),
|
||||
("ColorProfile", &["INCLUDEALLPROFILE", "INCLUDEDESTPROFILE", "INCLUDERGBPROFILE", "LEAVEPROFILEUNCHANGED", "None"]),
|
||||
("DownsampleMethod", &["AVERAGEDOWNSAMPLE", "BICUBICDOWNSAMPLE", "NODOWNSAMPLE", "SUBSAMPLE"]),
|
||||
("MonochromeCompression", &["CCIT3", "CCIT4", "MONOZIP", "None", "RUNLENGTH"]),
|
||||
("PageMarksTypes", &["Japanese", "Roman"]),
|
||||
(
|
||||
"PDFChangesAllowedEnum",
|
||||
&[
|
||||
"CHANGE128ANYCHANGES",
|
||||
"CHANGE128COMMENTING",
|
||||
"CHANGE128EDITPAGE",
|
||||
"CHANGE128FILLFORM",
|
||||
"CHANGE128NONE",
|
||||
"CHANGE40ANYCHANGES",
|
||||
"CHANGE40COMMENTING",
|
||||
"CHANGE40NONE",
|
||||
"CHANGE40PAGELAYOUT",
|
||||
],
|
||||
),
|
||||
("PDFPrintAllowedEnum", &["PRINT128HIGHRESOLUTION", "PRINT128LOWRESOLUTION", "PRINT128NONE", "PRINT40HIGHRESOLUTION", "PRINT40NONE"]),
|
||||
("PDFTrimMarkWeight", &["TRIMMARKWEIGHT0125", "TRIMMARKWEIGHT025", "TRIMMARKWEIGHT05"]),
|
||||
("PDFXStandard", &["PDFX1A2001", "PDFX1A2003", "PDFX32002", "PDFX32003", "PDFX42007", "PDFXNONE"]),
|
||||
("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]),
|
||||
("SVGDocumentEncoding", &["ASCII", "UTF16", "UTF8"]),
|
||||
("SVGDTDVersion", &["SVG1_0", "SVG1_1", "SVGBASIC1_1", "SVGTINY1_1", "SVGTINY1_1PLUS", "SVGTINY1_2"]),
|
||||
("SVGFontSubsetting", &["ALLGLYPHS", "COMMONENGLISH", "COMMONROMAN", "GLYPHSUSED", "GLYPHSUSEDPLUSENGLISH", "GLYPHSUSEDPLUSROMAN", "None"]),
|
||||
("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]),
|
||||
];
|
||||
|
||||
const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS";
|
||||
@@ -131,6 +228,11 @@ fn not_available(class: &str, name: &str) -> HostError {
|
||||
HostError::Error(format!("{class}.{name} is not available yet"))
|
||||
}
|
||||
|
||||
/// The error a property that the help page of `class` does not list throws.
|
||||
fn not_an_option(class: &str, name: &str) -> HostError {
|
||||
HostError::Error(format!("{class} has no option {name}"))
|
||||
}
|
||||
|
||||
fn whole_in(d: &Data, what: &str, lo: u64, hi: u64) -> std::result::Result<u64, HostError> {
|
||||
match d {
|
||||
Data::Number(n) => {
|
||||
@@ -158,9 +260,17 @@ fn compatibility(class: &str, d: &Data) -> std::result::Result<(), HostError> {
|
||||
}
|
||||
}
|
||||
|
||||
/// An artboard range: a string, given to the command as `range` unless it is empty.
|
||||
/// An artboard range: a string, or a whole number from 1 read as `String(number)` reads it, given to
|
||||
/// the command as `range` unless it is empty. Any other number throws.
|
||||
fn range(d: &Data, what: &str, p: &mut Map<String, Value>) -> std::result::Result<(), HostError> {
|
||||
let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) };
|
||||
let s = match d {
|
||||
Data::String(s) => s.clone(),
|
||||
Data::Number(n) => {
|
||||
whole(*n).filter(|n| *n >= 1).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 1 or a range")))?;
|
||||
vectorcraft_js::number_to_string(*n)
|
||||
}
|
||||
_ => return Err(HostError::Type(format!("{what} must be a string or a number"))),
|
||||
};
|
||||
if s.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range(format!("{what} is too long")));
|
||||
}
|
||||
@@ -182,17 +292,78 @@ fn ai_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Resu
|
||||
compatibility("IllustratorSaveOptions", d)?;
|
||||
None
|
||||
}
|
||||
"artboardRange" | "saveMultipleArtboards" => return artboards_map("IllustratorSaveOptions", name, d, p),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `artboardRange` and `saveMultipleArtboards` of a `.ai` or EPS save, as `range` and
|
||||
/// [`MULTIPLE`] until [`artboard_files`] reads them together.
|
||||
fn artboards_map(class: &str, name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("{class}.{name}");
|
||||
if name == "artboardRange" {
|
||||
range(d, &what, p)?;
|
||||
} else {
|
||||
p.insert(MULTIPLE.into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The key [`artboards_map`] keeps `saveMultipleArtboards` under.
|
||||
const MULTIPLE: &str = "_multiple";
|
||||
|
||||
/// The params of a `.ai` (`format` `ai`) or EPS save for `saveMultipleArtboards` and
|
||||
/// `artboardRange`: with `saveMultipleArtboards` true, the range (all when it is empty) goes to
|
||||
/// `separateArtboards` of a `.ai` save or `useArtboards` of an EPS save, which write the artboards'
|
||||
/// files; otherwise the range is not used, as the help pages say, but one that is not written as a
|
||||
/// range ([`written_as_range`]) still throws.
|
||||
fn artboard_files(format: &str, q: &mut Map<String, Value>) -> std::result::Result<(), HostError> {
|
||||
let multiple = q.remove(MULTIPLE).and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
if !multiple {
|
||||
if let Some(Value::String(r)) = q.remove("range")
|
||||
&& !r.trim().eq_ignore_ascii_case("all")
|
||||
&& !written_as_range(&r)
|
||||
{
|
||||
return Err(HostError::Range(format!("artboardRange `{r}` is not a range of artboard numbers")));
|
||||
}
|
||||
} else if format == "ai" {
|
||||
q.insert("separateArtboards".into(), json!(true));
|
||||
} else {
|
||||
q.insert("useArtboards".into(), json!(true));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `r` is written as an artboard range, whatever artboards a document has: one or more
|
||||
/// parts separated by commas, each a number from 1, or two of them joined by `-` or `–` with either one left out
|
||||
/// and the first no greater than the second.
|
||||
fn written_as_range(r: &str) -> bool {
|
||||
// A number of digits alone, from 1; past `u64` it counts as the largest.
|
||||
let num = |t: &str| -> Option<Option<u64>> {
|
||||
let t = t.trim();
|
||||
if t.is_empty() {
|
||||
return Some(None);
|
||||
}
|
||||
let n = t.bytes().all(|b| b.is_ascii_digit()).then(|| t.parse::<u64>().unwrap_or(u64::MAX))?;
|
||||
(n >= 1).then_some(Some(n))
|
||||
};
|
||||
let mut parts = r.split(',').map(str::trim).filter(|p| !p.is_empty()).peekable();
|
||||
parts.peek().is_some()
|
||||
&& parts.all(|part| match part.replace('\u{2013}', "-").split_once('-') {
|
||||
Some((a, b)) => match (num(a), num(b)) {
|
||||
(Some(Some(a)), Some(Some(b))) => a <= b,
|
||||
(Some(a), Some(b)) => a.is_some() || b.is_some(),
|
||||
_ => false,
|
||||
},
|
||||
None => matches!(num(part), Some(Some(_))),
|
||||
})
|
||||
}
|
||||
|
||||
const AI_KEPT: &[(&str, Default)] = &[
|
||||
("artboardRange", Default::Text("")),
|
||||
("embedLinkedFiles", Default::Bool(false)),
|
||||
("flattenOutput", Default::Member("OutputFlattening", "PRESERVEAPPEARANCE")),
|
||||
("fontSubsetThreshold", Default::Num(100.0)),
|
||||
("saveMultipleArtboards", Default::Bool(false)),
|
||||
];
|
||||
|
||||
fn ai_starts() -> Vec<(&'static str, Data)> {
|
||||
@@ -229,18 +400,17 @@ fn eps_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Res
|
||||
p.insert("overprints".into(), json!(if keep { "preserve" } else { "discard" }));
|
||||
}
|
||||
"compatibility" => compatibility("EPSSaveOptions", d)?,
|
||||
"artboardRange" | "saveMultipleArtboards" => return artboards_map("EPSSaveOptions", name, d, p),
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
const EPS_KEPT: &[(&str, Default)] = &[
|
||||
("artboardRange", Default::Text("")),
|
||||
("compatibleGradientPrinting", Default::Bool(false)),
|
||||
("embedAllFonts", Default::Bool(false)),
|
||||
("embedLinkedFiles", Default::Unset),
|
||||
("flattenOuput", Default::Unset),
|
||||
("saveMultipleArtboards", Default::Bool(false)),
|
||||
];
|
||||
|
||||
fn eps_starts() -> Vec<(&'static str, Data)> {
|
||||
@@ -522,7 +692,7 @@ fn options_params(class: &OptionClass, d: &Data) -> std::result::Result<Map<Stri
|
||||
match class.kept.iter().find(|(n, _)| n == k) {
|
||||
Some((_, default)) if default.matches(v) => {}
|
||||
Some(_) => return Err(not_available(class.name, k)),
|
||||
None => {}
|
||||
None => return Err(not_an_option(class.name, k)),
|
||||
}
|
||||
}
|
||||
Ok(p)
|
||||
@@ -566,9 +736,44 @@ pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
|
||||
r
|
||||
}
|
||||
|
||||
/// The path to give a command for the real path `real`.
|
||||
pub(super) fn plain(real: std::path::PathBuf) -> String {
|
||||
crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()
|
||||
/// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s
|
||||
/// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or
|
||||
/// a linked image an open could not read. → the command's answer.
|
||||
fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
|
||||
let (answer, value) = super::super::command_value(h, id, p)?;
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().take(super::MAX_LISTED).filter_map(Value::as_str) {
|
||||
super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
|
||||
}
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8.
|
||||
pub(super) fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
|
||||
crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into()))
|
||||
}
|
||||
|
||||
/// The built-in preset names scripts use that VectorCraft's built-in presets name otherwise, and the
|
||||
/// preset each one names here (`Default` is VectorCraft's default preset, as
|
||||
/// [`vectorcraft_pdf::builtin_preset`] reads it).
|
||||
const PRESET_ALIASES: &[(&str, &str)] = &[
|
||||
("Illustrator Default", "Default"), // brand-ok: the preset name scripts use
|
||||
("PDF/X-4:2008", "PDF/X-4:2010"),
|
||||
];
|
||||
|
||||
/// A `pDFPreset` in square brackets (`[Smallest File Size]`) names the built-in preset of the name
|
||||
/// inside the brackets, or the one [`PRESET_ALIASES`] gives for it. A preset the name already
|
||||
/// names, a saved preset called `[Name]` included, is left as it is, and any other name is left for
|
||||
/// the save to refuse.
|
||||
fn builtin_preset_name(h: &Host, q: &mut Map<String, Value>) {
|
||||
let Some(name) = q.get("preset").and_then(Value::as_str) else { return };
|
||||
let s = h.session.borrow();
|
||||
if crate::cmd::fileio::pdf::find_preset(name, &s.prefs.pdf_presets).is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(inside) = name.trim().strip_prefix('[').and_then(|n| n.strip_suffix(']')) else { return };
|
||||
let inside = PRESET_ALIASES.iter().find(|(alias, _)| alias.eq_ignore_ascii_case(inside.trim())).map_or(inside, |(_, to)| to);
|
||||
let Some(builtin) = vectorcraft_pdf::builtin_preset(inside, vectorcraft_pdf::APP) else { return };
|
||||
q.insert("preset".into(), json!(builtin.name));
|
||||
}
|
||||
|
||||
/// `document.saveAs(file, options?)`: `file.saveAs` on the document, in the format the options'
|
||||
@@ -577,34 +782,61 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let path = file_path(arg(a, 1), "saveAs")?;
|
||||
let mut p = Map::new();
|
||||
let given_options = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null));
|
||||
let given_options = given(arg(a, 2));
|
||||
// Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options
|
||||
// object of that format's class holds.
|
||||
let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase());
|
||||
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == extension.as_deref()).map(|(c, _)| fresh(c));
|
||||
let named_format = save_format_for_name(path, cfg!(windows)).map(|f| f.id);
|
||||
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == named_format).map(|(c, _)| fresh(c));
|
||||
if let Some(o) = given_options.or(by_extension.as_ref()) {
|
||||
let name = typename(o);
|
||||
let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else {
|
||||
return Err(HostError::Type("saveAs options must be IllustratorSaveOptions, EPSSaveOptions or PDFSaveOptions".into()));
|
||||
};
|
||||
let q = options_params(class, o)?;
|
||||
let mut q = options_params(class, o)?;
|
||||
if *format == "pdf" {
|
||||
builtin_preset_name(h, &mut q);
|
||||
} else {
|
||||
artboard_files(format, &mut q)?;
|
||||
}
|
||||
p.insert("format".into(), json!(format));
|
||||
if *format == "ai" {
|
||||
p.extend(q);
|
||||
} else if !q.is_empty() {
|
||||
p.insert("options".into(), Value::Object(q));
|
||||
}
|
||||
} else {
|
||||
let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id);
|
||||
p.insert("format".into(), json!(format));
|
||||
}
|
||||
if !p.contains_key("format") {
|
||||
let format = named_format.unwrap_or_else(|| super::with_doc(h, doc, |_, st| st.format));
|
||||
p.insert("format".into(), json!(format));
|
||||
}
|
||||
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
|
||||
p.insert("path".into(), json!(plain(real)));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?;
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.saveAs", "file.saveAs", &Value::Object(p))))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `path` with the extension of `kind` added, unless its name already ends with one of them.
|
||||
fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String {
|
||||
let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions };
|
||||
let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase();
|
||||
fn save_format_for_name(path: &str, windows: bool) -> Option<&'static crate::cmd::fileio::Format> {
|
||||
let name = filename_for_suffix(path, windows);
|
||||
// A name that is only a dot and an extension, such as `.pdf`, picks its format only for the
|
||||
// `.ai`, `.eps` and `.pdf` options classes; any other name takes the usual extension rule.
|
||||
match name.rsplit_once('.') {
|
||||
Some(("", extension)) if SAVE_CLASSES.iter().any(|(_, f)| extension.eq_ignore_ascii_case(f)) => {
|
||||
crate::cmd::fileio::format_for_name(&format!("x.{extension}"))
|
||||
}
|
||||
_ => crate::cmd::fileio::format_for_name(name),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn filename_for_suffix(path: &str, windows: bool) -> &str {
|
||||
let name = if windows { path.rsplit(['/', '\\']).next() } else { path.rsplit('/').next() }.unwrap_or(path);
|
||||
if windows { name.trim_end_matches(['.', ' ']) } else { name }
|
||||
}
|
||||
|
||||
pub(crate) fn with_extension(path: &str, extensions: &[&str], windows: bool) -> String {
|
||||
let name = filename_for_suffix(path, windows).to_lowercase();
|
||||
match extensions.first() {
|
||||
Some(first) if !extensions.iter().any(|e| name.ends_with(&format!(".{e}"))) => format!("{path}.{first}"),
|
||||
_ => path.to_string(),
|
||||
@@ -618,13 +850,14 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
let path = file_path(arg(a, 1), "exportFile")?;
|
||||
let kind = export_kind(arg(a, 2))?;
|
||||
// Without options, an export takes the defaults a new options object of its class holds.
|
||||
let mut p = match given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) {
|
||||
let mut p = match given(arg(a, 3)) {
|
||||
None => match kind.options {
|
||||
Some(class) => options_params(class, &fresh(class))?,
|
||||
None => Map::new(),
|
||||
},
|
||||
Some(o) => match kind.options {
|
||||
Some(class) => options_params(class, o)?,
|
||||
None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())),
|
||||
None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))),
|
||||
},
|
||||
};
|
||||
@@ -648,10 +881,10 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
} else {
|
||||
p.insert("useArtboards".into(), json!(false));
|
||||
}
|
||||
let named = with_extension(path, &kind, svgz);
|
||||
let named = with_extension(path, if svgz { &["svgz"] } else { kind.extensions }, cfg!(windows));
|
||||
let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?;
|
||||
p.insert("path".into(), json!(plain(real)));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?;
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.exportFile", "document.export", &Value::Object(p))))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -660,16 +893,19 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
let path = file_path(arg(a, 1), "open")?;
|
||||
let mut p = Map::new();
|
||||
if let Some(d) = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)) {
|
||||
if let Some(d) = given(arg(a, 2)) {
|
||||
let mode = if member(d, "DocumentColorSpace", &["CMYK", "RGB"], "documentColorSpace")? == "RGB" { "rgb" } else { "cmyk" };
|
||||
p.insert("colorMode".into(), json!(mode));
|
||||
}
|
||||
if let Some(o) = given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) {
|
||||
if let Some(o) = given(arg(a, 3)) {
|
||||
let Data::Object(items) = o else { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())) };
|
||||
if typename(o).is_some_and(|t| t != "PDFFileOptions") {
|
||||
return Err(HostError::Type("open's options must be a PDFFileOptions record".into()));
|
||||
}
|
||||
for (k, v) in items {
|
||||
if matches!(v, Data::Undefined) {
|
||||
continue;
|
||||
}
|
||||
match k.as_str() {
|
||||
"pageToOpen" => {
|
||||
p.insert("page".into(), json!(whole_in(v, "PDFFileOptions.pageToOpen", 1, 1_000_000)?));
|
||||
@@ -686,13 +922,26 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
};
|
||||
p.insert("cropTo".into(), json!(crop));
|
||||
}
|
||||
_ => {}
|
||||
// The read-only members the help page lists.
|
||||
"typename" | "parent" => {}
|
||||
_ => return Err(not_an_option("PDFFileOptions", k)),
|
||||
}
|
||||
}
|
||||
}
|
||||
if p.contains_key("cropTo") {
|
||||
p.insert("editingData".into(), json!(false));
|
||||
}
|
||||
// The command opens the given path; a real path that is not valid UTF-8 is still refused.
|
||||
let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?;
|
||||
p.insert("path".into(), json!(plain(real)));
|
||||
let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?;
|
||||
plain(real)?;
|
||||
p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?));
|
||||
let r = crate::cmd::fileio::with_read_limit(super::super::files::MAX_OPEN_BYTES as usize, || {
|
||||
exactly(h, || warned(h, "app.open", "document.open", &Value::Object(p)))
|
||||
})
|
||||
.map_err(|e| match e {
|
||||
HostError::Error(message) if message == crate::cmd::fileio::READ_TOO_LARGE => refused(super::super::files::OPEN_TOO_LARGE, path),
|
||||
e => e,
|
||||
})?;
|
||||
let index = match &r {
|
||||
Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) {
|
||||
("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()),
|
||||
@@ -705,6 +954,172 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(doc_ref(h, st.uid))
|
||||
}
|
||||
|
||||
/// The document's file, `None` for a document that has none, or `Script file access denied` with
|
||||
/// the document's name when the automation read roots do not allow the file to be named
|
||||
/// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them.
|
||||
fn shown_file(st: &crate::DocState) -> std::result::Result<Option<String>, HostError> {
|
||||
let path = st.path.as_deref().map(absolute_file).transpose()?;
|
||||
match path.as_deref() {
|
||||
Some(p) if crate::file_access::check_read(p).is_err() => {
|
||||
Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title())))
|
||||
}
|
||||
_ => Ok(path),
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute_file(path: &str) -> std::result::Result<String, HostError> {
|
||||
let path = std::path::Path::new(path);
|
||||
if path.is_absolute() {
|
||||
Ok(path.to_string_lossy().into_owned())
|
||||
} else {
|
||||
let cwd = std::env::current_dir().map_err(|e| HostError::Error(e.to_string()))?;
|
||||
Ok(cwd.join(path).to_string_lossy().into_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// `document.fullName`: a `File` for the document's file, or, for a document that has none, a
|
||||
/// `File` for its name in `Folder.current`.
|
||||
fn doc_full_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
super::with_doc(h, doc, |_, st| {
|
||||
Ok(match shown_file(st)? {
|
||||
Some(p) => vectorcraft_js::file_ref(&p),
|
||||
None => vectorcraft_js::file_ref(&st.title()),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a
|
||||
/// document that has none.
|
||||
fn doc_path(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let folder = super::with_doc(h, doc, |_, st| {
|
||||
Ok(shown_file(st)?.and_then(|p| {
|
||||
let parent = std::path::Path::new(&p).parent()?.to_string_lossy().into_owned();
|
||||
(!parent.is_empty()).then_some(parent)
|
||||
}))
|
||||
})?;
|
||||
Ok(folder.map_or_else(|| text(""), |f| vectorcraft_js::folder_ref(&f)))
|
||||
}
|
||||
|
||||
/// `document.saved`: whether the document has no changes since it was opened or last saved.
|
||||
fn doc_saved(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok(Data::Bool(super::with_doc(h, doc, |_, st| !st.is_dirty())))
|
||||
}
|
||||
|
||||
/// `document.saved = value`: `document.setSaved`, which records the document as saved or as having
|
||||
/// unsaved changes without saving it.
|
||||
fn doc_set_saved(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let saved = boolean(arg(a, 1), "Document.saved")?;
|
||||
if saved == super::with_doc(h, doc, |_, st| !st.is_dirty()) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
command(h, "document.setSaved", &json!({"index": doc.index, "saved": saved}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The error `close` gives for a document with unsaved changes with
|
||||
/// `SaveOptions.PROMPTTOSAVECHANGES`.
|
||||
const UNSAVED_CHANGES: &str =
|
||||
"the document has unsaved changes: save them first, or close with SaveOptions.SAVECHANGES or SaveOptions.DONOTSAVECHANGES";
|
||||
|
||||
/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes that has
|
||||
/// no file to save to.
|
||||
const NO_FILE_TO_SAVE: &str =
|
||||
"the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
|
||||
|
||||
/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes whose
|
||||
/// save would keep only some of its artboards.
|
||||
const SAVES_SOME_ARTBOARDS: &str =
|
||||
"the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
|
||||
|
||||
/// Whether the file that saving `st` with its remembered options writes would omit artboards. A
|
||||
/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai`
|
||||
/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its
|
||||
/// `range` names only the separate files. An EPS file embeds the whole document in its main file,
|
||||
/// so its `artboardRange` never omits an artboard from what reopens.
|
||||
fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
|
||||
if st.format == "eps" {
|
||||
return false;
|
||||
}
|
||||
let options = Value::Object(crate::cmd::fileio::remembered_save_options(st));
|
||||
let svg = matches!(st.format, "svg" | "svgz");
|
||||
if svg && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() {
|
||||
return true;
|
||||
}
|
||||
if st.format == "pdf" && options.get("useArtboards") == Some(&Value::Bool(false)) {
|
||||
return true;
|
||||
}
|
||||
let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options);
|
||||
if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy {
|
||||
return false;
|
||||
}
|
||||
let count = st.doc.artboards.len();
|
||||
// A `.ai` file other than a legacy one saves with `range` "all" (a `range` that isn't text is
|
||||
// left for the save to refuse).
|
||||
let modern_ai = matches!(st.format, "ai" | "ait") && !legacy;
|
||||
let mut effective = options.clone();
|
||||
if let (true, Value::Object(o)) = (modern_ai, &mut effective)
|
||||
&& o.get("range").is_none_or(|r| r.is_string() || r.is_null())
|
||||
{
|
||||
o.insert("range".into(), json!("all"));
|
||||
}
|
||||
let resolved = serde_json::from_value::<crate::cmd::fileio::ArtboardPick>(effective).map_err(|e| e.to_string()).and_then(|p| p.resolve(count));
|
||||
// Such a `.ai` file, and an SVG file that carries the native document, keep every artboard;
|
||||
// a pick the save refuses still refuses (an SVG save with `useArtboards: false` reads no pick).
|
||||
if modern_ai {
|
||||
return resolved.is_err();
|
||||
}
|
||||
if svg && crate::cmd::fileio::svg_preserves_editing(&st.doc, &options) {
|
||||
return options.get("useArtboards") != Some(&Value::Bool(false)) && resolved.is_err();
|
||||
}
|
||||
match resolved {
|
||||
Ok(None) => false,
|
||||
Ok(Some(indices)) => (0..count).any(|i| !indices.contains(&i)),
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved
|
||||
/// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES`
|
||||
/// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with
|
||||
/// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of
|
||||
/// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`]
|
||||
/// for a document that has no file, a converted or recovered one included, and
|
||||
/// [`SAVES_SOME_ARTBOARDS`] before writing when the save would omit artboards; and
|
||||
/// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script
|
||||
/// cannot show the prompt.
|
||||
fn doc_close(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let how = match given(arg(a, 1)) {
|
||||
Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?,
|
||||
None => "PROMPTTOSAVECHANGES",
|
||||
};
|
||||
let (dirty, file, format, picked) =
|
||||
super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format, picks_artboards(st)));
|
||||
if dirty {
|
||||
match how {
|
||||
"DONOTSAVECHANGES" => {}
|
||||
"SAVECHANGES" => {
|
||||
let path = absolute_file(&file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?)?;
|
||||
if picked {
|
||||
return Err(HostError::Error(SAVES_SOME_ARTBOARDS.into()));
|
||||
}
|
||||
// A refusal names the document, as `fullName` does when the read roots hide its file.
|
||||
let name = super::with_doc(h, doc, |_, st| st.title());
|
||||
let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?;
|
||||
let p = json!({"path": plain(real)?, "format": format});
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.close", "file.saveAs", &p)))?;
|
||||
}
|
||||
_ => return Err(HostError::Error(UNSAVED_CHANGES.into())),
|
||||
}
|
||||
}
|
||||
command(h, "file.close", &json!({"index": doc.index}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn app_interaction(h: &Host, _: &[Data]) -> Answer {
|
||||
Ok(text(if h.dom.save_options.quiet.get() { QUIET } else { DISPLAY }))
|
||||
}
|
||||
@@ -728,6 +1143,10 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("saveAs", method(l, doc_save_as), returns("undefined", &[("saveIn", "File"), ("options", "*")])),
|
||||
("exportFile", method(l, doc_export_file), returns("undefined", &[("exportFile", "File"), ("exportFormat", "ExportType"), ("options", "*")])),
|
||||
("fullName", get(l, doc_full_name), typed("File")),
|
||||
("path", get(l, doc_path), typed("Folder|string")),
|
||||
("saved", property(l, doc_saved, doc_set_saved), typed("boolean")),
|
||||
("close", method(l, doc_close), returns("undefined", &[("saveOptions", "SaveOptions")])),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -741,7 +1160,37 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
current(&l)?.charge_call(64)?;
|
||||
Ok(fresh(c))
|
||||
});
|
||||
HostClass { name: c.name.into(), parent: None, members: Vec::new(), info: Vec::new(), index: None, construct: Some(f) }
|
||||
HostClass { construct: Some(f), ..class(c.name, None, Vec::new(), None) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod save_format_tests {
|
||||
use super::save_format_for_name;
|
||||
|
||||
#[test]
|
||||
fn save_as_selects_the_format_from_windows_filename_aliases() {
|
||||
for extension in ["svg", "svgz", "ai", "eps", "pdf"] {
|
||||
for suffix in [".", " ", ". . ", "..."] {
|
||||
for prefix in ["", "/exports/", "C:\\exports\\"] {
|
||||
let name = format!("{prefix}drawing.{}{suffix}", extension.to_ascii_uppercase());
|
||||
assert_eq!(save_format_for_name(&name, true).map(|f| f.id), Some(extension), "{name}");
|
||||
assert!(save_format_for_name(&name, false).is_none(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
for name in ["drawing", "drawing. . ", "drawing.svg\t", "drawing.svg\u{a0}", "folder.svg/drawing", "folder.svg\\drawing"] {
|
||||
assert!(save_format_for_name(name, true).is_none(), "{name}");
|
||||
}
|
||||
assert_eq!(save_format_for_name("proof\\.svg", false).map(|f| f.id), Some("svg"));
|
||||
for windows in [false, true] {
|
||||
assert_eq!(save_format_for_name(".pdf", windows).map(|f| f.id), Some("pdf"));
|
||||
assert!(save_format_for_name(".svg", windows).is_none());
|
||||
assert!(save_format_for_name("/exports/.png", windows).is_none());
|
||||
assert_eq!(save_format_for_name("/exports/.eps", windows).map(|f| f.id), Some("eps"));
|
||||
assert_eq!(save_format_for_name("drawing.svg", windows).map(|f| f.id), Some("svg"));
|
||||
assert_eq!(save_format_for_name("drawing.svgz", windows).map(|f| f.id), Some("svgz"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,6 +108,9 @@ pub const MAX_MASK_STEPS: usize = 1 << 24;
|
||||
|
||||
pub(crate) const ACCESS_DENIED: &str = "Script file access denied";
|
||||
pub(crate) const TOO_LARGE: &str = "Script file exceeds 8 MiB";
|
||||
/// The largest document `app.open` reads, checked before the file is read.
|
||||
pub(crate) const MAX_OPEN_BYTES: u64 = 256 << 20;
|
||||
pub(crate) const OPEN_TOO_LARGE: &str = "Script document exceeds 256 MiB";
|
||||
pub(crate) const NOT_OPEN: &str = "Script file is not open";
|
||||
pub(crate) const UNDECODABLE: &str = "Script file cannot be decoded";
|
||||
pub(crate) const NOT_REGULAR: &str = "Script file is not a regular file";
|
||||
@@ -475,7 +478,7 @@ impl Disk {
|
||||
/// the run began link to them, `linked`, but not the files its `File` objects hold open for writing.
|
||||
pub(crate) fn gate(&self, documents: Vec<String>, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate {
|
||||
// A save, export or open of a `File` the script names reads and writes as its `File` would.
|
||||
let documents = if self.exact { Vec::new() } else { documents };
|
||||
let (documents, linked) = if self.exact { (Vec::new(), Default::default()) } else { (documents, linked) };
|
||||
let held = self.open.values().filter_map(|o| o.target.clone()).collect();
|
||||
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, linked, also: None }
|
||||
}
|
||||
@@ -723,9 +726,13 @@ impl Disk {
|
||||
Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED),
|
||||
Err(ScriptRead::Failed(_)) => return Err(READ_FAILED),
|
||||
};
|
||||
if !real.is_file() {
|
||||
let meta = std::fs::metadata(&real).map_err(|_| READ_FAILED)?;
|
||||
if !meta.is_file() {
|
||||
return Err(NOT_REGULAR);
|
||||
}
|
||||
if meta.len() > MAX_OPEN_BYTES {
|
||||
return Err(OPEN_TOO_LARGE);
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
|
||||
@@ -2886,6 +2886,8 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
}
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
s.script_in_run = false;
|
||||
// A panic in a member that opened the fence for one command skips its own reset.
|
||||
s.script_unfenced = None;
|
||||
job.world.swap(s);
|
||||
s.depth = depth;
|
||||
s.sync_front_profiles();
|
||||
@@ -2952,6 +2954,8 @@ thread_local! {
|
||||
pub(crate) static TEST_RESULT_BYTES: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: makes the next slice panic.
|
||||
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: makes the next command a member runs past the script fence panic before it runs.
|
||||
pub(crate) static PANIC_WHILE_UNFENCED: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
|
||||
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
|
||||
|
||||
@@ -247,6 +247,62 @@ fn replace_keeps_the_transform_and_the_stacking_place() {
|
||||
assert_eq!(top_children(&s)[0].id.0, first.as_u64().unwrap(), "one undo step brings the old image back");
|
||||
}
|
||||
|
||||
/// `image.info` reads a PNG's colour mode from its header without decoding its pixels: a grayscale
|
||||
/// PNG whose compressed pixel data is unreadable still says Grayscale. The Control bar asks again
|
||||
/// after every step of a drag, so a decode there redid a large image's whole decode each step.
|
||||
#[test]
|
||||
fn image_color_mode_reads_the_header_without_decoding_the_pixels() {
|
||||
let raw: Vec<u8> = (0..64u32 * 64).map(|i| (i * 7 % 251) as u8).collect();
|
||||
let gray = craft_image_codecs::Image::from_raw(64, 64, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap();
|
||||
let mut png = craft_image_codecs::encode(&gray, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
assert_eq!(cmd::place::color_mode(&png), "Grayscale");
|
||||
// Each IDAT chunk's data zeroed (an invalid zlib stream) under a correct CRC.
|
||||
let mut at = 8;
|
||||
let mut idat = 0;
|
||||
while at + 12 <= png.len() {
|
||||
let len = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
|
||||
if &png[at + 4..at + 8] == b"IDAT" {
|
||||
png[at + 8..at + 8 + len].fill(0);
|
||||
let crc = crc32fast::hash(&png[at + 4..at + 8 + len]);
|
||||
png[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes());
|
||||
idat += 1;
|
||||
}
|
||||
at += 12 + len;
|
||||
}
|
||||
assert!(idat > 0, "the PNG has pixel data");
|
||||
assert!(craft_image_codecs::decode(&png).is_err(), "the pixels no longer decode");
|
||||
assert_eq!(cmd::place::color_mode(&png), "Grayscale", "the header alone gives the colour mode");
|
||||
}
|
||||
|
||||
/// The colour mode read from a file's header is the one its decoded pixels have, in every format
|
||||
/// and channel layout the codecs write.
|
||||
#[test]
|
||||
fn image_color_mode_from_the_header_matches_the_decoded_pixels() {
|
||||
use craft_image_codecs::{ChannelLayout as L, Format as F};
|
||||
let decoded = |bytes: &[u8]| match craft_image_codecs::decode(bytes).map(|i| i.layout()) {
|
||||
Ok(L::Gray | L::GrayA) => "Grayscale",
|
||||
Ok(L::Cmyk | L::CmykA) => "CMYK",
|
||||
Ok(_) => "RGB",
|
||||
Err(e) => panic!("the written file decodes: {e}"),
|
||||
};
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut checked = 0;
|
||||
for format in [F::Png, F::Jpeg, F::Tiff, F::Gif, F::Bmp, F::WebP] {
|
||||
for layout in [L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk] {
|
||||
let n = 16 * 16 * layout.channels();
|
||||
let raw: Vec<u8> = (0..n).map(|i| (i * 13 % 256) as u8).collect();
|
||||
let img = craft_image_codecs::Image::from_raw(16, 16, layout, craft_image_codecs::SampleType::U8, raw).unwrap();
|
||||
let Ok(bytes) = craft_image_codecs::encode(&img, format, &craft_image_codecs::EncodeOptions::default()) else { continue };
|
||||
let want = decoded(&bytes);
|
||||
assert_eq!(cmd::place::color_mode(&bytes), want, "{format:?} written from {layout:?}");
|
||||
seen.insert(want);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked >= 12, "{checked} files written");
|
||||
assert_eq!(seen.into_iter().collect::<Vec<_>>(), ["CMYK", "Grayscale", "RGB"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_needs_exactly_one_selected_object() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -2348,29 +2348,35 @@ static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
struct HeldLoad {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
entered: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
go: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
go: std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
|
||||
gave_up: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
impl HeldLoad {
|
||||
/// Holds the load of the file at `path`. A load the test never lets go gives up after a
|
||||
/// million yields (so a test of code that waits for it ends) and says so in `gave_up`.
|
||||
/// Holds the load of the file at `path` until [`HeldLoad::release`] or the drop. A load that
|
||||
/// runs on the thread that made this one is not held, since nothing could let it go: it goes
|
||||
/// ahead at once and says so in `gave_up`.
|
||||
fn new(path: std::path::PathBuf) -> HeldLoad {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
|
||||
let (entered, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
|
||||
let go = Arc::new((Mutex::new(false), Condvar::new()));
|
||||
let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone());
|
||||
let test_thread = std::thread::current().id();
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| {
|
||||
if p != path {
|
||||
return;
|
||||
}
|
||||
e.store(true, Ordering::SeqCst);
|
||||
if !(0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
g.load(Ordering::SeqCst)
|
||||
}) {
|
||||
if std::thread::current().id() == test_thread {
|
||||
q.store(true, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
let (open, opened) = &*g;
|
||||
let mut open = open.lock().unwrap_or_else(|e| e.into_inner());
|
||||
while !*open {
|
||||
open = opened.wait(open).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
}));
|
||||
HeldLoad { _lock: lock, entered, go, gave_up }
|
||||
@@ -2381,7 +2387,9 @@ impl HeldLoad {
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
self.go.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let (open, opened) = &*self.go;
|
||||
*open.lock().unwrap_or_else(|e| e.into_inner()) = true;
|
||||
opened.notify_all();
|
||||
}
|
||||
|
||||
fn gave_up(&self) -> bool {
|
||||
@@ -2905,6 +2913,7 @@ fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() {
|
||||
#[test]
|
||||
fn a_query_runs_while_the_plugins_load() {
|
||||
let id = "test.engine.background.query";
|
||||
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
|
||||
let (folder, path) = store_with("plugin-background-query", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
@@ -2918,7 +2927,6 @@ fn a_query_runs_while_the_plugins_load() {
|
||||
let waited = held.gave_up() || !s.plugins_loading();
|
||||
held.release();
|
||||
assert!(!waited, "document.info waited for the plug-ins to load");
|
||||
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
|
||||
s.finish_plugin_loads();
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
@@ -2936,18 +2944,14 @@ fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
|
||||
while !held.entered() && !held.gave_up() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Other tests take the lock for a moment; the load holding it would hold it throughout (a
|
||||
// tenth of the yields the held load waits before it gives up).
|
||||
let free = (0..100_000).any(|_| {
|
||||
// A load run on this thread isn't held, so a free lock then shows nothing.
|
||||
assert!(!held.gave_up(), "the module loaded on the test's thread");
|
||||
// Other tests take the lock for a moment; the held load holding it would hold it until it is let go.
|
||||
while !crate::cmd::plugin::plugin_changes_free() {
|
||||
std::thread::yield_now();
|
||||
crate::cmd::plugin::plugin_changes_free()
|
||||
});
|
||||
// A load that gave up waiting no longer holds anything, so a free lock then shows nothing.
|
||||
let gave_up = held.gave_up();
|
||||
}
|
||||
held.release();
|
||||
s.finish_plugin_loads();
|
||||
assert!(!gave_up, "the held load gave up before the lock was looked at");
|
||||
assert!(free, "the lock was held while the module loaded");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
@@ -2975,6 +2979,10 @@ fn canceled_loads_forget_the_grants_of_what_they_installed() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
|
||||
assert!(s.plugins_loading(), "the second module is still loading");
|
||||
// Canceling waits for a running load until its deadline; the second module, let go, loads
|
||||
// while the cancel runs or before it, and doesn't install either way.
|
||||
held.release();
|
||||
s.cancel_plugin_loads();
|
||||
// The file goes once it holds no grant.
|
||||
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
|
||||
@@ -133,6 +133,90 @@ fn pathless_save_rejection_hides_document_folder() {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_file_save_directory_errors_hide_paths_the_caller_did_not_give() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let d = dir("multi-file-directory-error");
|
||||
let (inside, outside) = (d.join("in"), d.join("kept-out"));
|
||||
for folder in [&inside, &outside] {
|
||||
std::fs::create_dir_all(folder).unwrap();
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let own = path(&outside, "doc.vectorcraft");
|
||||
let saved = s.execute("document.save", &json!({"path": own, "separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = saved["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert!(files.len() > 1, "{saved}");
|
||||
let primary = std::fs::read(&own).unwrap();
|
||||
rect(&mut s);
|
||||
let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap();
|
||||
for target in [&files[0], &files[1]] {
|
||||
let original = std::fs::read(target).unwrap();
|
||||
std::fs::remove_file(target).unwrap();
|
||||
std::fs::create_dir(target).unwrap();
|
||||
let name = std::path::Path::new(target).file_name().unwrap().to_string_lossy();
|
||||
for (roots, params, shown) in [
|
||||
(&write_only, json!({"separateArtboards": true}), name.as_ref()),
|
||||
(&write_only, json!({"path": null, "separateArtboards": true}), name.as_ref()),
|
||||
(&write_only, json!({"path": own, "separateArtboards": true}), target.as_str()),
|
||||
(&both, json!({"separateArtboards": true}), target.as_str()),
|
||||
] {
|
||||
let error = confine(roots.as_ref(), || s.execute("document.save", ¶ms)).unwrap_err().to_string();
|
||||
assert_eq!(error, format!("{shown}: not a file"), "{params}");
|
||||
assert!(std::path::Path::new(target).is_dir());
|
||||
if target != &own {
|
||||
assert_eq!(std::fs::read(&own).unwrap(), primary);
|
||||
}
|
||||
assert!(s.doc().unwrap().is_dirty());
|
||||
}
|
||||
std::fs::remove_dir(target).unwrap();
|
||||
std::fs::write(target, original).unwrap();
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_multi_file_save_never_calls_the_writer() {
|
||||
use crate::cmd::fileio::save_job;
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let d = dir("refused-writer");
|
||||
let inside = d.join("in");
|
||||
let outside = d.join("out");
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let own = path(&outside, "doc.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": own})).unwrap();
|
||||
let original = std::fs::read(&own).unwrap();
|
||||
let roots = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
|
||||
for explicit in [false, true] {
|
||||
let p = if explicit { json!({"path": own, "separateArtboards": true}) } else { json!({"separateArtboards": true}) };
|
||||
let plan = save_plan(&s, SaveMode::Save, &p).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
let mut calls = 0;
|
||||
let error = confine(roots.as_ref(), || {
|
||||
job.write_unless(
|
||||
|_| None,
|
||||
|_, _| {
|
||||
calls += 1;
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert_eq!(calls, 0);
|
||||
assert!(error.contains("outside the write root"), "{error}");
|
||||
assert_eq!(error.contains(&outside.to_string_lossy().to_string()), explicit, "{error}");
|
||||
assert_eq!(std::fs::read(&own).unwrap(), original);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_svg_path_writes_svg_and_save_writes_it_back() {
|
||||
let d = dir("svg");
|
||||
|
||||
@@ -9,6 +9,23 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
#[test]
|
||||
fn postscript_suffix_recognizes_windows_filename_aliases() {
|
||||
use crate::script::dom::postscript_name;
|
||||
|
||||
for suffix in [".", " ", ". . ", "..."] {
|
||||
for prefix in ["", "/exports/", "C:\\exports\\"] {
|
||||
let name = format!("{prefix}proof.PS{suffix}");
|
||||
assert!(postscript_name(&name, true), "{name}");
|
||||
assert!(!postscript_name(&name, false), "{name}");
|
||||
}
|
||||
}
|
||||
for name in ["proof.pdf", "proof.ps\t", "proof.ps\u{a0}", "folder.ps/proof", "folder.ps\\proof"] {
|
||||
assert!(!postscript_name(name, true), "{name}");
|
||||
}
|
||||
assert!(postscript_name("proof.ps", false));
|
||||
}
|
||||
|
||||
/// A fresh folder for test `name`, by its real path, with `main` for the script.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-print-{name}-{}", std::process::id()));
|
||||
@@ -57,6 +74,95 @@ fn pages(path: &Path) -> Vec<(f64, f64)> {
|
||||
info.pages.iter().map(|p| (p.width.round(), p.height.round())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_blank_assigned_range_clears_the_saved_range() {
|
||||
let base = folder("blank-range");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap();
|
||||
for (name, range) in [("empty.pdf", ""), ("spaces.pdf", " ")] {
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
|
||||
o.jobOptions.artboardRange = '{}'; app.activeDocument.print(o);",
|
||||
quoted(&dir.join(name)),
|
||||
range
|
||||
),
|
||||
);
|
||||
assert_eq!(pages(&dir.join(name)).len(), s.active().unwrap().doc.artboards.len());
|
||||
}
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["range"], json!("1"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_uses_the_assigned_file_object_after_its_path_changes() {
|
||||
let base = folder("file-reference");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(), f = new File({}); o.jobOptions.file = f;
|
||||
vc.log(o.jobOptions.file === f); vc.log(f.changePath({}));
|
||||
app.activeDocument.print(o); vc.log(o.jobOptions.file === f);
|
||||
vc.log(f.rename('renamed.pdf')); app.activeDocument.print(o);
|
||||
o.jobOptions.file = null; vc.log(o.jobOptions.file == null);",
|
||||
quoted(&dir.join("old.pdf")),
|
||||
quoted(&dir.join("new.ps"))
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([true, true, true, true, true]));
|
||||
assert!(!dir.join("old.pdf").exists());
|
||||
assert!(!dir.join("new.ps").exists());
|
||||
assert!(std::fs::read(dir.join("renamed.pdf")).unwrap().starts_with(b"%PDF"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_custom_profile_requires_an_assigned_or_base_profile() {
|
||||
let base = folder("custom-profile-required");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let path = dir.join("custom.pdf");
|
||||
std::fs::write(&path, "original").unwrap();
|
||||
let script = format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
|
||||
o.colorManagementOptions.colorProfileMode = PrintColorProfile.CUSTOMPROFILE; app.activeDocument.print(o);",
|
||||
quoted(&path)
|
||||
);
|
||||
let error = failure(&mut s, &base, &script);
|
||||
assert!(error.contains("must name a color profile for CUSTOMPROFILE"), "{error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"original");
|
||||
s.execute("print.setup", &json!({"settings": {"color": {"profile": "sRGB IEC61966-2.1"}}})).unwrap();
|
||||
logged(&mut s, &base, &script);
|
||||
assert!(std::fs::read(&path).unwrap().starts_with(b"%PDF"));
|
||||
let preset_script = script.replace("app.activeDocument.print(o);", "o.printPreset = '[Default]'; app.activeDocument.print(o);");
|
||||
let error = failure(&mut s, &base, &preset_script);
|
||||
assert!(error.contains("must name a color profile for CUSTOMPROFILE"), "{error}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_dot_ps_file_names_write_postscript() {
|
||||
let base = folder("dot-ps");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
for name in [".ps", ".PS"] {
|
||||
let path = dir.join(name);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", quoted(&path)),
|
||||
);
|
||||
assert!(std::fs::read(&path).unwrap().starts_with(b"%!PS"));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
|
||||
let base = folder("happy");
|
||||
@@ -118,6 +224,22 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A panic while `print` has the fence open for `file.print` closes it again for the next run.
|
||||
#[test]
|
||||
fn a_panic_while_printing_leaves_the_fence_closed() {
|
||||
let base = folder("panic-unfenced");
|
||||
let mut s = session(&base);
|
||||
let print = "var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/p.pdf'); app.activeDocument.print(o);";
|
||||
crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(true));
|
||||
let r = run(&mut s, &base, print);
|
||||
crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(false));
|
||||
let e = r.map(|r| panic!("the print ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("a command past the fence failed"), "the run ends at the panic: {e}");
|
||||
let e = failure(&mut s, &base, "vc.run('file.print', {});");
|
||||
assert!(e.contains("a script cannot run"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_without_a_file_does_not_print() {
|
||||
let base = folder("no-file");
|
||||
@@ -135,6 +257,92 @@ fn print_without_a_file_does_not_print() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_print_job_file_can_be_read_and_assigned_to_another_job() {
|
||||
let base = folder("file-getter");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let path = dir.join("proof 100%.pdf");
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var first = new PrintJobOptions(), second = new PrintJobOptions();
|
||||
first.file = new File({}); second.file = first.file;
|
||||
vc.log([second.file instanceof File, second.file.fsName === first.file.fsName]);
|
||||
var o = new PrintOptions(); o.jobOptions = second; app.activeDocument.print(o);",
|
||||
quoted(&path)
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!([true, true]));
|
||||
assert!(!pages(&path).is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_scale_assignment_and_reflection_share_the_supported_range() {
|
||||
let base = folder("scale-range");
|
||||
let mut s = session(&base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var c = new PrintCoordinateOptions();
|
||||
var names = ['horizontalScale', 'verticalScale'];
|
||||
for (var i = 0; i < names.length; i++) {
|
||||
var name = names[i], info = c.reflect.find(name);
|
||||
c[name] = info.max;
|
||||
try { c[name] = info.max + 0.01; vc.log('accepted'); }
|
||||
catch (e) { vc.log([e.name, c[name] === info.max, info.max === 1000]); }
|
||||
}",
|
||||
);
|
||||
assert_eq!(out, json!([["RangeError", true, true], ["RangeError", true, true]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_fit_preserves_other_base_scaling_modes() {
|
||||
let base = folder("fit-false");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let boxes = |path: &Path| {
|
||||
let mut boxes = Vec::new();
|
||||
vectorcraft_pdf::import(&std::fs::read(path).unwrap()).unwrap().walk(|node| {
|
||||
if let Some(bounds) = node.path_data().and_then(|p| p.bounds()) {
|
||||
boxes.push(bounds);
|
||||
}
|
||||
});
|
||||
boxes
|
||||
};
|
||||
for mode in ["tileFull", "tileImageable", "custom", "fit"] {
|
||||
let settings = json!({"scaling": mode, "scale": {"width": 500, "height": 500}});
|
||||
s.execute("print.setup", &json!({"settings": settings})).unwrap();
|
||||
s.execute("print.presets.save", &json!({"name": "Base", "settings": settings})).unwrap();
|
||||
let override_settings = if mode == "fit" { json!({"scaling": "none"}) } else { json!({}) };
|
||||
let want = s.execute("file.print", &json!({"settings": override_settings, "path": dir.join("want.pdf").to_string_lossy()})).unwrap();
|
||||
for preset in [false, true] {
|
||||
if preset {
|
||||
s.execute("print.setup", &json!({"settings": {"scaling": "none"}})).unwrap();
|
||||
}
|
||||
let out = dir.join(format!("{mode}-{preset}.pdf"));
|
||||
let select = if preset { "o.printPreset = 'Base';" } else { "" };
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
|
||||
{select} o.coordinateOptions.fitToPage = false; app.activeDocument.print(o);",
|
||||
quoted(&out)
|
||||
),
|
||||
);
|
||||
let expected = boxes(&dir.join("want.pdf"));
|
||||
assert!(!expected.is_empty());
|
||||
assert_eq!(boxes(&out), expected, "{mode}, preset: {preset}");
|
||||
assert_eq!(pages(&out).len() as u64, want["pages"].as_u64().unwrap());
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Bad values throw when they are assigned, and nothing prints.
|
||||
#[test]
|
||||
fn print_options_refuse_bad_values() {
|
||||
@@ -149,8 +357,10 @@ fn print_options_refuse_bad_values() {
|
||||
("j.collate = 1;", "TypeError", "collate must be true or false"),
|
||||
("c.horizontalScale = NaN;", "TypeError", "horizontalScale"),
|
||||
("c.horizontalScale = Infinity;", "TypeError", "horizontalScale"),
|
||||
("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 10000"),
|
||||
("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 10000"),
|
||||
("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 1000"),
|
||||
("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 1000"),
|
||||
("c.horizontalScale = 1000.01;", "RangeError", "horizontalScale must be from 1 to 1000"),
|
||||
("c.verticalScale = 1000.01;", "RangeError", "verticalScale must be from 1 to 1000"),
|
||||
("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"),
|
||||
("c.orientation = 'PrintOrientation.SIDEWAYS';", "TypeError", "orientation must be a PrintOrientation value"),
|
||||
("c.orientation = 'PrintTiling.TILEFULLPAGES';", "TypeError", "orientation must be a PrintOrientation value"),
|
||||
@@ -194,10 +404,7 @@ fn options_that_are_not_available_throw() {
|
||||
("o.paperOptions.offset = 10;", "PrintPaperOptions.offset is not available yet"),
|
||||
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL1;", "PSLEVEL1 is not available yet"),
|
||||
("o.postScriptOptions.binaryPrinting = true;", "PrintPostScriptOptions.binaryPrinting is not available yet"),
|
||||
(
|
||||
&format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"),
|
||||
"horizontalScale above 1000 is not available yet",
|
||||
),
|
||||
(&format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"), "horizontalScale must be from 1 to 1000"),
|
||||
];
|
||||
let prefix = "Folder.userData; var o = new PrintOptions(), j = o.jobOptions;";
|
||||
for (case, part) in cases {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1002,6 +1002,10 @@ fn structured_junk() {
|
||||
("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})),
|
||||
("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})),
|
||||
("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})),
|
||||
("addon.arrange.match", json!({"size": "both", "rotate": true, "stacking": true, "reference": 8, "scaleStrokes": true})),
|
||||
("addon.arrange.match", json!({"source": "bottom", "size": "width", "patterns": true})),
|
||||
("addon.arrange.match", json!({"source": "key", "rotate": true})),
|
||||
("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})),
|
||||
("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
|
||||
|
||||
@@ -37,18 +37,20 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
|
||||
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
|
||||
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
|
||||
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
|
||||
("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"),
|
||||
("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"),
|
||||
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
|
||||
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
|
||||
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
|
||||
("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"),
|
||||
("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"),
|
||||
("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"),
|
||||
];
|
||||
|
||||
/// The names the host adds that stay inside the document and the run, by the object that has them.
|
||||
/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not
|
||||
/// change anything outside it. The document model (`app`, its classes and the enumerations) acts on
|
||||
/// the open documents; `Document.close` throws "not available yet". `app.open` reads the file it is
|
||||
/// given.
|
||||
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
|
||||
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
|
||||
/// `Document.path` only name its file and folder. `app.open` reads the file it is given.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "alert confirm length prompt prototype"),
|
||||
@@ -112,14 +114,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Document.", "prototype"),
|
||||
(
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close constructor convertCoordinate \
|
||||
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
|
||||
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
|
||||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace groupItems \
|
||||
groupItems= height layers layers= name pageItems paragraphStyles parent pathItems rulerOrigin \
|
||||
rulerOrigin= rulerUnits scaleFactor selection selection= stories swatches swatches= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
|
||||
groupItems= height layers layers= name pageItems paragraphStyles parent path pathItems rulerOrigin \
|
||||
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
@@ -190,7 +192,44 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
// The enumerations of saving, exporting and opening.
|
||||
("", "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint UserInteractionLevel"),
|
||||
(
|
||||
"",
|
||||
"ColorConversion ColorDestination ColorProfile Compatibility CompressionQuality DownsampleMethod EPSPostScriptLevelEnum \
|
||||
EPSPreview ExportType MonochromeCompression OutputFlattening PDFBoxType PDFChangesAllowedEnum PDFCompatibility \
|
||||
PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \
|
||||
SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel",
|
||||
),
|
||||
("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"),
|
||||
(
|
||||
"ColorDestination.",
|
||||
"COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \
|
||||
COLORDESTINATIONWORKINGRGB None",
|
||||
),
|
||||
("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"),
|
||||
(
|
||||
"CompressionQuality.",
|
||||
"AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM AUTOMATICJPEG2000MEDIUM \
|
||||
AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM \
|
||||
JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM \
|
||||
JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT",
|
||||
),
|
||||
("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"),
|
||||
("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"),
|
||||
("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"),
|
||||
(
|
||||
"PDFChangesAllowedEnum.",
|
||||
"CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE CHANGE40ANYCHANGES \
|
||||
CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT",
|
||||
),
|
||||
("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"),
|
||||
("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"),
|
||||
("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"),
|
||||
("PageMarksTypes.", "Japanese Roman"),
|
||||
("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"),
|
||||
("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"),
|
||||
("SVGDocumentEncoding.", "ASCII UTF16 UTF8"),
|
||||
("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"),
|
||||
("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"),
|
||||
(
|
||||
"Compatibility.",
|
||||
"ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \
|
||||
@@ -202,11 +241,12 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"),
|
||||
("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"),
|
||||
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
|
||||
("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"),
|
||||
("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"),
|
||||
// The print option classes and the enumerations of printing.
|
||||
(
|
||||
"",
|
||||
"FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
|
||||
"FontSubstitutionPolicy PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
|
||||
PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \
|
||||
PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \
|
||||
PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \
|
||||
@@ -267,7 +307,6 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
postScriptLevel= shadingResolution shadingResolution= typename",
|
||||
),
|
||||
("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"),
|
||||
("PageMarksTypes.", "Japanese Roman"),
|
||||
("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"),
|
||||
("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"),
|
||||
("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"),
|
||||
|
||||
@@ -88,6 +88,66 @@ fn path_of(p: &std::path::Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripted_open_converts_importer_output_to_the_requested_color_space() {
|
||||
let mut s = Session::new();
|
||||
install(&mut s, &tpl::returning(&tpl::importer("test.scriptcolorspace", r#"["tscmyk"]"#, "{}"), RECT));
|
||||
let dir = tmp_dir("scriptcolorspace");
|
||||
s.attach_script_data(dir.join("settings/Script Data"));
|
||||
let file = dir.join("drawing.tscmyk");
|
||||
std::fs::write(&file, b"importer input").unwrap();
|
||||
let script = dir.join("main.jsx");
|
||||
let path = serde_json::to_string(&file.to_string_lossy()).unwrap();
|
||||
for (argument, mode) in [
|
||||
("", vectorcraft_doc::ColorMode::Rgb),
|
||||
(", DocumentColorSpace.CMYK", vectorcraft_doc::ColorMode::Cmyk),
|
||||
(", DocumentColorSpace.RGB", vectorcraft_doc::ColorMode::Rgb),
|
||||
] {
|
||||
std::fs::write(&script, format!("Folder.userData; var d = app.open(new File({path}){argument}); vc.log(d.documentColorSpace);")).unwrap();
|
||||
let count = s.documents().len();
|
||||
let out = s.execute("script.run", &json!({"path": script.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.documents().len(), count + 1);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.color_mode, mode, "{argument}: {out}");
|
||||
let color = doc.layers[0].children().unwrap()[0].appearance.fill_paint().color().unwrap();
|
||||
if mode == vectorcraft_doc::ColorMode::Cmyk {
|
||||
assert!(matches!(color, vectorcraft_color::Color::Cmyk { .. }), "{color:?}");
|
||||
assert_eq!(out["log"], json!(["DocumentColorSpace.CMYK"]));
|
||||
} else {
|
||||
assert!(matches!(color, vectorcraft_color::Color::Rgb { .. }), "{color:?}");
|
||||
assert_eq!(out["log"], json!(["DocumentColorSpace.RGB"]));
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A script's PDF open options are refused for a file the named importer reads, which is given
|
||||
/// only the params, even when the file's extension is a PDF one.
|
||||
#[test]
|
||||
fn scripted_pdf_open_options_are_refused_for_an_importer() {
|
||||
let mut s = Session::new();
|
||||
install(&mut s, &tpl::returning(&tpl::importer("test.scriptpdfoptions", r#"["ai"]"#, "{}"), RECT));
|
||||
let dir = tmp_dir("scriptpdfoptions");
|
||||
s.attach_script_data(dir.join("settings/Script Data"));
|
||||
let file = dir.join("x.ai");
|
||||
std::fs::write(&file, b"importer input").unwrap();
|
||||
let script = dir.join("main.jsx");
|
||||
let path = serde_json::to_string(&file.to_string_lossy()).unwrap();
|
||||
for option in ["page: 1", "cropTo: 'media'", "pages: '1'", "crop: 'media'"] {
|
||||
std::fs::write(
|
||||
&script,
|
||||
format!("Folder.userData; vc.run('document.open', {{path: {path}, importer: 'plugin.test.scriptpdfoptions', {option}}});"),
|
||||
)
|
||||
.unwrap();
|
||||
let count = s.documents().len();
|
||||
let out = s.execute("script.run", &json!({"path": script.to_string_lossy()}));
|
||||
let text = format!("{out:?}");
|
||||
assert!(text.contains("PDF open options require a PDF file"), "{option}: {text}");
|
||||
assert_eq!(s.documents().len(), count, "{option}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_importer_adds_a_read_only_format_while_it_is_installed() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -103,7 +103,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
/// The text of the localization object `id` for the current locale: the string value of the first
|
||||
/// of [`Localization::keys`] that the object has as its own data property. No getter runs.
|
||||
pub(crate) fn localized_text(interp: &mut Interp, id: ObjId) -> JsResult<Option<Value>> {
|
||||
if !matches!(interp.object(id)?.class, Class::Ordinary) {
|
||||
if !matches!(interp.object(id)?.class, Class::Ordinary | Class::FsEntry(..)) {
|
||||
return Ok(None);
|
||||
}
|
||||
for k in interp.localization.keys() {
|
||||
@@ -293,11 +293,13 @@ impl Source {
|
||||
Some(Err(*length))
|
||||
}
|
||||
Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)),
|
||||
Class::Ordinary if has_symbols => return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")),
|
||||
Class::Ordinary if o.proto == Some(object_proto) && enumerable => {
|
||||
Class::Ordinary | Class::FsEntry(..) if has_symbols => {
|
||||
return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source"));
|
||||
}
|
||||
Class::Ordinary | Class::FsEntry(..) if o.proto == Some(object_proto) && enumerable => {
|
||||
Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::<Vec<_>>()))
|
||||
}
|
||||
Class::Ordinary => return Err(interp.type_error(NOT_PLAIN_OBJECT)),
|
||||
Class::Ordinary | Class::FsEntry(..) => return Err(interp.type_error(NOT_PLAIN_OBJECT)),
|
||||
_ => None,
|
||||
};
|
||||
let fixed = shape.as_ref().and(fixed_state(o));
|
||||
@@ -451,3 +453,53 @@ fn function_name(code: &Code) -> String {
|
||||
None => "[anonymous]".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::heap::{OPEN, PropMap};
|
||||
use crate::interp::Abrupt;
|
||||
|
||||
fn source_error(interp: &mut Interp, id: ObjId) -> String {
|
||||
let Err(Abrupt::Throw(error)) = write_source(interp, Value::Object(id)) else { panic!("expected a source error") };
|
||||
let Value::String(message) = interp.get_value(&error, &key("message")).unwrap() else { panic!("expected an error message") };
|
||||
message.to_rust_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_source_uses_ordinary_properties_and_guards_for_files() {
|
||||
for file in [false, true] {
|
||||
let mut interp = Interp::new(crate::Options { es2015: true, ..crate::Options::default() }, crate::Limits::default());
|
||||
let class = if file {
|
||||
let Value::String(path) = Value::str("native path") else { panic!("expected a string") };
|
||||
let mut slots = PropMap::default();
|
||||
slots.insert(key("__vcError"), Value::str(""));
|
||||
Class::FsEntry(path, Box::new(slots))
|
||||
} else {
|
||||
Class::Ordinary
|
||||
};
|
||||
let mut object = Object::new(class, Some(interp.intrinsics.object_proto));
|
||||
object.props.insert(key("label"), Prop::Data { value: Value::str("public"), flags: OPEN });
|
||||
let id = interp.heap.alloc_object(object);
|
||||
let Value::String(source) = write_source(&mut interp, Value::Object(id)).unwrap() else { panic!("expected source text") };
|
||||
assert_eq!(source.to_rust_string(), r#"({"label":"public"})"#);
|
||||
interp.object_mut(id).unwrap().props.insert(key("__vcPath"), Prop::Data { value: Value::str("own path"), flags: OPEN });
|
||||
let Value::String(source) = write_source(&mut interp, Value::Object(id)).unwrap() else { panic!("expected source text") };
|
||||
assert_eq!(source.to_rust_string(), r#"({"label":"public", "__vcPath":"own path"})"#);
|
||||
interp.object_mut(id).unwrap().proto = None;
|
||||
assert_eq!(source_error(&mut interp, id), NOT_PLAIN_OBJECT);
|
||||
interp.object_mut(id).unwrap().proto = Some(interp.intrinsics.object_proto);
|
||||
interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: 0 });
|
||||
assert_eq!(source_error(&mut interp, id), NOT_PLAIN_OBJECT);
|
||||
interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: crate::heap::ENUMERABLE });
|
||||
assert_eq!(source_error(&mut interp, id), FIXED_PROPERTY);
|
||||
interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: OPEN });
|
||||
interp.object_mut(id).unwrap().extensible = false;
|
||||
assert_eq!(source_error(&mut interp, id), NOT_EXTENSIBLE);
|
||||
interp.object_mut(id).unwrap().extensible = true;
|
||||
let symbol = interp.well_known(|w| &w.iterator).unwrap();
|
||||
interp.define_sym(id, symbol, Prop::Data { value: Value::Bool(true), flags: OPEN }).unwrap();
|
||||
assert_eq!(source_error(&mut interp, id), "toSource: an object with a Symbol property cannot be written as source");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,7 +282,7 @@ impl Interp {
|
||||
self.constructing = was;
|
||||
let v = v?;
|
||||
if let Value::Object(o) = &v
|
||||
&& matches!(self.object(*o)?.class, Class::Ordinary)
|
||||
&& matches!(self.object(*o)?.class, Class::Ordinary | Class::FsEntry(..))
|
||||
&& let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))?
|
||||
{
|
||||
self.object_mut(*o)?.proto = Some(proto);
|
||||
|
||||
+134
-26
@@ -7,10 +7,10 @@
|
||||
//! `File` and `new Folder(path)` always a `Folder`, while `File(path)` gives a `Folder` when the
|
||||
//! host's `stat` says the path is a folder, and `Folder(path)` a `File` when it is a file. Two
|
||||
//! objects for one path are different objects. An object keeps its path in the host's platform
|
||||
//! form in an internal slot that only the classes' own methods set ([`Class::FsEntry`]), so an
|
||||
//! object a script makes with `Object.create(File.prototype)` is not a `File`. It keeps its `error`
|
||||
//! text, the id of the file it has open (or -1), the encoding set before `open` and its line feed
|
||||
//! in properties that are not enumerable; every name the getters give comes from
|
||||
//! form, its `error` text, the id of the file it has open (or -1), the encoding set before `open`
|
||||
//! and its line feed in native slots that only the classes' own methods set ([`Class::FsEntry`]),
|
||||
//! so an object a script makes with `Object.create(File.prototype)` is not a `File`; every name the
|
||||
//! getters give comes from
|
||||
//! the host's `parse` of that path. `Folder.current` is kept in the realm and starts at the host's
|
||||
//! `current`.
|
||||
//!
|
||||
@@ -49,18 +49,43 @@ impl Classes {
|
||||
}
|
||||
}
|
||||
|
||||
/// The one key of the [`crate::Data`] object a host gives for a `Folder`, with the folder's path in
|
||||
/// the host's platform form as its value. A plain object a script made that carries the key is
|
||||
/// refused.
|
||||
pub const FOLDER_REF_KEY: &str = "\u{0}folderRef";
|
||||
|
||||
/// What a host gives for a `File` at `path`, in the host's platform form ([`crate::FILE_REF_KEY`]):
|
||||
/// the script receives a `File` object for it.
|
||||
pub fn file_ref(path: &str) -> crate::Data {
|
||||
crate::Data::Object(vec![(crate::FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))])
|
||||
}
|
||||
|
||||
/// What a host gives for a `Folder` at `path`, in the host's platform form: the script receives a
|
||||
/// `Folder` object for it.
|
||||
pub fn folder_ref(path: &str) -> crate::Data {
|
||||
crate::Data::Object(vec![(FOLDER_REF_KEY.to_string(), crate::Data::String(path.to_string()))])
|
||||
}
|
||||
|
||||
impl Interp {
|
||||
/// A new `File` for `path`, the path a [`crate::file_ref_path`] value a host function gives back holds.
|
||||
pub(crate) fn write_file_ref(&mut self, path: &str) -> JsResult<Value> {
|
||||
let Some(proto) = self.files.as_ref().map(|c| c.file_proto) else { return Err(self.type_error("File is not available")) };
|
||||
instance(self, proto, Value::str(path))
|
||||
/// A new `File` (or, with `folder`, a `Folder`) for `path`, a path in the host's platform form
|
||||
/// that a host gave ([`file_ref`], [`folder_ref`]). The host's `parse` reads it from
|
||||
/// `Folder.current`, as it reads the path of `new File()`, so a relative path names a file there.
|
||||
pub(crate) fn write_fs_ref(&mut self, path: &str, folder: bool) -> JsResult<Value> {
|
||||
let c = classes(self)?;
|
||||
let proto = if folder { c.folder_proto } else { c.file_proto };
|
||||
let text = Value::str(path);
|
||||
let fs = self.rooted(std::slice::from_ref(&text), |i| {
|
||||
let p = parse_text(i, text.clone(), true)?;
|
||||
i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))
|
||||
})?;
|
||||
instance(self, proto, fs)
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of `o` when the `File` or `Folder` class made it.
|
||||
fn own_path(i: &Interp, o: ObjId) -> JsResult<Option<Value>> {
|
||||
Ok(match &i.object(o)?.class {
|
||||
Class::FsEntry(s) => Some(Value::String(s.clone())),
|
||||
Class::FsEntry(s, _) => Some(Value::String(s.clone())),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
@@ -70,7 +95,7 @@ fn set_path(i: &mut Interp, o: ObjId, fs: Value) -> JsResult<()> {
|
||||
let Value::String(s) = fs else { return Err(i.type_error("File: the host gave no path")) };
|
||||
i.rooted(&[Value::Object(o), Value::String(s.clone())], |i| i.reserve_heap(string_bytes(s.len())))?;
|
||||
if let Some(ob) = i.heap.object_mut(o)
|
||||
&& let Class::FsEntry(path) = &mut ob.class
|
||||
&& let Class::FsEntry(path, _) = &mut ob.class
|
||||
{
|
||||
*path = s;
|
||||
}
|
||||
@@ -108,38 +133,50 @@ fn message(i: &mut Interp, name: &str) -> JsResult<Value> {
|
||||
/// so that a property a script put on `Object.prototype` is not read as part of it.
|
||||
fn field(i: &mut Interp, v: &Value, name: &str) -> JsResult<Value> {
|
||||
match v.as_object() {
|
||||
Some(o) => slot(i, o, name),
|
||||
Some(o) => Ok(match i.get_own_property(o, &key(name))? {
|
||||
Some(Prop::Data { value, .. }) => value,
|
||||
_ => Value::Undefined,
|
||||
}),
|
||||
None => Ok(Value::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the own data property `name` of `o`, `undefined` when it has none.
|
||||
/// The native slot `name` of `o`, or `undefined` when it has none.
|
||||
fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
Ok(match i.get_own_property(o, &key(name))? {
|
||||
Some(Prop::Data { value, .. }) => value,
|
||||
Ok(match &i.object(o)?.class {
|
||||
Class::FsEntry(_, fields) => fields.get(&key(name)).cloned().unwrap_or(Value::Undefined),
|
||||
_ => Value::Undefined,
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose
|
||||
/// path is in its [`Class::FsEntry`]. `None` for anything else, a `Folder` and an object made with
|
||||
/// `Object.create(File.prototype)` included.
|
||||
/// The path of `id` when it is a `File` the `File` class made: its prototype is `File.prototype`
|
||||
/// and it holds its path in its [`Class::FsEntry`]. `None` for anything else, a `Folder` and an
|
||||
/// object made with `Object.create(File.prototype)` included.
|
||||
pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult<Option<String>> {
|
||||
let Some(c) = &i.files else { return Ok(None) };
|
||||
if i.object(id)?.proto != Some(c.file_proto) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(own_path(i, id)?.and_then(|v| match v {
|
||||
Value::String(s) => Some(s.to_rust_string()),
|
||||
Ok(match own_path(i, id)? {
|
||||
Some(Value::String(s)) => Some(s.to_rust_string()),
|
||||
_ => None,
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> {
|
||||
if let Value::String(s) = &value {
|
||||
i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?;
|
||||
}
|
||||
i.define(o, key(name), Prop::Data { value, flags: HIDDEN })
|
||||
let Class::FsEntry(_, fields) = &i.object(o)?.class else {
|
||||
return Err(Abrupt::Internal("File slot on an object without native storage".into()));
|
||||
};
|
||||
let name = key(name);
|
||||
let added = if fields.contains(&name) { 0 } else { PROP_BYTES + string_bytes(name.len()) };
|
||||
i.rooted(&[Value::Object(o), value.clone()], |i| {
|
||||
i.reserve_heap(added)?;
|
||||
if let Class::FsEntry(_, fields) = &mut i.object_mut(o)?.class {
|
||||
fields.insert(name, value);
|
||||
i.heap.bytes = i.heap.bytes.saturating_add(added);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// The object `this` and its path, or a `TypeError` naming `what` when it is not a `File` or
|
||||
@@ -212,8 +249,10 @@ fn instance(i: &mut Interp, proto: ObjId, fs: Value) -> JsResult<Value> {
|
||||
let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) };
|
||||
let line_feed = host_value(i, "lineFeed")?;
|
||||
i.rooted(&[fs, line_feed.clone()], |i| {
|
||||
i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + string_bytes(path.len()))?;
|
||||
let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto)));
|
||||
let storage = std::mem::size_of::<crate::heap::PropMap<Value>>();
|
||||
i.reserve_heap(OBJECT_BYTES + storage + string_bytes(path.len()))?;
|
||||
let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone(), Box::default()), Some(proto)));
|
||||
i.heap.bytes = i.heap.bytes.saturating_add(storage);
|
||||
i.rooted(&[Value::Object(o)], |i| {
|
||||
set_slot(i, o, ERROR, Value::str(""))?;
|
||||
set_slot(i, o, HANDLE, Value::Number(-1.0))?;
|
||||
@@ -1393,6 +1432,75 @@ mod tests {
|
||||
assert_eq!(v.unwrap(), JsValue::String("x,/x,2,d/b,1".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_and_folders_localize_their_own_locale_properties() {
|
||||
let mut r = realm();
|
||||
r.add_script_extensions().unwrap();
|
||||
r.localization().set_locale("fr_FR");
|
||||
r.localization().set_enabled(true);
|
||||
let source = "var results = []; var constructors = [File, Folder];
|
||||
for (var n = 0; n < constructors.length; n++) {
|
||||
var C = constructors[n], f = new C('x'), hit = false;
|
||||
C.prototype.fr = 'inherited';
|
||||
results.push(localize(f) === f);
|
||||
f.en = 'English %1';
|
||||
Object.defineProperty(f, 'fr_FR', {get: function () { hit = true; return 'getter'; }, configurable: true});
|
||||
results.push(localize(f, 'text') === 'English text', !hit);
|
||||
f.fr = 'French %1';
|
||||
results.push(localize(f, 'text') === 'French text');
|
||||
results.push(Object.prototype.toString.call(f) === 'French %1');
|
||||
delete C.prototype.fr;
|
||||
}
|
||||
results.every(function (v) { return v; })";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_and_folders_copy_only_ordinary_own_properties() {
|
||||
let mut r = realm();
|
||||
let copy = HostItem::Function(Rc::new(|a: Vec<Data>| Ok(a.into_iter().next().unwrap_or(Data::Undefined))));
|
||||
r.define_host_object("host", vec![("copy".into(), copy)]).unwrap();
|
||||
let source = "var results = []; var constructors = [File, Folder];
|
||||
for (var n = 0; n < constructors.length; n++) {
|
||||
var C = constructors[n], f = new C('x');
|
||||
results.push(Object.getOwnPropertyNames(f).length === 0, Object.keys(f).length === 0);
|
||||
results.push(JSON.stringify(f) === '{}', typeof f === 'object', f instanceof C);
|
||||
results.push(Object.prototype.toString.call(f) === '[object Object]');
|
||||
f.label = 'public'; f.child = {values: [1, true]}; f.__vcPath = 'ordinary property';
|
||||
var plain = {label: 'public', child: {values: [1, true]}, __vcPath: 'ordinary property'};
|
||||
results.push(JSON.stringify(f) === JSON.stringify(plain));
|
||||
results.push(Object.keys(f).join() === Object.keys(plain).join());
|
||||
results.push(Object.getOwnPropertyNames(f).join() === Object.getOwnPropertyNames(plain).join());
|
||||
results.push(f.fsName === '/x', f.__vcPath === 'ordinary property', f.__vcHandle === undefined);
|
||||
var cloned = host.copy(f);
|
||||
results.push(JSON.stringify(cloned) === JSON.stringify(plain), cloned !== f, cloned.child !== f.child);
|
||||
results.push(Object.getPrototypeOf(cloned) === Object.prototype);
|
||||
}
|
||||
results.every(function (v) { return v; })";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_constructor_assigns_its_prototype_to_a_returned_file() {
|
||||
let mut r = realm();
|
||||
let make = Rc::new(|_: Vec<Data>| Ok(Data::Object(vec![(crate::FILE_REF_KEY.into(), Data::String("/x".into()))])));
|
||||
let copy = Rc::new(|a: Vec<Data>| Ok(a.get(1).cloned().unwrap_or(Data::Undefined)));
|
||||
let class = crate::HostClass {
|
||||
name: "ReturnedFile".into(),
|
||||
parent: None,
|
||||
members: vec![("copy".into(), crate::HostMember::Method(copy))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: Some(make),
|
||||
};
|
||||
r.define_host_classes(vec![class], Vec::new()).unwrap();
|
||||
let source = "var f = new ReturnedFile(); f.own = 'kept'; var d = new Folder('x'); d.own = 'folder';
|
||||
f instanceof ReturnedFile && Object.getPrototypeOf(f) === ReturnedFile.prototype &&
|
||||
Object.keys(f).join() === 'own' && JSON.stringify(f) === '{\"own\":\"kept\"}' &&
|
||||
JSON.stringify(f.copy(f)) === '{\"own\":\"kept\"}' && JSON.stringify(f.copy(d)) === '{\"own\":\"folder\"}'";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_constructor_picks_the_class_only_without_new() {
|
||||
let mut r = realm();
|
||||
|
||||
+20
-6
@@ -277,9 +277,9 @@ pub(crate) enum Class {
|
||||
ModuleNamespace(Box<ModuleExports>),
|
||||
/// An object of a class a host defined ([`crate::host_classes`]).
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `File` or `Folder` ([`crate::file_classes`]) and its path in the host's platform form,
|
||||
/// which only the classes' own methods set.
|
||||
FsEntry(Str),
|
||||
/// A `File` or `Folder` ([`crate::file_classes`]): its path in the host's platform form and its
|
||||
/// other native slots, which only the classes' own methods set.
|
||||
FsEntry(Str, Box<PropMap<Value>>),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
UnitValue(Box<crate::unit_value::Measure>),
|
||||
/// A promise (ECMA-262 11th edition, section 25.6) and its state.
|
||||
@@ -591,7 +591,7 @@ impl Class {
|
||||
Class::Ordinary
|
||||
| Class::ForIn(_)
|
||||
| Class::Host(_)
|
||||
| Class::FsEntry(_)
|
||||
| Class::FsEntry(..)
|
||||
| Class::Symbol(_)
|
||||
| Class::Iterator(_)
|
||||
| Class::IterRecord(_)
|
||||
@@ -1154,7 +1154,7 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
}
|
||||
extra = PROP_BYTES * exports.bindings.len();
|
||||
}
|
||||
Class::String(s) | Class::FsEntry(s) => strings.add(s),
|
||||
Class::String(s) => strings.add(s),
|
||||
Class::RegExp(re) => {
|
||||
if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) {
|
||||
strings.bytes += re.heap_bytes();
|
||||
@@ -1245,8 +1245,22 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
}
|
||||
extra = std::mem::size_of::<PropMap<Value>>() + PROP_BYTES * fields.len();
|
||||
}
|
||||
Class::FsEntry(path, fields) => {
|
||||
strings.add(path);
|
||||
for (name, value) in fields.iter() {
|
||||
strings.add_key(name);
|
||||
mark_value(value, work, strings);
|
||||
}
|
||||
extra = std::mem::size_of::<PropMap<Value>>() + PROP_BYTES * fields.len();
|
||||
}
|
||||
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
|
||||
Class::Host(h) => extra = crate::host_classes::handle_bytes(h.handle.len()),
|
||||
Class::Host(h) => {
|
||||
for (_, file, _) in &h.files {
|
||||
mark_value(file, work, strings);
|
||||
}
|
||||
extra = crate::host_classes::handle_bytes(h.handle.len())
|
||||
+ h.files.iter().map(|(name, _, path)| PROP_BYTES + name.len() + path.len()).sum::<usize>();
|
||||
}
|
||||
Class::Promise(p) => {
|
||||
for v in p.values() {
|
||||
mark_value(&v, work, strings);
|
||||
|
||||
+102
-14
@@ -119,6 +119,16 @@ pub(crate) enum ArgRead {
|
||||
/// [`Data`], objects of host classes in them as [`crate::host_ref`] gives them; the objects of
|
||||
/// host classes in the result are made from theirs.
|
||||
Hosted,
|
||||
/// A read of a host property whose reflected type is `File`.
|
||||
HostedFileGet,
|
||||
/// An assignment to a host property whose reflected type is `File`.
|
||||
HostedFileSet,
|
||||
}
|
||||
|
||||
impl ArgRead {
|
||||
fn hosted(&self) -> bool {
|
||||
matches!(self, Self::Hosted | Self::HostedFileGet | Self::HostedFileSet)
|
||||
}
|
||||
}
|
||||
|
||||
/// A member of an object the host adds to the global environment.
|
||||
@@ -275,6 +285,7 @@ impl Interp {
|
||||
if r.ancestors.len() >= r.limits.depth {
|
||||
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
|
||||
}
|
||||
// A `File` reads as its path ([`crate::FILE_REF_KEY`]).
|
||||
if r.hosted
|
||||
&& let Some(path) = crate::file_classes::file_path(self, id)?
|
||||
{
|
||||
@@ -285,7 +296,7 @@ impl Interp {
|
||||
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
|
||||
Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")),
|
||||
Class::Array { length, .. } => Shape::Array(*length),
|
||||
Class::Ordinary | Class::FsEntry(_) => {
|
||||
Class::Ordinary | Class::FsEntry(..) => {
|
||||
let o = self.object(id)?;
|
||||
if o.props.len() > r.limits.entries {
|
||||
return Err(self.data_error(r, ErrorType::Range, "has too many entries"));
|
||||
@@ -349,7 +360,7 @@ impl Interp {
|
||||
self.use_fuel()?;
|
||||
self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?;
|
||||
let name = String::from_utf16_lossy(&k);
|
||||
if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) {
|
||||
if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY || name == crate::FOLDER_REF_KEY) {
|
||||
return Err(self.data_error(r, ErrorType::Type, "is not plain data"));
|
||||
}
|
||||
r.path.push(Step::Name(k));
|
||||
@@ -373,6 +384,14 @@ impl Interp {
|
||||
if depth > self.data_limits.depth {
|
||||
return Err(self.throw(ErrorType::Range, "a host value is nested too deep"));
|
||||
}
|
||||
// A host member's `File` or `Folder` ([`crate::file_ref`], [`crate::folder_ref`]).
|
||||
if self.write_hosted
|
||||
&& let Data::Object(items) = &d
|
||||
&& let [(k, Data::String(path))] = items.as_slice()
|
||||
&& (k == crate::FILE_REF_KEY || k == crate::FOLDER_REF_KEY)
|
||||
{
|
||||
return self.write_fs_ref(path, k == crate::FOLDER_REF_KEY);
|
||||
}
|
||||
Ok(match d {
|
||||
Data::Undefined => Value::Undefined,
|
||||
Data::Null => Value::Null,
|
||||
@@ -390,12 +409,6 @@ impl Interp {
|
||||
Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => {
|
||||
self.write_host_ref(&Data::Object(items))?
|
||||
}
|
||||
Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, Data::String(_))] if k == crate::FILE_REF_KEY) => {
|
||||
match items.into_iter().next() {
|
||||
Some((_, Data::String(path))) => self.write_file_ref(&path)?,
|
||||
_ => Value::Undefined,
|
||||
}
|
||||
}
|
||||
Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?,
|
||||
})
|
||||
}
|
||||
@@ -436,9 +449,12 @@ impl Interp {
|
||||
/// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to
|
||||
/// the script.
|
||||
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, this: &Value, args: &[Value], how: &ArgRead) -> JsResult<Value> {
|
||||
if how.hosted() {
|
||||
self.sync_host_files()?;
|
||||
}
|
||||
let data = match how {
|
||||
ArgRead::Site => site_data(self.call_site()),
|
||||
ArgRead::Hosted => self.read_args(name, Some(this), args, how)?,
|
||||
how if how.hosted() => self.read_args(name, Some(this), args, how)?,
|
||||
_ => self.read_args(name, None, args, how)?,
|
||||
};
|
||||
// Only the script's own code, in a run that can pause, can wait for a result, and a host
|
||||
@@ -447,12 +463,25 @@ impl Interp {
|
||||
self.can_wait.set(can_wait);
|
||||
let result = f(data);
|
||||
self.can_wait.set(false);
|
||||
if result.is_ok()
|
||||
&& let Some(id) = this.as_object()
|
||||
{
|
||||
if matches!(how, ArgRead::HostedFileSet) {
|
||||
let file = args.first().cloned().unwrap_or(Value::Undefined);
|
||||
self.keep_host_file(id, name.clone(), file)?;
|
||||
} else if matches!(how, ArgRead::HostedFileGet)
|
||||
&& let Class::Host(h) = &self.object(id)?.class
|
||||
&& let Some((_, file, _)) = h.files.iter().find(|(n, _, _)| n == name)
|
||||
{
|
||||
return Ok(file.clone());
|
||||
}
|
||||
}
|
||||
match result {
|
||||
Ok(d) if matches!(how, ArgRead::Hosted) => self.write_hosted(d),
|
||||
Ok(d) if how.hosted() => self.write_hosted(d),
|
||||
Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)),
|
||||
Err(HostError::Wait) if can_wait => {
|
||||
self.waiting = true;
|
||||
self.waiting_hosted = matches!(how, ArgRead::Hosted);
|
||||
self.waiting_hosted = how.hosted();
|
||||
self.pause.set(true);
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
@@ -461,6 +490,59 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
fn keep_host_file(&mut self, id: ObjId, name: Rc<str>, file: Value) -> JsResult<()> {
|
||||
let path = match file.as_object() {
|
||||
Some(file) => crate::file_classes::file_path(self, file)?,
|
||||
None => None,
|
||||
};
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(()) };
|
||||
let before = h.files.iter().find(|(n, _, _)| n == &name).map_or(0, |(n, _, p)| PROP_BYTES + n.len() + p.len());
|
||||
let after = path.as_ref().map_or(0, |p| PROP_BYTES + name.len() + p.len());
|
||||
if after > before {
|
||||
self.reserve_heap(after - before)?;
|
||||
}
|
||||
self.heap.bytes = self.heap.bytes.saturating_sub(before).saturating_add(after);
|
||||
if let Class::Host(h) = &mut self.object_mut(id)?.class {
|
||||
h.files.retain(|(n, _, _)| n != &name);
|
||||
if let Some(path) = path {
|
||||
h.files.push((name, file, path));
|
||||
}
|
||||
}
|
||||
if after > 0 && !self.host_file_objects.contains(&id) {
|
||||
self.host_file_objects.push(id);
|
||||
} else if after == 0 && matches!(&self.object(id)?.class, Class::Host(h) if h.files.is_empty()) {
|
||||
self.host_file_objects.retain(|&kept| kept != id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sync_host_files(&mut self) -> JsResult<()> {
|
||||
let mut updates = Vec::new();
|
||||
for id in self.host_file_objects.clone() {
|
||||
self.use_fuel()?;
|
||||
let Some(object) = self.heap.object(id) else { continue };
|
||||
let Class::Host(h) = &object.class else { continue };
|
||||
let Some(class) = self.host_classes.get(h.class as usize) else { continue };
|
||||
for (name, file, previous) in &h.files {
|
||||
let Some(file_id) = file.as_object() else { continue };
|
||||
if crate::file_classes::file_path(self, file_id)?.as_ref() != Some(previous)
|
||||
&& let Some((_, set)) = class.file_setters.iter().find(|(n, _)| n == name)
|
||||
{
|
||||
updates.push((id, name.clone(), file.clone(), set.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, name, file, set) in updates {
|
||||
self.use_fuel()?;
|
||||
let data = self.read_args(&name, Some(&Value::Object(id)), std::slice::from_ref(&file), &ArgRead::Hosted)?;
|
||||
if let Err(error) = set(data) {
|
||||
return Err(self.host_error(error)?);
|
||||
}
|
||||
self.keep_host_file(id, name, file)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where the innermost frame of the script's code is: its source's tag and the line and column
|
||||
/// of the instruction it is running.
|
||||
fn call_site(&self) -> CallSite {
|
||||
@@ -548,7 +630,7 @@ impl Interp {
|
||||
ancestors: Vec::new(),
|
||||
path: Vec::new(),
|
||||
function: name.clone(),
|
||||
hosted: matches!(how, ArgRead::Hosted),
|
||||
hosted: how.hosted(),
|
||||
};
|
||||
let args = match how {
|
||||
ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args),
|
||||
@@ -564,14 +646,20 @@ impl Interp {
|
||||
}
|
||||
// A conversion can run the script's own `toString`, which may collect garbage.
|
||||
let mark = self.temp_roots.len();
|
||||
if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Hosted) {
|
||||
if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen) && !how.hosted() {
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
}
|
||||
let mut read = Ok(());
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX)));
|
||||
let d = match how {
|
||||
ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading),
|
||||
ArgRead::Data
|
||||
| ArgRead::DataWithin(_)
|
||||
| ArgRead::Frozen
|
||||
| ArgRead::Site
|
||||
| ArgRead::Hosted
|
||||
| ArgRead::HostedFileGet
|
||||
| ArgRead::HostedFileSet => self.read_data(a, &mut reading),
|
||||
ArgRead::Text => self.read_text(a, &mut reading),
|
||||
ArgRead::Each(list) => match list.get(i) {
|
||||
Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined),
|
||||
|
||||
@@ -117,6 +117,8 @@ pub struct HostClass {
|
||||
pub(crate) struct HostObj {
|
||||
pub(crate) class: u32,
|
||||
pub(crate) handle: Rc<[f64]>,
|
||||
/// The assigned File objects and the paths last sent to their setters.
|
||||
pub(crate) files: Vec<(Rc<str>, Value, String)>,
|
||||
}
|
||||
|
||||
/// The estimated bytes an object of a host class holds beyond [`crate::heap::OBJECT_BYTES`] for a
|
||||
@@ -146,6 +148,7 @@ pub(crate) struct Entry {
|
||||
unavailable: Rc<HashSet<Key>>,
|
||||
/// The class's own members as `reflect` lists them.
|
||||
members: Rc<[Reflected]>,
|
||||
pub(crate) file_setters: Vec<(Rc<str>, HostFunction)>,
|
||||
}
|
||||
|
||||
/// How a script may use a member of a host class.
|
||||
@@ -304,7 +307,7 @@ impl Interp {
|
||||
}
|
||||
let extra = handle_bytes(handle.len());
|
||||
self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(extra))?;
|
||||
let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto));
|
||||
let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into(), files: Vec::new() }), Some(proto));
|
||||
o.extensible = false;
|
||||
let id = self.heap.alloc_object(o);
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(extra);
|
||||
@@ -478,6 +481,17 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
|
||||
own: Rc::new(names(own_members)),
|
||||
unavailable: Rc::new(names(unavailable)),
|
||||
members,
|
||||
file_setters: class
|
||||
.members
|
||||
.iter()
|
||||
.filter_map(|(name, member)| {
|
||||
let HostMember::Property { set, .. } = member else { return None };
|
||||
if !class.info.iter().any(|(n, info)| n == name && info.data_type == "File") {
|
||||
return None;
|
||||
}
|
||||
Some((format!("{}.{name}", class.name).into(), set.clone()))
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
let global = i.global;
|
||||
i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
@@ -526,9 +540,11 @@ fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult<ObjId
|
||||
let prop = match member {
|
||||
HostMember::Get(f) => Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: ENUMERABLE },
|
||||
HostMember::Property { get, set } => {
|
||||
let get = hosted_function(i, get.clone(), &full);
|
||||
let file = class.info.iter().any(|(n, info)| n == name && info.data_type == "File");
|
||||
let get = hosted_function_read(i, get.clone(), &full, if file { ArgRead::HostedFileGet } else { ArgRead::Hosted });
|
||||
i.temp_roots.push(Value::Object(get));
|
||||
Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: ENUMERABLE }
|
||||
let set = hosted_function_read(i, set.clone(), &full, if file { ArgRead::HostedFileSet } else { ArgRead::Hosted });
|
||||
Prop::Accessor { get: Some(get), set: Some(set), flags: ENUMERABLE }
|
||||
}
|
||||
HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 },
|
||||
HostMember::Unavailable(f) => {
|
||||
@@ -551,6 +567,10 @@ fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult<ObjId
|
||||
}
|
||||
|
||||
fn hosted_function(i: &mut Interp, f: HostFunction, name: &str) -> ObjId {
|
||||
hosted_function_read(i, f, name, ArgRead::Hosted)
|
||||
}
|
||||
|
||||
fn hosted_function_read(i: &mut Interp, f: HostFunction, name: &str, read: ArgRead) -> ObjId {
|
||||
let proto = i.intrinsics.function_proto;
|
||||
i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read: ArgRead::Hosted }), Some(proto)))
|
||||
i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read }), Some(proto)))
|
||||
}
|
||||
@@ -352,6 +352,8 @@ pub(crate) struct Interp {
|
||||
/// the same one give the same object. It is not a root: an entry whose object was collected is
|
||||
/// dropped after each collection.
|
||||
pub(crate) host_objects: crate::host_classes::Made,
|
||||
/// Host objects with assigned Files stay reachable until the next script run.
|
||||
pub(crate) host_file_objects: Vec<ObjId>,
|
||||
/// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the
|
||||
/// operators take no object as a measurement.
|
||||
pub(crate) unit_values: Option<crate::unit_value::Classes>,
|
||||
@@ -679,6 +681,7 @@ impl Interp {
|
||||
host_classes: Vec::new(),
|
||||
write_hosted: false,
|
||||
host_objects: crate::host_classes::Made::default(),
|
||||
host_file_objects: Vec::new(),
|
||||
unit_values: None,
|
||||
date_host: crate::date_builtins::DateHost::default(),
|
||||
held: Rc::default(),
|
||||
@@ -964,6 +967,7 @@ impl Interp {
|
||||
roots.objects.extend(self.script_ui.iter().flat_map(crate::scriptui::Classes::objects));
|
||||
roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects));
|
||||
roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects));
|
||||
roots.objects.extend(self.host_file_objects.iter().copied());
|
||||
roots.values.extend(self.symbols.root_values());
|
||||
roots.objects.extend(self.symbols.root_objects());
|
||||
roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object));
|
||||
|
||||
@@ -168,6 +168,7 @@ pub use ast::{
|
||||
};
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use file_classes::{FOLDER_REF_KEY, file_ref, folder_ref};
|
||||
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
|
||||
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use crate::bytecode::CodeKind;
|
||||
use crate::heap::{Func, HIDDEN, Object, Prop, key};
|
||||
use crate::heap::{Class, Func, HIDDEN, Object, Prop, key};
|
||||
use crate::interp::{Abrupt, CompileError, Interp};
|
||||
use crate::module::{LinkFail, ModuleLimits, ModuleLoader};
|
||||
use crate::value::Value;
|
||||
@@ -745,6 +745,11 @@ impl Realm {
|
||||
pub fn reset_folder_current(&mut self) -> Result<(), RunError> {
|
||||
self.interp.last_thrown = Value::Undefined;
|
||||
self.interp.last_error = Value::Null;
|
||||
for id in std::mem::take(&mut self.interp.host_file_objects) {
|
||||
if let Class::Host(host) = &mut self.interp.object_mut(id).map_err(|_| internal_error("missing host file object"))?.class {
|
||||
host.files.clear();
|
||||
}
|
||||
}
|
||||
match crate::file_classes::reset_current(&mut self.interp) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => self.outcome(Err(e)).map(drop),
|
||||
|
||||
@@ -51,6 +51,7 @@ pub(crate) struct IncludeRef {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct Known {
|
||||
pub bound: HashMap<String, String>,
|
||||
pub bound_dom: HashMap<String, String>,
|
||||
pub files: HashSet<String>,
|
||||
pub folders: HashSet<String>,
|
||||
/// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts
|
||||
@@ -59,10 +60,11 @@ pub(crate) struct Known {
|
||||
}
|
||||
|
||||
impl Known {
|
||||
/// The names known, a name that may hold a File object counting twice: a Folder that becomes a
|
||||
/// possible File object ([`Known::add`]) changes it too.
|
||||
/// The names known, a chain's document-model form counting as one more and a name that may hold
|
||||
/// a File object counting twice: a Folder that becomes a possible File object ([`Known::add`])
|
||||
/// changes it too.
|
||||
pub fn len(&self) -> usize {
|
||||
self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure)
|
||||
self.bound.len() + self.bound_dom.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure)
|
||||
}
|
||||
|
||||
/// No variable holds a member chain or a File or Folder object. [`Known::unsure`] may be set.
|
||||
@@ -76,8 +78,13 @@ impl Known {
|
||||
pub fn add(&mut self, other: Known, entries: usize) {
|
||||
self.unsure |= other.unsure;
|
||||
for (name, chain) in other.bound {
|
||||
if self.bound.len() < entries || self.bound.contains_key(&name) {
|
||||
self.bound.entry(name).or_insert(chain);
|
||||
if self.bound.len() < entries
|
||||
&& let std::collections::hash_map::Entry::Vacant(entry) = self.bound.entry(name.clone())
|
||||
{
|
||||
if let Some(dom) = other.bound_dom.get(&name) {
|
||||
self.bound_dom.insert(name, dom.clone());
|
||||
}
|
||||
entry.insert(chain);
|
||||
}
|
||||
}
|
||||
for name in other.files {
|
||||
@@ -277,10 +284,69 @@ struct Assign {
|
||||
after_new: bool,
|
||||
}
|
||||
|
||||
/// `name = {`: an object literal assigned to a variable.
|
||||
struct ObjectValue {
|
||||
name: String,
|
||||
/// The bracket depth inside its `{`.
|
||||
depth: usize,
|
||||
/// The document methods writing a file that it defines with a single function expression as the
|
||||
/// key's whole value, a bit each ([`Analyzer::writers`]).
|
||||
bits: u8,
|
||||
/// It is the value of the first name a `var` statement declares, and the statement is directly
|
||||
/// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or
|
||||
/// a loop's parentheses: only then does the variable hold `bits` after it.
|
||||
whole: bool,
|
||||
/// The bit of the method whose value is being read, and how far that value has been read.
|
||||
value: Option<(u8, Value)>,
|
||||
}
|
||||
|
||||
/// How far the value of an object literal's key that names a document method writing a file has been
|
||||
/// read, by the tokens directly inside the literal's braces.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Value {
|
||||
/// `function`.
|
||||
Function,
|
||||
/// The function expression's name.
|
||||
Name,
|
||||
/// The `(` of its parameters.
|
||||
Params,
|
||||
/// The `{` of its body: the value is the function expression when `,` or the literal's `}` comes
|
||||
/// next.
|
||||
Body,
|
||||
/// Anything else, or anything after the body.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ObjectValue {
|
||||
/// `t`, a token directly inside the literal's braces: a `,` or the closing `}` ends the value
|
||||
/// being read, and gives the literal the method only when the value is a single function
|
||||
/// expression (`function () {} && d.saveAs`, `function () {}(f)` and `function () {}.call` give
|
||||
/// it nothing).
|
||||
fn step(&mut self, t: &Sig) {
|
||||
let Some((bit, value)) = self.value else { return };
|
||||
if t.is(",") || t.is("}") {
|
||||
if value == Value::Body {
|
||||
self.bits |= bit;
|
||||
} else {
|
||||
self.bits &= !bit;
|
||||
}
|
||||
self.value = None;
|
||||
return;
|
||||
}
|
||||
let next = match value {
|
||||
Value::Function if t.kind == T::Ident => Value::Name,
|
||||
Value::Function | Value::Name if t.is("(") => Value::Params,
|
||||
Value::Params if t.is("{") => Value::Body,
|
||||
_ => Value::Other,
|
||||
};
|
||||
self.value = Some((bit, next));
|
||||
}
|
||||
}
|
||||
|
||||
/// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it
|
||||
/// is a Folder object whatever the path names: [`Operand::file_step`]).
|
||||
enum Held {
|
||||
Chain(String),
|
||||
Chain { path: String, dom: Option<String> },
|
||||
File { folder: bool },
|
||||
}
|
||||
|
||||
@@ -414,12 +480,22 @@ struct Chain {
|
||||
assign: Option<String>,
|
||||
/// The grouped value ([`Group::id`]) whose operand starts with the chain.
|
||||
group: Option<usize>,
|
||||
/// The chain as the document model reads it, for telling which method is called on what: as
|
||||
/// `path`, without the echo limit, but with a string literal in brackets that names a member
|
||||
/// written as that member (`app['activeDocument']` is `app.activeDocument`). `None` once it
|
||||
/// passes [`DOM_KEY_MAX`] characters.
|
||||
dom: Option<String>,
|
||||
}
|
||||
|
||||
/// The most characters [`Chain::dom`] holds.
|
||||
const DOM_KEY_MAX: usize = 256;
|
||||
|
||||
impl Chain {
|
||||
fn new(root: String, bare: bool, line: usize) -> Self {
|
||||
let (chars, cut) = (root.chars().count(), root.ends_with('…'));
|
||||
let dom = (!cut && chars <= DOM_KEY_MAX).then(|| root.clone());
|
||||
Chain {
|
||||
dom,
|
||||
path: root,
|
||||
chars,
|
||||
cut,
|
||||
@@ -451,10 +527,23 @@ impl Chain {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `s` to [`Chain::dom`], which ends when it would pass [`DOM_KEY_MAX`] characters.
|
||||
fn append_dom(&mut self, s: &str) {
|
||||
if let Some(dom) = &mut self.dom {
|
||||
if dom.chars().count() + s.chars().count() > DOM_KEY_MAX {
|
||||
self.dom = None;
|
||||
} else {
|
||||
dom.push_str(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn member(&mut self, name: &str, cap: usize) {
|
||||
self.segments += 1;
|
||||
self.append(".", cap);
|
||||
self.append(name, cap);
|
||||
self.append_dom(".");
|
||||
self.append_dom(name);
|
||||
self.last_change = name.starts_with("set") || name.starts_with("remove");
|
||||
}
|
||||
|
||||
@@ -463,6 +552,28 @@ impl Chain {
|
||||
self.change_call |= call && self.last_change;
|
||||
self.last_change = false;
|
||||
self.append(if call { "()" } else { "[]" }, cap);
|
||||
self.append_dom(if call { "()" } else { "[]" });
|
||||
}
|
||||
|
||||
/// The index `[]` just closed held only the string literal `name`, read whole. When `name` is
|
||||
/// an identifier and the index is not one of a collection (`documents['Draft']` looks a
|
||||
/// document up by its name), [`Chain::dom`] reads `.name` there, as a member reached with a
|
||||
/// dot does. The shown `path` keeps `[]`.
|
||||
fn named_index(&mut self, name: &str) {
|
||||
let mut chars = name.chars();
|
||||
let identifier = chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
|
||||
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
|
||||
let Some(dom) = &mut self.dom else { return };
|
||||
let Some(before) = dom.strip_suffix("[]") else { return };
|
||||
let collection = before.rsplit('.').next().unwrap_or(before);
|
||||
let lookup = !catalog::OBJECT_PROTOTYPE_MEMBERS.contains(&name)
|
||||
&& catalog::DOM_COLLECTIONS.iter().any(|(c, members)| collection == *c && !members.contains(&name));
|
||||
if !identifier || lookup {
|
||||
return;
|
||||
}
|
||||
dom.truncate(before.len());
|
||||
self.append_dom(".");
|
||||
self.append_dom(name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,6 +583,8 @@ impl Chain {
|
||||
/// member chain or a File object assigned in it to an outer name stays.
|
||||
struct Scope {
|
||||
depth: usize,
|
||||
/// The offset of the body's `{` in the text, which [`Declared::looped`] names it by.
|
||||
start: usize,
|
||||
saved: HashMap<String, Saved>,
|
||||
/// The bracket depth of the `var` statement the body is in, if any: it goes on when the body
|
||||
/// closes.
|
||||
@@ -493,6 +606,8 @@ struct Catch {
|
||||
struct Saved {
|
||||
/// The member chain assigned to it.
|
||||
chain: Option<String>,
|
||||
/// The document-model form of the saved chain when it differs from the shown path.
|
||||
dom: Option<String>,
|
||||
/// It held a File or Folder object.
|
||||
file: bool,
|
||||
/// It held a Folder object.
|
||||
@@ -507,6 +622,8 @@ struct Saved {
|
||||
shadowed: Option<bool>,
|
||||
/// It was a platform name the script had a meaning of its own for.
|
||||
own: bool,
|
||||
/// What it held in [`Analyzer::writers`], 0 for nothing.
|
||||
writer: u8,
|
||||
}
|
||||
|
||||
/// The open brackets and their lines, up to [`crate::Limits::nesting`]; the brackets past that are
|
||||
@@ -556,6 +673,8 @@ struct Analyzer<'s, 'a, 'l> {
|
||||
file: Option<&'a str>,
|
||||
/// The four significant tokens before this one, the latest first.
|
||||
h: [Option<Sig<'s>>; 4],
|
||||
/// The significant token before the four of [`Self::h`].
|
||||
h4: Option<Sig<'s>>,
|
||||
brackets: Brackets,
|
||||
/// Nesting too deep to follow was reported: it is reported once.
|
||||
deep: bool,
|
||||
@@ -568,6 +687,9 @@ struct Analyzer<'s, 'a, 'l> {
|
||||
shadowed: [bool; 4],
|
||||
/// Variables assigned from a member chain, and the chain.
|
||||
bound: HashMap<String, String>,
|
||||
/// For a variable in `bound`, the chain as the document model reads it ([`Chain::dom`]) when it
|
||||
/// differs from the chain shown.
|
||||
bound_dom: HashMap<String, String>,
|
||||
/// Variables holding a File or Folder object.
|
||||
files: HashSet<String>,
|
||||
/// The variables in `files` holding a Folder object whatever the path names ([`Held::File`]).
|
||||
@@ -578,6 +700,25 @@ struct Analyzer<'s, 'a, 'l> {
|
||||
maybe_files: HashSet<String>,
|
||||
/// `maybe_files` ran out of room: no variable counts as holding a Folder object.
|
||||
maybe_files_full: bool,
|
||||
/// The variables holding an object literal of the script's own that defines a method named as a
|
||||
/// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit
|
||||
/// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing.
|
||||
writers: HashMap<String, u8>,
|
||||
/// The object literals being assigned to a variable, the innermost last, up to
|
||||
/// [`crate::Limits::nesting`] of them.
|
||||
objects: Vec<ObjectValue>,
|
||||
/// An object literal whose `}` the last token was, with the methods it defines: the variable
|
||||
/// holds them when the next token ends the `var` statement's value.
|
||||
closed: Option<(String, u8)>,
|
||||
/// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver
|
||||
/// that is not such a variable.
|
||||
index_receiver: u8,
|
||||
/// The variables that may get another value when code read elsewhere runs: assigned inside a
|
||||
/// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]).
|
||||
/// None of them joins [`Analyzer::writers`].
|
||||
later: HashSet<String>,
|
||||
/// `later` ran out of room: no variable joins [`Analyzer::writers`].
|
||||
later_full: bool,
|
||||
/// This file or what the scan started with gives names values the analysis doesn't read
|
||||
/// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names.
|
||||
unsure: bool,
|
||||
@@ -641,6 +782,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
acc,
|
||||
file,
|
||||
h: [None; 4],
|
||||
h4: None,
|
||||
brackets: Brackets::default(),
|
||||
deep: false,
|
||||
active: None,
|
||||
@@ -648,12 +790,19 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
suspend: false,
|
||||
shadowed: [false; 4],
|
||||
bound: known.bound.clone(),
|
||||
bound_dom: known.bound_dom.clone(),
|
||||
files: known.files.clone(),
|
||||
folders: known.folders.clone(),
|
||||
// A variable of the same name as a property a member assignment writes may be that
|
||||
// property of the global object.
|
||||
maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(),
|
||||
maybe_files_full: false,
|
||||
writers: HashMap::new(),
|
||||
objects: vec![],
|
||||
closed: None,
|
||||
index_receiver: 0,
|
||||
later: HashSet::new(),
|
||||
later_full: false,
|
||||
unsure: known.unsure || declared.unsure,
|
||||
own_names: HashSet::new(),
|
||||
scopes: vec![],
|
||||
@@ -738,6 +887,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
// `t` ends, holds the value, or nothing the check follows, before `t` starts a member chain or
|
||||
// closes a function body.
|
||||
self.settle_groups(&t);
|
||||
self.settle_literal(&t);
|
||||
// A line break ends a `var` statement when it is outside the statement's brackets, and the
|
||||
// tokens on either side of it don't go on with the expression.
|
||||
if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(self.h[0]) && !goes_on_with(&t) {
|
||||
@@ -760,9 +910,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.group_step(&t, started, before);
|
||||
self.paren_step(&t, before);
|
||||
self.assignment(&t, started);
|
||||
self.object_key(&t, before);
|
||||
self.features(&t);
|
||||
self.newer(&t);
|
||||
self.module_check(&t);
|
||||
self.h4 = self.h[3];
|
||||
self.h = [Some(t), self.h[0], self.h[1], self.h[2]];
|
||||
}
|
||||
|
||||
@@ -806,7 +958,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
self.active = Some(Chain::new(root, bare, t.line));
|
||||
let mut c = Chain::new(root, bare, t.line);
|
||||
if let Some(dom) = self.bound_dom.get(t.text).filter(|_| self.bound.contains_key(t.text)) {
|
||||
c.dom = Some(dom.clone());
|
||||
}
|
||||
self.active = Some(c);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -844,22 +1000,28 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
&& g.id == id
|
||||
&& matches!(g.operand, Operand::Chain)
|
||||
{
|
||||
g.operand = Operand::Done(Held::Chain(c.path.clone()));
|
||||
g.operand = Operand::Done(Held::Chain { path: c.path.clone(), dom: c.dom.clone() });
|
||||
}
|
||||
if let Some(name) = c.assign {
|
||||
let ends = ending.is_none_or(ends_value);
|
||||
if ends && !key {
|
||||
self.bind(name, c.path);
|
||||
self.bind(name, c.path, c.dom);
|
||||
} else {
|
||||
self.unbind(&name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self, name: String, path: String) {
|
||||
/// `name` holds the chain `path`, which the document model reads as `dom` when that differs.
|
||||
fn bind(&mut self, name: String, path: String, dom: Option<String>) {
|
||||
self.files.remove(&name);
|
||||
self.folders.remove(&name);
|
||||
self.writers.remove(&name);
|
||||
self.bound_dom.remove(&name);
|
||||
if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) {
|
||||
if let Some(dom) = dom.filter(|d| *d != path) {
|
||||
self.bound_dom.insert(name.clone(), dom);
|
||||
}
|
||||
self.bound.insert(name, path);
|
||||
}
|
||||
}
|
||||
@@ -867,7 +1029,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
/// `name` holds a File or Folder object (`folder` for a Folder object whatever the path names).
|
||||
fn hold_file(&mut self, name: String, folder: bool) {
|
||||
self.bound.remove(&name);
|
||||
self.bound_dom.remove(&name);
|
||||
self.folders.remove(&name);
|
||||
self.writers.remove(&name);
|
||||
if !folder && !self.maybe_files.contains(&name) {
|
||||
if self.acc.room(self.maybe_files.len()) {
|
||||
self.maybe_files.insert(name.clone());
|
||||
@@ -985,20 +1149,26 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
let shadowed = catalog::DOM_ROOTS.iter().position(|r| *r == name).and_then(|i| self.shadowed.get(i).copied());
|
||||
Saved {
|
||||
chain: self.bound.get(name).cloned(),
|
||||
dom: self.bound_dom.get(name).cloned(),
|
||||
file: self.files.contains(name),
|
||||
folder: self.folders.contains(name),
|
||||
maybe_file: self.maybe_files.contains(name),
|
||||
local: false,
|
||||
shadowed,
|
||||
own: self.own_names.contains(name),
|
||||
writer: self.writers.get(name).copied().unwrap_or(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` holds `saved` again.
|
||||
fn restore(&mut self, name: String, saved: Saved) {
|
||||
self.acc.steps = self.acc.steps.saturating_add(1);
|
||||
self.bound_dom.remove(&name);
|
||||
match saved.chain {
|
||||
Some(chain) => {
|
||||
if let Some(dom) = saved.dom {
|
||||
self.bound_dom.insert(name.clone(), dom);
|
||||
}
|
||||
self.bound.insert(name.clone(), chain);
|
||||
}
|
||||
None => {
|
||||
@@ -1025,6 +1195,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
} else {
|
||||
self.own_names.remove(&name);
|
||||
}
|
||||
// An outer variable the body assigned keeps only the methods it still has: the body may have
|
||||
// given it another value.
|
||||
let writer = if saved.local { saved.writer } else { saved.writer & self.writers.get(&name).copied().unwrap_or(0) };
|
||||
if writer != 0 {
|
||||
self.writers.insert(name.clone(), writer);
|
||||
} else {
|
||||
self.writers.remove(&name);
|
||||
}
|
||||
if let Some(hidden) = saved.shadowed
|
||||
&& let Some(i) = catalog::DOM_ROOTS.iter().position(|r| *r == name)
|
||||
&& let Some(s) = self.shadowed.get_mut(i)
|
||||
@@ -1072,8 +1250,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
fn empty(&mut self, name: &str) {
|
||||
self.make_own(name);
|
||||
self.bound.remove(name);
|
||||
self.bound_dom.remove(name);
|
||||
self.files.remove(name);
|
||||
self.folders.remove(name);
|
||||
self.writers.remove(name);
|
||||
self.hide_root(name);
|
||||
}
|
||||
|
||||
@@ -1134,7 +1314,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
if body {
|
||||
let params = self.params.take().map(|(_, names)| names).unwrap_or_default();
|
||||
if self.scopes.len() < self.acc.limits.nesting {
|
||||
self.scopes.push(Scope { depth: self.depth(), saved: HashMap::new(), var_depth: self.var_depth.take() });
|
||||
self.scopes.push(Scope { depth: self.depth(), start: t.start, saved: HashMap::new(), var_depth: self.var_depth.take() });
|
||||
// The parameters are the body's own names, and so are the names it declares.
|
||||
for name in params {
|
||||
self.acc.steps = self.acc.steps.saturating_add(1);
|
||||
@@ -1156,6 +1336,19 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
if self.suspended.last().is_some_and(|c| c.wait == self.depth()) {
|
||||
self.active = self.suspended.pop();
|
||||
// `app['activeDocument']` reads as `app.activeDocument` in the chain's
|
||||
// `dom`. A key longer than `DOM_KEY_MAX` characters is not read whole.
|
||||
if t.text == "]"
|
||||
&& is(self.h[1], "[")
|
||||
&& let Some(s) = self.h[0].filter(|s| s.kind == T::Str)
|
||||
{
|
||||
let name = unquote(s.text, DOM_KEY_MAX + 1);
|
||||
if name.chars().count() <= DOM_KEY_MAX
|
||||
&& let Some(c) = self.active.as_mut()
|
||||
{
|
||||
c.named_index(&name);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.close_scopes();
|
||||
let grouped = self.close_parens(t);
|
||||
@@ -1261,12 +1454,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
let Some(c) = self.catches.get_mut(i) else { return };
|
||||
let empty = Saved {
|
||||
chain: None,
|
||||
dom: None,
|
||||
file: false,
|
||||
folder: false,
|
||||
maybe_file: false,
|
||||
local: false,
|
||||
shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true),
|
||||
own: platform_name(name),
|
||||
writer: 0,
|
||||
};
|
||||
let outside = std::mem::replace(&mut c.saved, empty);
|
||||
if let Some(scope) = self.scopes.last_mut() {
|
||||
@@ -1290,6 +1485,21 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.start_value(a.name, Operand::Done(Held::File { folder: false }));
|
||||
} else if !a.after_new && t.is("(") {
|
||||
self.start_group(a.name);
|
||||
} else if !a.after_new && t.is("{") {
|
||||
// An object literal: its keys are read at the depth inside its `{` ([`Self::object_key`]).
|
||||
self.unbind(&a.name);
|
||||
let [_, _, declaration, before] = self.h;
|
||||
let depth = self.depth();
|
||||
let body = self.scopes.last().map_or(0, |s| s.depth);
|
||||
let starts = before.is_none()
|
||||
|| [";", "{", "}"].iter().any(|p| is(before, p))
|
||||
// A line break after a label's `:` does not end the statement the label may be
|
||||
// the body of (`if (c) l:` before the line).
|
||||
|| (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do"));
|
||||
let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body);
|
||||
if self.objects.len() < self.acc.limits.nesting {
|
||||
self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None });
|
||||
}
|
||||
} else {
|
||||
self.unbind(&a.name);
|
||||
}
|
||||
@@ -1316,9 +1526,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
// A name after `.`, `..`, `.@`, `::` or `@` is a property's or an attribute's; any other
|
||||
// name before `=` is a variable, at the start of a statement or inside an expression.
|
||||
if !member_mark(h1) && !is(h1, "@") {
|
||||
if !self.scopes.is_empty() && !self.declared_in_body(name.text) {
|
||||
self.reassigned_later(name.text);
|
||||
}
|
||||
self.assign = Some(Assign { name: name.text.to_string(), after_new: false });
|
||||
}
|
||||
}
|
||||
if let Some((name, _)) = self.updated(t)
|
||||
&& !self.scopes.is_empty()
|
||||
&& !self.declared_in_body(name)
|
||||
{
|
||||
self.reassigned_later(name);
|
||||
}
|
||||
match self.updated(t) {
|
||||
// The value on the right is read at this depth, and the name holds nothing the check
|
||||
// follows once that value ends ([`Analyzer::settle_groups`]).
|
||||
@@ -1328,6 +1547,85 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins
|
||||
/// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t`
|
||||
/// closes a function body, so a literal given to the body's own variable stays inside the body.
|
||||
/// Calls inside a loop that assigns the variable use [`Declared::looped`] to classify its methods.
|
||||
fn settle_literal(&mut self, t: &Sig<'s>) {
|
||||
if let Some((name, bits)) = self.closed.take()
|
||||
&& (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t)))
|
||||
&& !self.later_full
|
||||
&& !self.later.contains(&name)
|
||||
&& !self.declared.looped_full
|
||||
&& (self.writers.contains_key(&name) || self.acc.room(self.writers.len()))
|
||||
{
|
||||
self.writers.insert(name, bits);
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` may get another value when code read elsewhere runs: a function body assigns it without
|
||||
/// declaring it, and the function may be called before or after any line, or it is assigned as a
|
||||
/// property of `this`. Its object literal's methods are no longer known, now or later.
|
||||
fn reassigned_later(&mut self, name: &str) {
|
||||
self.writers.remove(name);
|
||||
if !self.later.contains(name) {
|
||||
if self.acc.room(self.later.len()) {
|
||||
self.later.insert(name.to_string());
|
||||
} else {
|
||||
self.later_full = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The global variable `name` is assigned as a property of `this`: as [`Self::reassigned_later`],
|
||||
/// and when a function body's own variable hides it, the global's methods saved for the body's
|
||||
/// end are no longer known either.
|
||||
pub(super) fn reassigned_global(&mut self, name: &str) {
|
||||
self.reassigned_later(name);
|
||||
if let Some(saved) = self.scopes.iter_mut().find_map(|s| s.saved.get_mut(name)) {
|
||||
saved.writer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` is declared in the innermost function body (`var name`, `function
|
||||
/// name`, a parameter).
|
||||
fn declared_in_body(&self, name: &str) -> bool {
|
||||
self.scopes.last().is_some_and(|s| s.saved.get(name).is_some_and(|v| v.local))
|
||||
}
|
||||
|
||||
/// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single
|
||||
/// function expression directly inside its braces as the whole value of a key that names a
|
||||
/// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`)
|
||||
/// counts the method for the literal, and any other value of that key (`{saveAs: d.saveAs}`,
|
||||
/// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing
|
||||
/// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the
|
||||
/// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on
|
||||
/// (`{…} && d`), see the variable as it was.
|
||||
fn object_key(&mut self, t: &Sig<'s>, before: usize) {
|
||||
if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) {
|
||||
o.step(t);
|
||||
}
|
||||
let depth = self.depth();
|
||||
while let Some(o) = self.objects.pop_if(|o| o.depth > depth) {
|
||||
if o.whole && o.bits != 0 && o.depth == depth.saturating_add(1) {
|
||||
self.closed = Some((o.name, o.bits));
|
||||
}
|
||||
}
|
||||
let [h0, h1, h2, _] = self.h;
|
||||
if !is(h0, ":") || !(is(h2, "{") || is(h2, ",")) {
|
||||
return;
|
||||
}
|
||||
let key = match h1 {
|
||||
Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text),
|
||||
Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)),
|
||||
_ => return,
|
||||
};
|
||||
let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return };
|
||||
// A value that starts with a bracket has opened it already: the key is at the depth before it.
|
||||
let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) else { return };
|
||||
o.value = Some((1 << i, if t.word("function") { Value::Function } else { Value::Other }));
|
||||
}
|
||||
|
||||
/// The variable that `t` changes to a number or a string, nothing the check follows, and whether
|
||||
/// the change waits for the value on the right. `name += …` and the other compound assignments
|
||||
/// (ECMA-262 3rd edition, section 11.13.2) store their result after that value is read, so the
|
||||
@@ -1501,7 +1799,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
fn settle(&mut self, g: Group, ends: bool) {
|
||||
let complete = (g.closed || g.bare) && ends;
|
||||
match g.operand {
|
||||
Operand::Done(Held::Chain(path)) if complete => self.bind(g.name, path),
|
||||
Operand::Done(Held::Chain { path, dom }) if complete => self.bind(g.name, path, dom),
|
||||
Operand::Done(Held::File { folder }) | Operand::FileName { new: true, folder } if complete => self.hold_file(g.name, folder),
|
||||
_ => self.unbind(&g.name),
|
||||
}
|
||||
@@ -1542,6 +1840,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.var_depth = None;
|
||||
self.conds.clear();
|
||||
self.h = [None; 4];
|
||||
self.h4 = None;
|
||||
self.acc.steps = self.acc.steps.saturating_add(1);
|
||||
let d = directives::parse(t.text);
|
||||
let Some(name) = d.known else {
|
||||
@@ -1588,7 +1887,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
// A variable that any assignment gave a value that may be a File object leaves as one.
|
||||
let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect();
|
||||
let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders, unsure: self.unsure };
|
||||
let known = Known {
|
||||
bound: std::mem::take(&mut self.bound),
|
||||
bound_dom: std::mem::take(&mut self.bound_dom),
|
||||
files: std::mem::take(&mut self.files),
|
||||
folders,
|
||||
unsure: self.unsure,
|
||||
};
|
||||
(std::mem::take(&mut self.includes), module, known)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The names declared, read before the analysis.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word};
|
||||
|
||||
@@ -14,10 +14,41 @@ const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_E
|
||||
/// The property a function reaches `Function` through.
|
||||
const CONSTRUCTOR: &str = "constructor";
|
||||
|
||||
/// The statements whose parentheses the rest of the statement follows, so a line break after them
|
||||
/// does not end a loop's body without braces.
|
||||
const HEADS: &[&str] = &["if", "while", "for", "with", "switch"];
|
||||
|
||||
/// The longest property name, in characters, that [`Declared::rebound`] keeps. A string literal in
|
||||
/// brackets that spells a longer one sets [`Declared::unsure`].
|
||||
const PROPERTY_CHARS: usize = 256;
|
||||
|
||||
#[cfg(not(test))]
|
||||
type LoopSpans = Vec<(usize, usize)>;
|
||||
|
||||
#[cfg(test)]
|
||||
#[derive(Default)]
|
||||
pub(super) struct LoopSpans {
|
||||
spans: Vec<(usize, usize)>,
|
||||
reads: std::cell::Cell<usize>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl std::ops::Deref for LoopSpans {
|
||||
type Target = Vec<(usize, usize)>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.reads.set(self.reads.get() + 1);
|
||||
&self.spans
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl std::ops::DerefMut for LoopSpans {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.spans
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a file's function bodies and its global code declare, read before the analysis. A
|
||||
/// function's `var` statements and the function declarations directly in its body make the names
|
||||
/// they declare the function's own before any statement in it runs, and the function declarations
|
||||
@@ -36,6 +67,16 @@ pub(crate) struct Declared<'s> {
|
||||
/// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be
|
||||
/// the global object, so a variable of that name may get a value the analysis doesn't read.
|
||||
pub(super) rebound: HashSet<String>,
|
||||
/// The variables assigned inside a loop, its parentheses included (`name = …`), each by the
|
||||
/// offset of the `{` of the function body that declares it (`None`: the global code's), with the
|
||||
/// outermost loops that assign it, entries of `loop_spans`.
|
||||
pub(super) looped: HashMap<(Option<usize>, &'s str), Vec<usize>>,
|
||||
/// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at
|
||||
/// the end of the text).
|
||||
pub(super) loop_spans: LoopSpans,
|
||||
/// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any
|
||||
/// variable may be assigned in a loop.
|
||||
pub(super) looped_full: bool,
|
||||
/// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or
|
||||
/// a `constructor` property used, a property read, called or assigned whose name in brackets is
|
||||
/// not one string or number literal, which may be a variable's name on the global object
|
||||
@@ -46,14 +87,23 @@ pub(crate) struct Declared<'s> {
|
||||
pub(super) unsure: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl Declared<'_> {
|
||||
pub(crate) fn loop_span_reads(&self) -> usize {
|
||||
self.loop_spans.reads.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in
|
||||
/// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement
|
||||
/// the body is in, which goes on when the body closes.
|
||||
/// the body is in, which goes on when the body closes, and the names assigned in a loop inside it
|
||||
/// so far, each with its loops ([`Declared::looped`]).
|
||||
struct Body<'s> {
|
||||
depth: usize,
|
||||
index: usize,
|
||||
names: HashSet<&'s str>,
|
||||
var_depth: Option<usize>,
|
||||
looped: HashMap<&'s str, Vec<usize>>,
|
||||
}
|
||||
|
||||
/// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in
|
||||
@@ -87,9 +137,46 @@ struct Declarations<'s, 'a, 'l> {
|
||||
untracked: Option<usize>,
|
||||
/// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`].
|
||||
keys: Vec<Key>,
|
||||
/// The loops being read, the innermost last, up to [`crate::Limits::nesting`].
|
||||
loops: Vec<Loop>,
|
||||
out: Declared<'s>,
|
||||
}
|
||||
|
||||
/// A loop [`Declarations`] is reading: the bracket depth of its keyword, how far it has been read,
|
||||
/// and, for a body without braces, whether the last `{` at that depth opened a block (not an object
|
||||
/// literal), whether an `if`, `while`, `for` or `with` at that depth waits for its `)`, and whether
|
||||
/// the last token was that `)`.
|
||||
struct Loop {
|
||||
depth: usize,
|
||||
stage: Stage,
|
||||
block: bool,
|
||||
head: bool,
|
||||
after_head: bool,
|
||||
/// The loop starts with `do` and has a trailing condition.
|
||||
do_loop: bool,
|
||||
}
|
||||
|
||||
/// How far a [`Loop`] has been read.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Stage {
|
||||
/// The parentheses after `for` or `while`.
|
||||
Head,
|
||||
/// The parentheses after the `while` of a `do` loop.
|
||||
DoHead,
|
||||
/// The `)` of a `do` loop's `while` was read: the loop ends with the `;` after it, or before the
|
||||
/// next token.
|
||||
DoEnd,
|
||||
/// The body's first token is next.
|
||||
Start,
|
||||
/// A body in braces.
|
||||
Block,
|
||||
/// A body that is one statement without braces.
|
||||
Statement,
|
||||
/// The statement of a body without braces has reached its end: the loop ends at the next token,
|
||||
/// unless it is `else`, `catch` or `finally`, which go on with the statement.
|
||||
Tail,
|
||||
}
|
||||
|
||||
/// What `src` declares ([`Declared`]), read in one pass over its tokens.
|
||||
pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
let mut lexer = Lexer::new(src, acc.limits.nesting);
|
||||
@@ -103,6 +190,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
bodies: vec![],
|
||||
untracked: None,
|
||||
keys: vec![],
|
||||
loops: vec![],
|
||||
out: Declared::default(),
|
||||
};
|
||||
let mut breaks = LineBreaks::default();
|
||||
@@ -113,7 +201,15 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
Read::Token(sig) => d.token(sig),
|
||||
}
|
||||
}
|
||||
// A body the file does not close keeps its names assigned in a loop as well.
|
||||
while let Some(body) = d.bodies.pop() {
|
||||
d.settle_looped(body);
|
||||
}
|
||||
let mut out = d.out;
|
||||
for ids in out.looped.values_mut() {
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
}
|
||||
out.unsure |= out.rebound.contains(catalog::FOLDER);
|
||||
acc.steps = acc.steps.saturating_add(lexer.steps);
|
||||
out
|
||||
@@ -138,12 +234,22 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) {
|
||||
self.var_depth = None;
|
||||
}
|
||||
self.loop_start(&t);
|
||||
if t.kind == T::Punct {
|
||||
self.bracket(&t);
|
||||
} else if t.kind == T::Ident {
|
||||
self.declaration(&t);
|
||||
}
|
||||
let depth = self.depth();
|
||||
self.loop_end(&t, depth);
|
||||
if t.is("=")
|
||||
&& !self.loops.is_empty()
|
||||
&& !member_mark(h1)
|
||||
&& !is(h1, "@")
|
||||
&& let Some(name) = h0.filter(|s| s.kind == T::Ident)
|
||||
{
|
||||
self.looped(name.text);
|
||||
}
|
||||
if let Some(after_new) = self.assign.take() {
|
||||
if t.word("new") && !after_new {
|
||||
self.assign = Some(true);
|
||||
@@ -167,6 +273,209 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
self.h = [Some(t), h0, h1];
|
||||
}
|
||||
|
||||
/// `t`, a token before the brackets are followed past it: the body of the innermost loop starts
|
||||
/// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any
|
||||
/// variable may be assigned in one ([`Declared::looped_full`]).
|
||||
fn loop_start(&mut self, t: &Sig<'s>) {
|
||||
let [h0, h1, ..] = self.h;
|
||||
let depth = self.depth();
|
||||
while let Some(l) = self.loops.last_mut() {
|
||||
let after_head = std::mem::take(&mut l.after_head);
|
||||
match l.stage {
|
||||
Stage::Start => {
|
||||
l.stage = if t.is("{") { Stage::Block } else { Stage::Statement };
|
||||
l.head = HEADS.iter().any(|w| t.word(w)) && !member_mark(h0);
|
||||
break;
|
||||
}
|
||||
// A line break ends a body of one statement where the tokens on either side of it
|
||||
// don't go on with it, as in [`Analyzer::token`], and it does not follow the
|
||||
// parentheses of an `if` or another statement that the body goes on with.
|
||||
Stage::Statement
|
||||
if t.nl
|
||||
&& depth == l.depth
|
||||
&& !goes_on_after(h0)
|
||||
&& !goes_on_with(t)
|
||||
&& !after_head
|
||||
&& !["else", "do", "catch", "finally"].iter().any(|w| word(h0, w) && !member_mark(h1)) =>
|
||||
{
|
||||
l.stage = Stage::Tail;
|
||||
}
|
||||
Stage::Statement => {
|
||||
if depth == l.depth {
|
||||
if t.is("{") {
|
||||
l.block = t.stmt || after_head || word(h0, "else") || (word(h0, "finally") && !member_mark(h1));
|
||||
} else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) {
|
||||
l.head = true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
Stage::Tail if l.do_loop && t.word("while") => {
|
||||
l.stage = Stage::DoHead;
|
||||
return;
|
||||
}
|
||||
Stage::Tail if t.word("else") => {
|
||||
l.stage = Stage::Statement;
|
||||
break;
|
||||
}
|
||||
// The `catch` and `finally` of a `try` statement that is the body go on with it.
|
||||
Stage::Tail if t.word("catch") || t.word("finally") => {
|
||||
l.stage = Stage::Statement;
|
||||
l.head = t.word("catch");
|
||||
break;
|
||||
}
|
||||
Stage::DoEnd if t.is(";") && depth == l.depth => break,
|
||||
Stage::Tail | Stage::DoEnd => {
|
||||
self.pop_loop(t.start);
|
||||
// A body of one statement that is this loop ends with it.
|
||||
if let Some(outer) = self.loops.last_mut()
|
||||
&& outer.stage == Stage::Statement
|
||||
&& outer.depth == depth
|
||||
{
|
||||
outer.stage = Stage::Tail;
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
let stage = if (t.word("for") || t.word("while")) && !member_mark(h0) {
|
||||
Stage::Head
|
||||
} else if t.word("do") && !member_mark(h0) {
|
||||
Stage::Start
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
if self.loops.len() >= self.acc.limits.nesting || (self.loops.is_empty() && !self.acc.room(self.out.loop_spans.len())) {
|
||||
self.out.looped_full = true;
|
||||
} else {
|
||||
if self.loops.is_empty() {
|
||||
self.out.loop_spans.push((t.start, usize::MAX));
|
||||
}
|
||||
self.loops.push(Loop { depth, stage, block: false, head: false, after_head: false, do_loop: t.word("do") });
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the innermost loop at offset `at`, which ends the outermost one in
|
||||
/// [`Declared::loop_spans`].
|
||||
fn pop_loop(&mut self, at: usize) {
|
||||
self.loops.pop();
|
||||
if self.loops.is_empty()
|
||||
&& let Some((_, end)) = self.out.loop_spans.last_mut()
|
||||
{
|
||||
*end = at;
|
||||
}
|
||||
}
|
||||
|
||||
/// `t`, after the brackets are followed past it to `depth`: the parentheses of a loop end at the
|
||||
/// `)` back at its depth, and a body in braces at the `}` back at it. A body of one statement
|
||||
/// reaches its end ([`Stage::Tail`]) at a `;` at the loop's depth, at a `}` there that closes a
|
||||
/// block, or with a loop that is that statement. A bracket closing below a loop's depth ends it.
|
||||
fn loop_end(&mut self, t: &Sig<'s>, depth: usize) {
|
||||
let mut inner = false;
|
||||
while let Some(l) = self.loops.last_mut() {
|
||||
let ended = depth < l.depth
|
||||
|| match l.stage {
|
||||
Stage::Head => {
|
||||
if t.is(")") && depth == l.depth {
|
||||
l.stage = Stage::Start;
|
||||
}
|
||||
false
|
||||
}
|
||||
Stage::DoHead => {
|
||||
if t.is(")") && depth == l.depth {
|
||||
l.stage = Stage::DoEnd;
|
||||
}
|
||||
false
|
||||
}
|
||||
Stage::DoEnd => t.is(";") && depth == l.depth,
|
||||
Stage::Block => {
|
||||
if t.is("}") && depth == l.depth && l.do_loop {
|
||||
l.stage = Stage::Tail;
|
||||
false
|
||||
} else {
|
||||
t.is("}") && depth == l.depth
|
||||
}
|
||||
}
|
||||
Stage::Statement => {
|
||||
if depth == l.depth {
|
||||
if t.is(";") || (t.is("}") && l.block) || inner {
|
||||
l.stage = Stage::Tail;
|
||||
} else if t.is(")") && l.head {
|
||||
l.head = false;
|
||||
l.after_head = true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
Stage::Start | Stage::Tail => false,
|
||||
};
|
||||
if !ended {
|
||||
break;
|
||||
}
|
||||
self.pop_loop(t.start);
|
||||
inner = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` is assigned in the loops being read: kept with the outermost one for the innermost
|
||||
/// function body that declares it when that body closes ([`Self::settle_looped`]), or for the
|
||||
/// global code.
|
||||
fn looped(&mut self, name: &'s str) {
|
||||
let id = self.out.loop_spans.len().saturating_sub(1);
|
||||
match self.bodies.last_mut() {
|
||||
Some(body) if body.looped.contains_key(name) || self.acc.room(body.looped.len()) => {
|
||||
let ids = body.looped.entry(name).or_default();
|
||||
if !ids.contains(&id) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
Some(_) => self.out.looped_full = true,
|
||||
None => self.keep_looped(None, name, vec![id]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The names assigned in a loop inside `body`, which is closing: the body's own are kept for it,
|
||||
/// and the others go to the body around it, or to the global code.
|
||||
fn settle_looped(&mut self, body: Body<'s>) {
|
||||
let start = self.out.bodies.get(body.index).map(|(at, _)| *at);
|
||||
for (name, ids) in body.looped {
|
||||
if body.names.contains(name) {
|
||||
self.keep_looped(start, name, ids);
|
||||
} else if let Some(outer) = self.bodies.last_mut() {
|
||||
if outer.looped.contains_key(name) || self.acc.room(outer.looped.len()) {
|
||||
let kept = outer.looped.entry(name).or_default();
|
||||
for id in ids {
|
||||
if !kept.contains(&id) {
|
||||
kept.push(id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.out.looped_full = true;
|
||||
}
|
||||
} else {
|
||||
self.keep_looped(None, name, ids);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps `name` of `body` as assigned in outermost loops `ids`.
|
||||
fn keep_looped(&mut self, body: Option<usize>, name: &'s str, ids: Vec<usize>) {
|
||||
let len = self.out.looped.len();
|
||||
match self.out.looped.get_mut(&(body, name)) {
|
||||
Some(kept) => {
|
||||
for id in ids {
|
||||
if !kept.contains(&id) {
|
||||
kept.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
None if self.acc.room(len) => {
|
||||
self.out.looped.insert((body, name), ids);
|
||||
}
|
||||
None => self.out.looped_full = true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and
|
||||
/// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read.
|
||||
fn unread_binding(&mut self, t: &Sig<'s>) {
|
||||
@@ -234,7 +543,13 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if self.bodies.len() < self.acc.limits.nesting {
|
||||
let index = self.out.bodies.len();
|
||||
self.out.bodies.push((t.start, vec![]));
|
||||
self.bodies.push(Body { depth: self.depth(), index, names: HashSet::new(), var_depth: self.var_depth.take() });
|
||||
self.bodies.push(Body {
|
||||
depth: self.depth(),
|
||||
index,
|
||||
names: HashSet::new(),
|
||||
var_depth: self.var_depth.take(),
|
||||
looped: HashMap::new(),
|
||||
});
|
||||
} else if self.untracked.is_none() {
|
||||
self.untracked = Some(self.depth());
|
||||
}
|
||||
@@ -261,6 +576,7 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
}
|
||||
while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) {
|
||||
self.var_depth = body.var_depth;
|
||||
self.settle_looped(body);
|
||||
}
|
||||
if self.untracked.is_some_and(|d| depth < d) {
|
||||
self.untracked = None;
|
||||
|
||||
@@ -85,6 +85,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.writer_use(t);
|
||||
match t.kind {
|
||||
T::Ident => self.name(t, line),
|
||||
T::Punct => self.punct(t, line),
|
||||
@@ -130,6 +131,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `SaveOptions.SAVECHANGES` read at `line`: a `Document.close` given it saves the document to
|
||||
/// its own file, and the value may reach `close` through a variable or an argument.
|
||||
fn save_changes(&mut self, line: Option<usize>) {
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
}
|
||||
|
||||
/// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes.
|
||||
fn file_setter(&mut self, line: Option<usize>) {
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
@@ -200,6 +208,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
} else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) {
|
||||
self.acc.feature(FeatureId::FilePlaces, line);
|
||||
}
|
||||
if n == catalog::SAVE_CHANGES && of(catalog::SAVE_OPTIONS) {
|
||||
self.save_changes(line);
|
||||
}
|
||||
if n == catalog::ON_DRAW {
|
||||
self.acc.feature(FeatureId::ScriptuiDrawing, line);
|
||||
}
|
||||
@@ -272,8 +283,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
"]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => {
|
||||
let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default();
|
||||
self.setter(&name, h2, h3, line);
|
||||
if name == catalog::SAVE_CHANGES
|
||||
&& word(h2, catalog::SAVE_OPTIONS)
|
||||
&& !member_mark(h3)
|
||||
&& !self.own_names.contains(catalog::SAVE_OPTIONS)
|
||||
{
|
||||
self.save_changes(line);
|
||||
}
|
||||
}
|
||||
"(" => self.call(line),
|
||||
// `local['saveAs']`: what the object before the bracket defines, for a call that may follow.
|
||||
"[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)),
|
||||
"(" => self.call(t, line),
|
||||
// `Name.prototype["+"] = …` defines an operator.
|
||||
"=" => {
|
||||
let operator = || h1.filter(|s| s.kind == T::Str).is_some_and(|s| catalog::OPERATORS.contains(&unquote(s.text, 4).as_str()));
|
||||
@@ -288,25 +308,40 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
|
||||
/// Whether this `(` calls a document's `print`: the document-model member chain the `(` has just
|
||||
/// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `called`, the method
|
||||
/// as the chain writes it (`.print()`, or `[]()` when brackets name it).
|
||||
fn document_print(&self, called: &str) -> bool {
|
||||
/// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `.print()`, read as
|
||||
/// the document model reads the chain ([`super::Chain::dom`]), so a member name in brackets
|
||||
/// counts as one after a dot.
|
||||
fn document_print(&self) -> bool {
|
||||
let chain = self.suspended.last().filter(|c| c.wait.saturating_add(1) == self.depth());
|
||||
chain.and_then(|c| c.path.strip_suffix(called)).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver))
|
||||
chain
|
||||
.and_then(|c| c.dom.as_deref())
|
||||
.and_then(|dom| dom.strip_suffix(".print()"))
|
||||
.is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver))
|
||||
}
|
||||
|
||||
/// `(` after a name: a call.
|
||||
fn call(&mut self, line: Option<usize>) {
|
||||
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
// `doc['saveAs'](f)`: a document method named by a string literal in brackets.
|
||||
if is(h0, "]")
|
||||
&& is(h2, "[")
|
||||
&& let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
|
||||
&& (catalog::DOM_FILE_WRITES.contains(&name.as_str()) || (name == catalog::DOM_PRINT && self.document_print("[]()")))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
return;
|
||||
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !Self::defines(self.index_receiver, &name))
|
||||
|| (name == catalog::DOM_PRINT && self.document_print())
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
return;
|
||||
}
|
||||
if name == catalog::OPEN
|
||||
&& word(h3, "app")
|
||||
&& !self.shadowed[0]
|
||||
&& self.suspended.last().is_some_and(|c| c.wait.saturating_add(1) == self.depth() && c.dom.as_deref() == Some("app.open()"))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileRead, line);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return };
|
||||
let n = callee.text;
|
||||
@@ -320,6 +355,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
let file = held.is_some();
|
||||
if n == catalog::MENU_COMMAND {
|
||||
self.pending = Pending::Menu(line);
|
||||
} else if n == catalog::OPEN && word(h2, "app") && !member_mark(h3) && !self.shadowed[0] {
|
||||
self.acc.feature(FeatureId::FileRead, line);
|
||||
} else if n == catalog::OPEN && file {
|
||||
self.pending = Pending::Open(line);
|
||||
} else if catalog::DRAWING.contains(&n) {
|
||||
@@ -329,8 +366,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
} else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) {
|
||||
self.acc.feature(FeatureId::FileRead, line);
|
||||
} else if (file && catalog::FILE_WRITES.contains(&n))
|
||||
|| catalog::DOM_FILE_WRITES.contains(&n)
|
||||
|| (n == catalog::DOM_PRINT && self.document_print(".print()"))
|
||||
|| (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n))
|
||||
|| (n == catalog::DOM_PRINT && self.document_print())
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
@@ -354,6 +391,87 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The methods that `receiver`, which `before` comes before, defines when it is a variable holding
|
||||
/// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name;
|
||||
/// 0 for anything else. A receiver the check does not follow may be a document.
|
||||
/// At call offset `at`, a variable assigned in a loop containing that offset may be a document.
|
||||
fn writer_bits(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>, at: Option<usize>) -> u8 {
|
||||
match receiver {
|
||||
Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => {
|
||||
let Some(bits) = self.writers.get(r.text).copied() else { return 0 };
|
||||
if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) {
|
||||
return 0;
|
||||
}
|
||||
let looped = at.is_some_and(|at| {
|
||||
self.declared.looped_full
|
||||
|| self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| {
|
||||
let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at);
|
||||
next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok())
|
||||
})
|
||||
});
|
||||
if looped { 0 } else { bits }
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable of [`Analyzer::writers`] used before `t` in any way but a member (`local.name`,
|
||||
/// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or
|
||||
/// `exportFile` is assigned: another name may hold its object, or its methods may change, so its
|
||||
/// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`,
|
||||
/// `local[k] = w`, `delete local.saveAs`).
|
||||
fn writer_use(&mut self, t: &Sig<'s>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--"));
|
||||
let key = t.is(":") && (is(h1, "{") || is(h1, ","));
|
||||
// `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a
|
||||
// function called without a receiver (ECMA-262 3rd edition, sections 10.2.1 and 10.2.3), so the
|
||||
// global variable of that name may get another value.
|
||||
if changes {
|
||||
// `this`, not a property named `this` (`holder.this.d`).
|
||||
let global = if is(h1, ".") && word(h2, "this") && !member_mark(h3) {
|
||||
h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string())
|
||||
} else if is(h0, "]") && is(h2, "[") && word(h3, "this") && !member_mark(self.h4) {
|
||||
h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(name) = global {
|
||||
self.reassigned_global(&name);
|
||||
}
|
||||
}
|
||||
let writer = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text);
|
||||
let escaped = if word(h0, "delete") {
|
||||
// `delete local…`
|
||||
writer(Some(*t), h0)
|
||||
} else if let Some(name) = writer(h0, h1) {
|
||||
// `local` followed by anything but a member, its own assignment or an object key's `:`.
|
||||
(!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name)
|
||||
} else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) {
|
||||
// `local.saveAs = …`
|
||||
writer(h2, h3)
|
||||
} else if is(h0, "[") {
|
||||
// `local[k]` with a key that is not a string literal.
|
||||
writer(h1, h2).filter(|_| t.kind != T::Str)
|
||||
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) {
|
||||
// `local['name' + k]`.
|
||||
writer(h2, h3).filter(|_| !t.is("]"))
|
||||
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
|
||||
// `local['saveAs'] = …`, not `other.local['saveAs'] = …`.
|
||||
writer(h3, self.h4)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(name) = escaped {
|
||||
self.writers.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called.
|
||||
fn defines(bits: u8, method: &str) -> bool {
|
||||
catalog::DOM_FILE_WRITES.iter().position(|m| *m == method).is_some_and(|i| bits & (1 << i) != 0)
|
||||
}
|
||||
|
||||
/// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object
|
||||
/// (not a property of the same name), or a File or Folder object made in place or held in
|
||||
/// grouping parentheses ([`Sig::file`]): `Some(true)` for a Folder object whatever the path names
|
||||
@@ -376,6 +494,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
if t.text.contains(catalog::ACTION_TEXT) {
|
||||
self.acc.feature(FeatureId::Actions, line);
|
||||
}
|
||||
// The value written as the string `"SaveOptions.SAVECHANGES"`.
|
||||
let value = unquote(t.text, 32);
|
||||
if value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) {
|
||||
self.save_changes(line);
|
||||
}
|
||||
let compares = h0.is_some_and(|s| s.kind == T::Punct && matches!(s.text, "==" | "===" | "!=" | "!=="));
|
||||
if compares && word(h1, "typename") && is(h2, ".") {
|
||||
let name = unquote(t.text, self.acc.limits.echo.saturating_add(1));
|
||||
|
||||
@@ -105,6 +105,40 @@ pub(crate) const DOM_DOCUMENTS: &[&str] = &[
|
||||
"app.open()",
|
||||
];
|
||||
|
||||
// Every collection inherits these Object.prototype members (ECMA-262 3rd edition, section 15.2.4).
|
||||
pub(crate) const OBJECT_PROTOTYPE_MEMBERS: &[&str] =
|
||||
&["constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable"];
|
||||
|
||||
// Each collection lists the members a string key names instead of looking up an item.
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ and the corresponding collection
|
||||
// pages list these properties and methods.
|
||||
pub(crate) const DOM_COLLECTIONS: &[(&str, &[&str])] = &[
|
||||
("artboards", &["add", "getActiveArtboardIndex", "getByName", "insert", "length", "parent", "remove", "setActiveArtboardIndex", "typename"]),
|
||||
("characterStyles", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("documents", &["add", "addDocument", "addDocumentNoUI", "getByName", "index", "length", "parent", "typename"]),
|
||||
("groupItems", &["add", "createFromFile", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("layers", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("pageItems", &["getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("paragraphStyles", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
(
|
||||
"pathItems",
|
||||
&["add", "ellipse", "getByName", "index", "length", "parent", "polygon", "rectangle", "removeAll", "roundedRectangle", "star", "typename"],
|
||||
),
|
||||
("pathPoints", &["add", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("stories", &["index", "length", "parent", "typename"]),
|
||||
("swatches", &["add", "getByName", "getSelected", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("symbols", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("tags", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("textFrames", &["add", "areaText", "getByName", "index", "length", "parent", "pathText", "pointText", "removeAll", "typename"]),
|
||||
("views", &["index", "length", "parent", "typename"]),
|
||||
];
|
||||
|
||||
// The save option of `Document.close` that saves the document to its own file:
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ (SaveOptions).
|
||||
pub(crate) const SAVE_CHANGES: &str = "SAVECHANGES";
|
||||
pub(crate) const SAVE_OPTIONS: &str = "SaveOptions";
|
||||
|
||||
// Application methods that page doesn't list, named in public forum posts:
|
||||
// https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand,
|
||||
// doScript, loadAction, unloadAction) and
|
||||
|
||||
@@ -53,6 +53,12 @@ const FEATURE_CASES: &[(&str, &str, &str)] = &[
|
||||
("file.objects", "var f = new File(path);", "var f = new Filer(path);"),
|
||||
("file.places", "var t = Folder.temp;", "var t = cache.temp;"),
|
||||
("file.read", "var f = new File(p); f.open('r');", "var f = new File(p);"),
|
||||
("file.read", "app.open(f);", "var f = app.open;"),
|
||||
("file.read", "app.open(f);", "cache.app.open(f);"),
|
||||
("file.read", "app.open(f);", "var app = cache; app.open(f);"),
|
||||
("file.read", "app['open'](f);", "var f = app['open'];"),
|
||||
("file.read", "app['open'](f);", "cache.app['open'](f);"),
|
||||
("file.read", "app['open'](f);", "var app = cache; app['open'](f);"),
|
||||
("file.read", "var f = new File(p); var s = f.read();", "var s = cache.read();"),
|
||||
("file.read", "var all = folder.getFiles();", "var all = folder.files;"),
|
||||
("file.read", "var s = File(p).read();", "var s = Cache(p).read();"),
|
||||
@@ -546,6 +552,7 @@ fn save_as_and_export_file_write_a_file() {
|
||||
"d.saveAs(f);\n",
|
||||
"app.activeDocument.exportFile(f, ExportType.PNG24);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[2][..]));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
|
||||
}
|
||||
@@ -573,6 +580,56 @@ fn export_variables_in_brackets_writes_a_file() {
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() {
|
||||
for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] {
|
||||
let r = report(&format!(
|
||||
"var local = {{exportVariables: function () {{}}, saveAs: function () {{}}, exportFile: function () {{}}}};\n\
|
||||
eval('local = app.activeDocument');\n{call}\n"
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]), "{call}");
|
||||
let written = r.outside.iter().find(|o| o.id == "filesWritten");
|
||||
assert_eq!(written.map(|o| o.lines.as_slice()), Some(&[3][..]), "{call}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in
|
||||
/// brackets, as a string or through a variable; closing without it, and the other save options,
|
||||
/// write nothing.
|
||||
#[test]
|
||||
fn closing_with_save_changes_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"app.activeDocument.close();\n",
|
||||
"app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);\n",
|
||||
"app.activeDocument.close(SaveOptions.PROMPTTOSAVECHANGES);\n",
|
||||
"app.activeDocument.close(SaveOptions.SAVECHANGES);\n",
|
||||
"var how = SaveOptions['SAVECHANGES'];\n",
|
||||
"documents[0].close(how);\n",
|
||||
"documents[1].close('SaveOptions.SAVECHANGES');\n",
|
||||
"var w = new Window('dialog'); w.close(1);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 7][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[4, 5, 7][..])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_save_changes_properties_and_strings_do_not_report_writes() {
|
||||
let r = report(concat!(
|
||||
"var a = other.SAVECHANGES;\n",
|
||||
"var b = other['SAVECHANGES'];\n",
|
||||
"app.activeDocument.close('SAVECHANGES');\n",
|
||||
"var c = holder.SaveOptions.SAVECHANGES;\n",
|
||||
"var d = holder.SaveOptions['SAVECHANGES'];\n",
|
||||
"var e = 'SAVECHANGES';\n",
|
||||
"var key = SaveOptions['SAVECHANGES' + suffix];\n",
|
||||
"var f = SaveOptions.SAVECHANGES;\n",
|
||||
"var g = SaveOptions['SAVECHANGES'];\n",
|
||||
"var h = 'SaveOptions.SAVECHANGES';\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[8, 9, 10][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[8, 9, 10][..])]);
|
||||
}
|
||||
|
||||
/// `saveAs` and `exportFile` called with their names as string literals in brackets write the file
|
||||
/// too; reading the method without calling it does not.
|
||||
#[test]
|
||||
@@ -617,6 +674,395 @@ fn print_writes_a_file() {
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)]);
|
||||
}
|
||||
|
||||
/// A document reached with its member names in brackets prints to a file as one reached with dots
|
||||
/// does, and so does one a collection looks up by its name; a bracketed name that is not a
|
||||
/// document's member, and a computed one, do not. The report still shows the chains as written.
|
||||
#[test]
|
||||
fn print_on_bracketed_document_chains_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var o = new PrintOptions(); o.jobOptions.file = new File(p);\n",
|
||||
"app['activeDocument'].print(o);\n",
|
||||
"app[\"activeDocument\"][\"print\"](o);\n",
|
||||
"app[\"documents\"][0].print(o);\n",
|
||||
"app.documents['Draft'].print(o);\n",
|
||||
"app['preferences'].print(o);\n",
|
||||
"app[key].print(o);\n",
|
||||
"app['open'](new File(p));\n",
|
||||
"var d = app['activeDocument']; d.print(o);\n",
|
||||
"app.documents['getByName']('Draft').print(o);\n",
|
||||
"app['documents']['length'].print(o);\n",
|
||||
"var grouped = (app['activeDocument']); grouped.print(o);\n",
|
||||
"var scoped = app['activeDocument']; function f(scoped) {} scoped.print(o);\n",
|
||||
"var caught = app['activeDocument']; try {} catch (caught) {} caught.print(o);\n",
|
||||
"function later() { future.print(o); } var future = app['activeDocument'];\n",
|
||||
"app.documents['removeAll'].print(o);\n",
|
||||
"app['documents']['remove'].print(o);\n",
|
||||
"app.documents['addDocumentNoUI']('Print').print(o);\n",
|
||||
"app.documents['index'](0).print(o);\n",
|
||||
"app.documents['parent'].print(o); app.documents['typename'].print(o);\n",
|
||||
"app['documents']['toString'].print(o);\n",
|
||||
));
|
||||
let lines = &[2, 3, 4, 5, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19][..];
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)]);
|
||||
assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[8][..]));
|
||||
assert!(r.members.iter().any(|m| m.name == "app[].print()"));
|
||||
assert!(r.members.iter().all(|m| m.name != "app.activeDocument.print()"));
|
||||
}
|
||||
|
||||
/// A bracketed document chain keeps its document-model form across scans and included files.
|
||||
#[test]
|
||||
fn print_on_bracketed_document_chains_in_included_files_writes_a_file() {
|
||||
for order in [["doc.jsxinc", "alias.jsxinc"], ["alias.jsxinc", "doc.jsxinc"]] {
|
||||
let mut m = mem(&[("doc.jsxinc", "var doc = app['activeDocument'];\n"), ("alias.jsxinc", "var alias = doc;\n")]);
|
||||
let main = format!("#include '{}'\n#include '{}'\ndoc.print(o);\nalias.print(o);\n", order[0], order[1]);
|
||||
let r = check("main.jsx", main.as_bytes(), Some(&mut m), &Limits::default());
|
||||
let lines = &[3, 4][..];
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines), "{order:?}");
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)], "{order:?}");
|
||||
let mut members: Vec<&str> = r.members.iter().map(|m| m.name.as_str()).collect();
|
||||
members.sort_unstable();
|
||||
assert_eq!(members, ["app[]", "app[].print()"], "{order:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `saveAs` and `exportFile` called on an object literal of the script's own that defines them write
|
||||
/// nothing, with `.` or in brackets. On a document, on a variable the check does not follow, on one
|
||||
/// assigned something else since, and for a method the literal does not define, they write the file.
|
||||
#[test]
|
||||
fn the_scripts_own_save_as_writes_no_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}, 'n': 1};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"local['saveAs'](f);\n",
|
||||
"app.activeDocument.saveAs(f);\n",
|
||||
"local.exportFile(f);\n",
|
||||
"other.saveAs(f);\n",
|
||||
"local = app.activeDocument;\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var t = {x: 1, a: ok ? saveAs : 0, 'exportFile': function () {}};\n",
|
||||
"t['exportFile'](f);\n",
|
||||
"t.saveAs(f);\n",
|
||||
"var activeDocument = {saveAs: function () {}};\n",
|
||||
"app.activeDocument['saveAs'](f);\n",
|
||||
"app.activeDocument.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 6, 7, 9, 12, 14, 15][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 6, 7, 9, 12, 14, 15][..])]);
|
||||
}
|
||||
|
||||
/// Once the script replaces or deletes such a method, indexes the object with a computed key, or
|
||||
/// lets another name hold the object, its `saveAs` may write a file again, and so may a `saveAs` key
|
||||
/// whose last value in the literal is not a function expression.
|
||||
#[test]
|
||||
fn a_changed_or_shared_own_save_as_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
|
||||
"var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
|
||||
"a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n",
|
||||
"a.saveAs = app.activeDocument.saveAs;\n",
|
||||
"b['saveAs'] = w;\n",
|
||||
"delete d.saveAs;\n",
|
||||
"var h = e;\n",
|
||||
"use(g);\n",
|
||||
"a.saveAs(f);\n",
|
||||
"b.saveAs(f);\n",
|
||||
"d.saveAs(f);\n",
|
||||
"e.saveAs(f);\n",
|
||||
"g['saveAs'](f);\n",
|
||||
"var m = {saveAs: d.saveAs}; var n = {saveAs: function () {}, saveAs: d.saveAs};\n",
|
||||
"m.saveAs(f);\n",
|
||||
"n.saveAs(f);\n",
|
||||
"var q = {saveAs: function () {}, saveAs: (d.saveAs)}; var s = {saveAs: function () {}, saveAs: [w][0]};\n",
|
||||
"q['saveAs'](f);\n",
|
||||
"s.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 14, 16, 17, 19, 20][..]));
|
||||
// A computed key may name any variable, so every `saveAs` in the script may write, the ones
|
||||
// before the computed key included.
|
||||
let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc.saveAs(f);\nc[k] = w;\nc.saveAs(f);\n");
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..]));
|
||||
}
|
||||
|
||||
/// A variable assigned in a loop may hold a document when a later iteration calls its `saveAs`,
|
||||
/// before the assignment in the text: the call writes a file. One assigned only after a loop does
|
||||
/// not.
|
||||
#[test]
|
||||
fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"for (var i = 0; i < 2; i++) { a.saveAs(f); a = app.activeDocument; }\n",
|
||||
"while (n--) b.saveAs(f), b = app.activeDocument;\n",
|
||||
"do { c.saveAs(f); } while ((c = next()));\n",
|
||||
"for (;;) { d.saveAs(f); break; }\n",
|
||||
"d = app.activeDocument;\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 6][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[4, 5, 6][..])]);
|
||||
// The `else` of a body without braces is in the loop; a statement after a line break that ends
|
||||
// such a body is not, and neither is a variable of the same name that a function declares.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var e = {saveAs: function () {}}; var g = {saveAs: function () {}}; var h = {saveAs: function () {}};\n",
|
||||
"while (n--) if (n) e.saveAs(f); else e = app.activeDocument;\n",
|
||||
"while (n--) g.saveAs(f), n\n",
|
||||
"g = app.activeDocument\n",
|
||||
"function k() { var h; for (;;) h = app.activeDocument; }\n",
|
||||
"h.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
// An object literal's `}` does not end a body without braces, a call's `)` before a line break
|
||||
// does, and a literal given after the last loop that assigns its variable is the script's own.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
|
||||
"while (n--) a.saveAs(f), t = {}, a = app.activeDocument;\n",
|
||||
"b.saveAs(f);\n",
|
||||
"while (n--) tick()\n",
|
||||
"b = app.activeDocument\n",
|
||||
"for (;;) { c = app.activeDocument; }\n",
|
||||
"var c = {saveAs: function () {}};\n",
|
||||
"c.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}};\n",
|
||||
"while (n--) if (n)\n",
|
||||
" a.saveAs(f), a = app.activeDocument;\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..]));
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
|
||||
"a.saveAs(f); b['saveAs'](f);\n",
|
||||
"while (n--) { a.saveAs(f); a = app.activeDocument; }\n",
|
||||
"while (n--) { b['saveAs'](f); b = app.activeDocument; }\n",
|
||||
"var a = {saveAs: function () {}};\n",
|
||||
"a.saveAs(f);\n",
|
||||
"while (n--) { a.saveAs(f); a = app.activeDocument; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..]));
|
||||
}
|
||||
|
||||
/// The `catch` and `finally` of a `try` body, and an `else` after a `do` loop inside a body without
|
||||
/// braces, are in the loop; a statement after the whole loop is not.
|
||||
#[test]
|
||||
fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
|
||||
"var h = {saveAs: function () {}};\n",
|
||||
"while (i++ < 2) try { d.saveAs(f); } finally { d = app.activeDocument; }\n",
|
||||
"while (i++ < 2)\n",
|
||||
" if (i === 2) do e.saveAs(f); while (false);\n",
|
||||
" else e = app.activeDocument;\n",
|
||||
"while (n--) do g.saveAs(f); while (false);\n",
|
||||
"g = app.activeDocument;\n",
|
||||
"while (n--) h.saveAs(f), holder.finally\n",
|
||||
"h = app.activeDocument;\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6][..]));
|
||||
}
|
||||
|
||||
/// A literal after a label's line break may not run, a `this` assignment in a function whose own
|
||||
/// variable hides the global one changes the global, and a property `d` of another object is not
|
||||
/// the variable `d`.
|
||||
#[test]
|
||||
fn labels_hidden_globals_and_other_objects_keep_writes_known() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = app.activeDocument;\n",
|
||||
"if (no) l:\n",
|
||||
"var a = {saveAs: function () {}};\n",
|
||||
"a.saveAs(f);\n",
|
||||
"var b = {saveAs: function () {}};\n",
|
||||
"function change() { var b; this.b = app.activeDocument; }\n",
|
||||
"change(); b.saveAs(f);\n",
|
||||
"var c = {saveAs: function () {}};\n",
|
||||
"function keep() { var c; c = 1; }\n",
|
||||
"keep(); c.saveAs(f);\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"holder.d['saveAs'] = 1;\n",
|
||||
"d.saveAs(f);\n",
|
||||
"var e = {saveAs: function () {}};\n",
|
||||
"e['saveAs'] = app.activeDocument.saveAs;\n",
|
||||
"e.saveAs(f);\n",
|
||||
"var g = {saveAs: function () {}};\n",
|
||||
"function other() { var g; holder.this.g = app.activeDocument; holder.this['g'] = 1; }\n",
|
||||
"other(); g.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17][..]));
|
||||
}
|
||||
|
||||
/// Only a `var` statement directly in a function body or the global code that gives its first name
|
||||
/// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the
|
||||
/// statement. A literal given in a branch, one the value goes on from, one given by an assignment
|
||||
/// or to a later name of the statement, a call inside the literal, and a variable a function gave
|
||||
/// another value keep reporting the write.
|
||||
#[test]
|
||||
fn only_a_whole_var_value_makes_save_as_the_scripts_own() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"function choose() { d = null; d = app.activeDocument; }\n",
|
||||
"d.saveAs(f);\n",
|
||||
"var e = app.activeDocument;\n",
|
||||
"if (flag) var e = {saveAs: function () {}};\n",
|
||||
"e.saveAs(f);\n",
|
||||
"if (flag) { var e2 = {saveAs: function () {}}; }\n",
|
||||
"e2.saveAs(f);\n",
|
||||
"var g = {saveAs: function () {}} && app.activeDocument;\n",
|
||||
"g.saveAs(f);\n",
|
||||
"var h = app.activeDocument;\n",
|
||||
"h = {saveAs: function () {}, value: h.saveAs(f)};\n",
|
||||
"var k = {saveAs: function () {}, value: k.saveAs(f)};\n",
|
||||
"k.saveAs(f);\n",
|
||||
"var x = 1, y = {saveAs: function () {}};\n",
|
||||
"y.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_calls_after_many_assignment_loops_have_bounded_work() {
|
||||
for reinitialize in [false, true] {
|
||||
let mut src = "var d = {saveAs: function () {}};\n".to_string();
|
||||
for _ in 0..512 {
|
||||
src.push_str("while (n--) { d = next(); }\n");
|
||||
}
|
||||
if reinitialize {
|
||||
src.push_str("var d = {saveAs: function () {}};\n");
|
||||
}
|
||||
src.push_str("var local = {saveAs: function () {}};\n");
|
||||
for _ in 0..2048 {
|
||||
src.push_str("d.saveAs(f); local.saveAs(f);\n");
|
||||
}
|
||||
let limits = Limits::default();
|
||||
let mut acc = report::Acc::new(&limits);
|
||||
let declared = analyze::declarations(&src, &mut acc);
|
||||
let before = declared.loop_span_reads();
|
||||
analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc);
|
||||
let reads = declared.loop_span_reads() - before;
|
||||
if reinitialize {
|
||||
assert!(reads < 16 * 2048, "{reads} span accesses for 2048 calls on d");
|
||||
} else {
|
||||
assert_eq!(reads, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A function body read before the literal that assigns its variable without declaring it may run
|
||||
/// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the
|
||||
/// name assigns its own variable.
|
||||
#[test]
|
||||
fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function choose() { d = app.activeDocument; }\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"choose(); d.saveAs(f);\n",
|
||||
"function bump() { e++; }\n",
|
||||
"var e = {saveAs: function () {}};\n",
|
||||
"e.saveAs(f);\n",
|
||||
"function own() { var g; g = app.activeDocument; }\n",
|
||||
"var g = {saveAs: function () {}};\n",
|
||||
"g.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_writer_receivers_can_change_before_each_call() {
|
||||
for method in ["saveAs", "exportFile"] {
|
||||
for call in [format!("d.{method}(f)"), format!("d['{method}'](f)")] {
|
||||
for (prefix, suffix) in [("", ""), ("function outer() {\n", "}\nouter();\n")] {
|
||||
let src = format!(
|
||||
"{prefix}var d = {{{method}: function () {{}}}};\n\
|
||||
function save(f) {{ {call}; }}\n\
|
||||
d = app.activeDocument; save(f);\n{suffix}"
|
||||
);
|
||||
let r = report(&src);
|
||||
let line = if prefix.is_empty() { 2 } else { 3 };
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[line][..]), "{src}");
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[line][..])], "{src}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function outer() {\n",
|
||||
" function choose() { d = app.activeDocument; }\n",
|
||||
" var d = {saveAs: function () {}};\n",
|
||||
" choose(); d.saveAs(f);\n",
|
||||
" function bump() { e++; }\n",
|
||||
" var e = {saveAs: function () {}};\n",
|
||||
" bump(); e.saveAs(f);\n",
|
||||
" function own() { var g; g = app.activeDocument; }\n",
|
||||
" var g = {saveAs: function () {}};\n",
|
||||
" own(); g.saveAs(f);\n",
|
||||
"}\n",
|
||||
"outer();\n",
|
||||
));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 8][..])]);
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..]));
|
||||
}
|
||||
|
||||
/// Assigning a property of `this`, the global object in the global code and in a function called
|
||||
/// without a receiver, may give the global variable of that name another value, before or after
|
||||
/// its literal.
|
||||
#[test]
|
||||
fn assigning_a_property_of_this_keeps_save_as_writing() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"this.d = app.activeDocument;\n",
|
||||
"d.saveAs(f);\n",
|
||||
"function swap() { this['e'] = app.activeDocument; }\n",
|
||||
"var e = {saveAs: function () {}};\n",
|
||||
"swap(); e.saveAs(f);\n",
|
||||
"var g = {saveAs: function () {}};\n",
|
||||
"this.other = 1;\n",
|
||||
"g.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..]));
|
||||
}
|
||||
|
||||
/// A `saveAs` key's value is a method of the script's own only when the whole value is one function
|
||||
/// expression: a value that goes on after the function's body, and a literal inside another, leave
|
||||
/// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body
|
||||
/// leaves the outer variable as it was.
|
||||
#[test]
|
||||
fn a_value_that_goes_on_after_the_function_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {} && app.activeDocument.saveAs};\n",
|
||||
"var b = {saveAs: function () {}(f), n: 1};\n",
|
||||
"var c = {saveAs: function () {} ? x : y};\n",
|
||||
"var e = {saveAs: function () {}.call};\n",
|
||||
"var k = {exportFile: function w(x) { return x; }, saveAs: function () {}};\n",
|
||||
"var m = {o: {saveAs: function () {}}};\n",
|
||||
"var q = app.activeDocument; function r() { var q = {saveAs: function () {}}\n",
|
||||
"}\n",
|
||||
"a.saveAs(f);\n",
|
||||
"b.saveAs(f);\n",
|
||||
"c.saveAs(f);\n",
|
||||
"e.saveAs(f);\n",
|
||||
"k.saveAs(f); k.exportFile(f);\n",
|
||||
"m.saveAs(f);\n",
|
||||
"q.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 15, 16][..]));
|
||||
}
|
||||
|
||||
/// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing
|
||||
/// them and setting them on another object does not.
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects,
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Randomize Opacity and
|
||||
//! Sort Objects,
|
||||
//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping
|
||||
//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
|
||||
|
||||
@@ -25,14 +26,16 @@ const GRID: &str = "addon.arrange.grid";
|
||||
const OFFSET: &str = "addon.arrange.offset";
|
||||
const REPLACE: &str = "addon.arrange.replace";
|
||||
const SIZE: &str = "addon.arrange.size";
|
||||
const MATCH: &str = "addon.arrange.match";
|
||||
const OPACITY: &str = "addon.arrange.randomizeOpacity";
|
||||
const SORT: &str = "addon.arrange.sort";
|
||||
/// Each dialog's command and heading.
|
||||
const DIALOGS: [(&str, &str); 6] = [
|
||||
const DIALOGS: [(&str, &str); 7] = [
|
||||
(GRID, "Arrange in Grid"),
|
||||
(OFFSET, "Offset Objects"),
|
||||
(REPLACE, "Replace with Top Object"),
|
||||
(SIZE, "Set Size of Each"),
|
||||
(MATCH, "Match Objects"),
|
||||
(OPACITY, "Randomize Opacity"),
|
||||
(SORT, "Sort Objects"),
|
||||
];
|
||||
@@ -63,6 +66,7 @@ pub fn menu() -> Vec<Node> {
|
||||
cp("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })),
|
||||
c("Replace with Top Object…", REPLACE),
|
||||
c("Set Size of Each…", SIZE),
|
||||
c("Match Objects…", MATCH),
|
||||
cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})),
|
||||
c("Randomize Opacity…", OPACITY),
|
||||
c("Sort Objects…", SORT),
|
||||
@@ -75,6 +79,7 @@ static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None
|
||||
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
|
||||
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
|
||||
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
|
||||
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None };
|
||||
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
|
||||
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
|
||||
|
||||
@@ -149,6 +154,20 @@ fn size_rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
]
|
||||
}
|
||||
|
||||
fn match_rows() -> Vec<Param> {
|
||||
let sources = [("key", "Key Object"), ("top", "Top Object"), ("bottom", "Bottom Object")];
|
||||
let sizes = [("none", "None"), ("width", "Width"), ("height", "Height"), ("both", "Width and Height")];
|
||||
vec![
|
||||
choice("source", "Match To:", &sources, "key"),
|
||||
choice("size", "Size:", &sizes, "both"),
|
||||
check("rotate", "Rotation", false),
|
||||
check("stacking", "Stacking Order", false),
|
||||
reference_param("reference", tl!("Reference Point")),
|
||||
scale_strokes().enabled_when_in("size", ["width", "height", "both"]),
|
||||
check("patterns", "Transform Patterns", false),
|
||||
]
|
||||
}
|
||||
|
||||
fn opacity_rows() -> Vec<Param> {
|
||||
vec![percent("min", "Minimum:", 30.0), percent("max", "Maximum:", 100.0), seed()]
|
||||
}
|
||||
@@ -192,6 +211,10 @@ fn size_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(params)
|
||||
}
|
||||
|
||||
fn match_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&match_rows(), fields))
|
||||
}
|
||||
|
||||
fn opacity_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&opacity_rows(), fields))
|
||||
}
|
||||
@@ -205,6 +228,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?;
|
||||
let st = app.session.active()?;
|
||||
let strokes = app.session.prefs.scale_strokes;
|
||||
let key = st.selection.key.is_some();
|
||||
let lengths = general_lengths(app);
|
||||
let (rows, opening) = match command {
|
||||
// A square grid to start with: as many columns as the square root of the count.
|
||||
@@ -217,6 +241,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
),
|
||||
OFFSET => (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })),
|
||||
REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })),
|
||||
// The key object while the selection has one, else the top object.
|
||||
MATCH => (
|
||||
match_rows(),
|
||||
json!({
|
||||
"source": if key { "key" } else { "top" }, "size": "both", "rotate": false, "stacking": false,
|
||||
"reference": 4, "scaleStrokes": strokes, "patterns": app.session.prefs.transform_pattern_tiles,
|
||||
}),
|
||||
),
|
||||
// A new seed each time the document has changed, so running it again varies the result.
|
||||
OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })),
|
||||
// The random order's seed (not shown): new whenever the document has changed, so each run
|
||||
@@ -245,6 +277,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))),
|
||||
OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))),
|
||||
REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))),
|
||||
MATCH => super::dialogs::open(app, &MATCH_SPEC, fields, move |fields| {
|
||||
let chosen = fields.text("size").is_some_and(|size| size != "none")
|
||||
|| fields.bool("rotate") == Some(true)
|
||||
|| fields.bool("stacking") == Some(true);
|
||||
let source = key || fields.text("source") != Some("key");
|
||||
let reason = if source { tl!("Choose Size, Rotation or Stacking Order.") } else { tl!("The selection has no key object.") };
|
||||
dialog(MATCH, match_rows()).ok_enabled(chosen && source).ok_reason(reason.into()).values(Bind::bound(fields))
|
||||
}),
|
||||
OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| {
|
||||
let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0));
|
||||
dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields))
|
||||
|
||||
@@ -231,6 +231,59 @@ fn set_size_of_each_sets_the_sides_ticked() {
|
||||
assert_eq!((bounds(&app, b).width(), bounds(&app, b).height()), (30.0, 40.0));
|
||||
}
|
||||
|
||||
fn layer_order(app: &VectorcraftApp) -> Vec<NodeId> {
|
||||
app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_match_keyboard_edits_preview_confirm_and_cancel() {
|
||||
let (app, a, b) = app();
|
||||
let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let before = steps(&app);
|
||||
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
|
||||
click(&mut panel.app(), "Match Objects…");
|
||||
panel.frame();
|
||||
let id = host::dialog_id(&panel.app());
|
||||
// No key object: it opens on the top object, b, and previews its size on a.
|
||||
assert_eq!(
|
||||
host::read(&panel.app(), id, |f| (f.text("source").map(str::to_owned), f.text("size").map(str::to_owned))),
|
||||
(Some("top".into()), Some("both".into()))
|
||||
);
|
||||
assert_eq!(bounds(&panel.app(), a), vectorcraft_geom::Rect::new(-10.0, -15.0, 30.0, 25.0));
|
||||
panel.focus("Stacking Order");
|
||||
panel.key(egui::Key::Space, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(host::read(&panel.app(), id, |f| f.bool("stacking")), Some(true));
|
||||
assert_eq!(layer_order(&panel.app()), [b, a], "the preview puts a above b");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
{
|
||||
let app = panel.app();
|
||||
assert_eq!((bounds(&app, a), layer_order(&app), steps(&app)), (vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0), vec![a, b], before));
|
||||
}
|
||||
click(&mut panel.app(), "Match Objects…");
|
||||
panel.frame();
|
||||
let id = host::dialog_id(&panel.app());
|
||||
host::set(&panel.app(), id, "size", json!("none"));
|
||||
panel.frame();
|
||||
assert!(!panel.enabled("OK"), "nothing to match");
|
||||
host::set(&panel.app(), id, "size", json!("width"));
|
||||
host::set(&panel.app(), id, "source", json!("key"));
|
||||
panel.frame();
|
||||
assert!(!panel.enabled("OK"), "the selection has no key object");
|
||||
host::set(&panel.app(), id, "source", json!("bottom"));
|
||||
panel.frame();
|
||||
assert!(panel.enabled("OK"));
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
let app = panel.app();
|
||||
assert!(!app.any_dialog_open());
|
||||
// b takes a's width, its height in proportion, as one undo step.
|
||||
assert_eq!(bounds(&app, b), vectorcraft_geom::Rect::new(110.0, 110.0, 130.0, 130.0));
|
||||
assert_eq!(bounds(&app, a), vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0));
|
||||
assert_eq!(steps(&app), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_opens_with_the_scale_strokes_preference_and_swap_runs_directly() {
|
||||
let (mut app, a, b) = app();
|
||||
|
||||
@@ -134,6 +134,7 @@ impl VectorcraftApp {
|
||||
print_tiling: None,
|
||||
live_paint_gaps: None,
|
||||
find_font: None,
|
||||
missing_fonts: vec![],
|
||||
hidden_chars: Default::default(),
|
||||
spelling: Default::default(),
|
||||
text_nodes: Default::default(),
|
||||
|
||||
@@ -64,6 +64,10 @@ pub struct CanvasCache {
|
||||
/// version of the document's content and of the available fonts: the dialog reads them every
|
||||
/// frame.
|
||||
pub find_font: Option<FindFontCache>,
|
||||
/// The missing fonts of each document whose Missing Fonts dialog waits to open, for a version of
|
||||
/// the document's content and of the available fonts: the frame that checks whether a dialog
|
||||
/// waits and the frame's pump that opens it read the same list.
|
||||
pub missing_fonts: Vec<MissingFontsCache>,
|
||||
/// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame
|
||||
/// that does not draw them drops them ([`canvas::show`]).
|
||||
pub hidden_chars: canvas::marks::HiddenChars,
|
||||
@@ -253,6 +257,15 @@ pub struct FindFontCache {
|
||||
pub missing: Option<bool>,
|
||||
}
|
||||
|
||||
/// [`CanvasCache::missing_fonts`]: a document's `text.missingFonts` rows
|
||||
/// ([`vectorcraft_engine::cmd::fontfiles::missing_font_rows`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MissingFontsCache {
|
||||
/// The document and the content and fonts the rows were worked out from.
|
||||
pub key: FontsKey,
|
||||
pub fonts: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// A document's uid, a version of its content (compared by identity) and the font database's
|
||||
/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's
|
||||
/// allocation, so a later version is never placed at the same address while the key is kept.
|
||||
|
||||
@@ -35,6 +35,7 @@ use egui::{Context, Ui};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::caches::{FontsKey, MissingFontsCache};
|
||||
use crate::file_asks::{self, Owner};
|
||||
|
||||
/// The dialog's key and kind: the fonts a document opened without.
|
||||
@@ -327,19 +328,45 @@ fn after_open_for(app: &mut VectorcraftApp, r: &Value, web: bool) {
|
||||
}
|
||||
|
||||
/// Whether an opened document's Missing Fonts dialog waits for the frame's pump to open it.
|
||||
pub(crate) fn waiting(app: &VectorcraftApp) -> bool {
|
||||
app.ui.pending_fonts.iter().any(|&uid| dialog_for(app, uid).is_some())
|
||||
pub(crate) fn waiting(app: &mut VectorcraftApp) -> bool {
|
||||
let queued = app.ui.pending_fonts.clone();
|
||||
queued.into_iter().any(|uid| missing_rows(app, uid).is_some_and(|fonts| !fonts.is_empty()))
|
||||
}
|
||||
|
||||
/// The Missing Fonts dialog of the open document `uid`, when fonts it uses aren't available.
|
||||
fn dialog_for(app: &VectorcraftApp, uid: u64) -> Option<MissingFontsDialog> {
|
||||
fn dialog_for(app: &mut VectorcraftApp, uid: u64) -> Option<MissingFontsDialog> {
|
||||
let fonts = missing_rows(app, uid).filter(|f| !f.is_empty())?;
|
||||
let st = app.session.documents().iter().find(|d| d.uid == uid)?;
|
||||
let r = vectorcraft_engine::cmd::fontfiles::missing_fonts_of(st, app.session.search_rules.as_ref());
|
||||
let fonts = r["fonts"].as_array().filter(|f| !f.is_empty())?.clone();
|
||||
let next = r["fontsNextToDocument"].as_str().unwrap_or_default().to_string();
|
||||
let next = vectorcraft_engine::cmd::fontfiles::fonts_next_to_document(st, app.session.search_rules.as_ref()).unwrap_or_default();
|
||||
Some(MissingFontsDialog::new(State::new(uid, fonts, next, file_asks::can(app, PickKind::Folder))))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`missing_rows`] worked out a document's missing fonts.
|
||||
static ROW_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The `text.missingFonts` rows of the open document `uid` (`None` when it is closed), kept in
|
||||
/// [`crate::CanvasCache::missing_fonts`] and worked out again only for another version of its
|
||||
/// content or another font generation.
|
||||
fn missing_rows(app: &mut VectorcraftApp, uid: u64) -> Option<Vec<Value>> {
|
||||
let st = app.session.documents().iter().find(|d| d.uid == uid)?;
|
||||
// The generation is read first: fonts loaded while the rows are worked out leave the entry
|
||||
// under the older generation, so the next look works them out again.
|
||||
let key = FontsKey { uid, doc: std::sync::Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() };
|
||||
if let Some(c) = app.canvas.missing_fonts.iter().find(|c| c.key == key) {
|
||||
return Some(c.fonts.clone());
|
||||
}
|
||||
#[cfg(test)]
|
||||
ROW_SCANS.set(ROW_SCANS.get() + 1);
|
||||
let fonts = vectorcraft_engine::cmd::fontfiles::missing_font_rows(&st.doc);
|
||||
let cache = &mut app.canvas.missing_fonts;
|
||||
cache.retain(|c| c.key.uid != uid);
|
||||
cache.push(MissingFontsCache { key, fonts: fonts.clone() });
|
||||
Some(fonts)
|
||||
}
|
||||
|
||||
/// Once per frame: run what the finished dialog left to do, follow a running search, stop the search
|
||||
/// of a dialog that is gone, and with no dialog open open the dialog of the first queued document
|
||||
/// that is still open and still misses fonts.
|
||||
@@ -360,6 +387,9 @@ pub(crate) fn open_next(app: &mut VectorcraftApp) {
|
||||
}
|
||||
break;
|
||||
}
|
||||
// Only the documents that still wait keep their rows.
|
||||
let queued = &app.ui.pending_fonts;
|
||||
app.canvas.missing_fonts.retain(|c| queued.contains(&c.key.uid));
|
||||
}
|
||||
|
||||
/// Run what `answer` asks, and open the dialog again when it stays open (a search starts, a search
|
||||
|
||||
@@ -445,6 +445,40 @@ fn reopening_an_open_document_does_not_ask_about_its_fonts_again() {
|
||||
assert!(!is_open::<MissingFontsDialog>(&app));
|
||||
}
|
||||
|
||||
/// The frame after an open checks whether a Missing Fonts dialog waits (before a file that finished
|
||||
/// opening may come to the front) and then opens it: the document's missing fonts are worked out
|
||||
/// once for both.
|
||||
#[test]
|
||||
fn the_frame_after_an_open_works_out_the_missing_fonts_once() {
|
||||
let root = folder("once");
|
||||
let mut app = app_for(&root);
|
||||
let doc = root.join("doc.vectorcraft");
|
||||
save_doc(&mut app, &doc, "No Such Font Family", false);
|
||||
open(&mut app, &doc);
|
||||
ROW_SCANS.set(0);
|
||||
assert!(!crate::opening::may_switch(&mut app), "the dialog waits for the pump");
|
||||
pump(&mut app);
|
||||
assert_eq!(family(&app).as_deref(), Some("No Such Font Family"));
|
||||
assert_eq!(ROW_SCANS.get(), 1, "one look at the document's fonts");
|
||||
assert!(app.canvas.missing_fonts.is_empty(), "the rows go once the dialog opens");
|
||||
}
|
||||
|
||||
/// A document changed while its dialog waits lists the fonts of its new content.
|
||||
#[test]
|
||||
fn a_document_changed_while_its_dialog_waits_lists_its_new_fonts() {
|
||||
let root = folder("changed");
|
||||
let mut app = app_for(&root);
|
||||
let doc = root.join("doc.vectorcraft");
|
||||
save_doc(&mut app, &doc, "Alpha Missing Family", false);
|
||||
open(&mut app, &doc);
|
||||
assert!(!crate::opening::may_switch(&mut app));
|
||||
app.run("text.create", json!({"x": 10, "y": 80, "text": "More", "font": "Beta Missing Family"})).unwrap();
|
||||
pump(&mut app);
|
||||
let fonts = fields(&app).expect("the dialog is open")["fonts"].clone();
|
||||
let families: Vec<_> = fonts.as_array().unwrap().iter().map(|f| f["family"].as_str().unwrap_or_default()).collect();
|
||||
assert_eq!(families, ["Alpha Missing Family", "Beta Missing Family"]);
|
||||
}
|
||||
|
||||
/// A placed document that Links › Edit Original opens asks about its fonts, as File › Open does.
|
||||
#[test]
|
||||
fn edit_original_asks_about_the_placed_documents_fonts() {
|
||||
|
||||
@@ -14,7 +14,6 @@ use craft::ui::contract::{Bind, CollectionEvent, Gap, Props as _, Show as _, Sho
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows};
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::runtime::env::LengthUnits;
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::tabs::{Tab, TabKind, TabStrip};
|
||||
@@ -194,12 +193,11 @@ impl Rows<'_> {
|
||||
self.range(key, label, range, 1, UnitKind::Percent)
|
||||
}
|
||||
|
||||
/// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says.
|
||||
/// A length in points, shown in the general unit as [`length_units`](super::three_d_classic::length_units) 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);
|
||||
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))
|
||||
let lengths = super::three_d_classic::length_units(self.unit, self.bare_points);
|
||||
let row = Param::new(key, label, ParamKind::range(range.0, range.1, self.default_number(key), SliderScale::Linear)).resettable();
|
||||
super::three_d_classic::as_length(row, lengths)
|
||||
}
|
||||
|
||||
fn flag(&self, key: &str, label: &'static str) -> Param {
|
||||
|
||||
@@ -494,10 +494,10 @@ 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.
|
||||
/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, hold points and show the
|
||||
/// document's unit: "pt" in a points document, "px" in a pixels one, "mm" in a millimeters one, "in" in an inches one.
|
||||
#[test]
|
||||
fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
|
||||
fn the_3d_length_rows_show_the_document_unit() {
|
||||
use craft::ui::patterns::form_dialogs::DialogFields;
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use vectorcraft_doc::Unit;
|
||||
@@ -510,7 +510,13 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
|
||||
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)] {
|
||||
let units = [
|
||||
(Unit::Points, UnitKind::Points),
|
||||
(Unit::Pixels, UnitKind::Pixels),
|
||||
(Unit::Millimeters, UnitKind::Millimetres),
|
||||
(Unit::Inches, UnitKind::Inches),
|
||||
];
|
||||
for (general, shown) in units {
|
||||
for key in ["depth", "bevelWidth", "bevelHeight"] {
|
||||
assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}");
|
||||
checked += 1;
|
||||
@@ -526,7 +532,56 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, 21);
|
||||
assert_eq!(checked, 28);
|
||||
}
|
||||
|
||||
/// In a millimeters document the 3D dialogs' depth and offset fields show the 72 pt they hold as 25.4 mm, and a
|
||||
/// number typed there is read in millimeters and kept unrounded; Up steps by a millimeter step.
|
||||
#[test]
|
||||
fn a_3d_dialog_in_a_millimeters_document_shows_its_lengths_in_millimeters() {
|
||||
use craft::ui::contract::Role;
|
||||
let rows = [
|
||||
(CLASSIC_EXTRUDE, "object", "depth", "Depth"),
|
||||
(CLASSIC_REVOLVE, "object", "offset", "Offset"),
|
||||
(EXTRUDE, "object", "depth", "Depth"),
|
||||
(REVOLVE, "rotation", "offset", "Offset"),
|
||||
];
|
||||
for (effect, page, key, name) in rows {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width":300,"height":300,"units":"Millimeters"})).unwrap();
|
||||
app.run("path.create", json!({"d": SQUARE})).unwrap();
|
||||
let mut h = opened(app, json!({"effect": effect, "item": null}));
|
||||
h.set("__page", json!(page));
|
||||
h.set(key, json!(72.0));
|
||||
let field = |h: &ThreeD| {
|
||||
let tree = h.fixture.tree();
|
||||
h.fixture
|
||||
.by_role(Role::SPIN_BUTTON)
|
||||
.into_iter()
|
||||
.find(|t| tree.name_of(t.node) == Some(name))
|
||||
.unwrap_or_else(|| panic!("{effect}: no {name} field"))
|
||||
};
|
||||
let shown = h.fixture.tree().value_of(field(&h).node).map(str::to_owned);
|
||||
assert!(shown.as_deref().is_some_and(|s| s.contains("25.4") && s.contains("mm")), "{effect} {key}: 72 pt shows as 25.4 mm: {shown:?}");
|
||||
let target = field(&h);
|
||||
h.fixture.click(&target);
|
||||
// Tab commits the field and leaves the dialog open (Enter would press OK).
|
||||
h.fixture.key(Key::A, Modifiers::COMMAND).type_text("10").key(Key::Tab, Modifiers::NONE);
|
||||
h.settle();
|
||||
let stored = h.json(key);
|
||||
assert!(
|
||||
stored.as_f64().is_some_and(|points| (points - 10.0 * 72.0 / 25.4).abs() < 1e-3),
|
||||
"{effect} {key}: 10 mm is kept in points: {stored:?}"
|
||||
);
|
||||
// Up moves by the shown unit's own step, at least a tenth of a millimeter.
|
||||
let target = field(&h);
|
||||
h.fixture.click(&target);
|
||||
h.fixture.key(Key::ArrowUp, Modifiers::NONE).key(Key::Tab, Modifiers::NONE);
|
||||
h.settle();
|
||||
let moved = h.json(key).as_f64().zip(stored.as_f64()).map(|(after, before)| after - before);
|
||||
assert!(moved.is_some_and(|by| by >= 0.1 * 72.0 / 25.4 - 1e-6), "{effect} {key}: Up moves at least 0.1 mm: {moved:?}");
|
||||
h.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -20,7 +20,7 @@ use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind};
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::runtime::env::{Env, UnitKind};
|
||||
use craft::ui::runtime::env::{Env, LengthUnits, UnitKind};
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::style::DataColor;
|
||||
use craft::ui::text::NumberField;
|
||||
@@ -50,13 +50,23 @@ 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 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,
|
||||
}
|
||||
/// The lengths of a 3D length row: stored in points and shown in the general `unit` (a pixel is a point, as the rulers
|
||||
/// count it), a bare number read as Numbers Without Units Are Points (`bare_points`) says.
|
||||
pub(super) fn length_units(unit: Unit, bare_points: bool) -> LengthUnits {
|
||||
crate::fields::bare_points(LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(unit), 72.0), bare_points)
|
||||
}
|
||||
|
||||
/// `row`, a range row of points with no decimals set, as a length shown in `lengths.shown`. Without set decimals the
|
||||
/// field keeps the shown unit's own places and step, and the points are kept unrounded, so a value typed in
|
||||
/// millimeters or inches reads back as typed.
|
||||
pub(super) fn as_length(row: Param, lengths: LengthUnits) -> Param {
|
||||
row.unit(lengths.shown).length(lengths)
|
||||
}
|
||||
|
||||
/// A length row over `range` points with the effect's default, shown as [`as_length`] says.
|
||||
fn length_row(effect: &str, key: &str, label: &'static str, range: (f64, f64), lengths: LengthUnits) -> Param {
|
||||
let default = vectorcraft_effects::default_params(effect).and_then(|p| p.get(key).and_then(Value::as_f64)).unwrap_or(range.0);
|
||||
as_length(Param::new(key, label, ParamKind::range(range.0, range.1, default, SliderScale::Linear)).resettable(), lengths)
|
||||
}
|
||||
|
||||
/// Where the rows show: the 3D and Materials panel marks its fields with `__panel`.
|
||||
@@ -120,15 +130,15 @@ fn map_art_button(fields: &DialogFields) -> Option<Param> {
|
||||
/// Extrude & Bevel (Classic)'s Object page: depth and cap, then the bevel: its shape (a custom one included), its
|
||||
/// height and whether it is added around the shape or carved into it.
|
||||
pub(crate) fn object_params(data: &Data, fields: &DialogFields, effect: &str) -> Vec<Param> {
|
||||
let unit = Some(length_unit(data.unit));
|
||||
let lengths = length_units(data.unit, data.bare_points);
|
||||
let shaped: Vec<&str> = options_of(effect, "bevel").into_iter().map(|(value, _)| value).filter(|v| *v != "none").collect();
|
||||
let mut rows = vec![
|
||||
Param::section(tl!("Object")),
|
||||
range_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), unit, 1),
|
||||
length_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), lengths),
|
||||
cap_row(effect),
|
||||
Param::section(c3("Bevel")),
|
||||
bevel_row(data, CLASSIC_EXTRUDE, place_of(fields)),
|
||||
range_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), unit, 1).enabled_when_in("bevel", shaped.clone()),
|
||||
length_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), lengths).enabled_when_in("bevel", shaped.clone()),
|
||||
toggle_row(effect, "bevelInside", tl!("Bevel Inside")).enabled_when_in("bevel", shaped),
|
||||
];
|
||||
rows.extend(map_art_button(fields));
|
||||
@@ -141,7 +151,7 @@ pub(crate) fn revolve_params(data: &Data, fields: &DialogFields, effect: &str) -
|
||||
Param::section(tl!("Object")),
|
||||
range_row(effect, "angle", tl!("Angle"), (0.0, 360.0), Some(UnitKind::Degrees), 1),
|
||||
cap_row(effect),
|
||||
range_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), Some(length_unit(data.unit)), 1),
|
||||
length_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), length_units(data.unit, data.bare_points)),
|
||||
choice_row(effect, "edge", tl!("Axis side")),
|
||||
];
|
||||
rows.extend(map_art_button(fields));
|
||||
@@ -272,8 +282,9 @@ fn set_map_value(fields: &mut DialogFields, key: &str, value: Value) -> Result<(
|
||||
let n = value.as_f64().filter(|n| n.is_finite()).ok_or("not a number")?;
|
||||
let mut m = old.ok_or("the surface has no map")?;
|
||||
match key {
|
||||
"mapX" => m.x = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
|
||||
"mapY" => m.y = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
|
||||
// X and Y arrive in points converted from the document's unit: rounding them would move a typed 10 mm.
|
||||
"mapX" => m.x = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
|
||||
"mapY" => m.y = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
|
||||
"mapScaleX" => m.scale_x = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1),
|
||||
"mapScaleY" => m.scale_y = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1),
|
||||
"mapRotation" => m.rotation = n.clamp(-360.0, 360.0),
|
||||
@@ -370,6 +381,12 @@ fn map_of_box(state: &BoxState, rect: Rect, base: &SurfaceMap) -> SurfaceMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// The map a box edit leaves, or none while the box is still the one `map` drew (`drawn`), so a frame without an edit
|
||||
/// keeps the map's numbers exactly as typed.
|
||||
fn map_after_edit(state: &BoxState, drawn: &BoxState, rect: Rect, map: &SurfaceMap) -> Option<SurfaceMap> {
|
||||
(state != drawn).then(|| map_of_box(state, rect, map)).filter(|moved| moved != map)
|
||||
}
|
||||
|
||||
/// The id of Map Art's Done, in the footer as Reset all is on the other pages.
|
||||
pub(crate) const MAP_DONE: &str = "mapDone";
|
||||
|
||||
@@ -406,6 +423,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response {
|
||||
}
|
||||
let (Some(m), Some(rect)) = (map.as_ref(), rect) else { return };
|
||||
let mut state = map_box(m, rect);
|
||||
let drawn = state;
|
||||
if m.rotation.abs() < 0.01
|
||||
&& let (Some(doc), Some((w, h))) = (flat.doc.as_ref(), flat.art)
|
||||
{
|
||||
@@ -422,8 +440,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response {
|
||||
.reference_point(false)
|
||||
.rotate_zone(RotateZone::border(18.0))
|
||||
.show_at(ui, body.rect);
|
||||
let moved = map_of_box(&state, rect, m);
|
||||
if moved != *m {
|
||||
if let Some(moved) = map_after_edit(&state, &drawn, rect, m) {
|
||||
edited = Some(moved);
|
||||
}
|
||||
});
|
||||
@@ -505,7 +522,7 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) -
|
||||
let flat_row = flat.clone();
|
||||
rows.push(Param::custom("__mapFlat", "", move |ui, fields, _| flat_view(ui, fields, &flat_row)).full_width());
|
||||
if let Some(m) = &map {
|
||||
let unit = Some(length_unit(data.unit));
|
||||
let lengths = length_units(data.unit, data.bare_points);
|
||||
let values = [m.x, m.y, m.scale_x, m.scale_y, m.rotation];
|
||||
let labels = ["X", "Y", tl!("Horizontal Scale"), tl!("Vertical Scale"), tl!("Rotation")];
|
||||
let bounds = [
|
||||
@@ -515,14 +532,14 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) -
|
||||
GRAPHIC_SCALE_RANGE,
|
||||
(-360.0, 360.0),
|
||||
];
|
||||
let kinds = [unit, unit, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)];
|
||||
// X and Y are lengths in points; the scales are shares and the rotation an angle.
|
||||
let kinds = [None, None, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)];
|
||||
for i in 0..MAP_KEYS.len() {
|
||||
let row = Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear))
|
||||
.decimals(2)
|
||||
.on_set(set_map_value);
|
||||
let row =
|
||||
Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear)).on_set(set_map_value);
|
||||
rows.push(match kinds[i] {
|
||||
Some(kind) => row.unit(kind),
|
||||
None => row,
|
||||
Some(kind) => row.decimals(2).unit(kind),
|
||||
None => as_length(row, lengths),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -575,4 +592,26 @@ mod tests {
|
||||
let turned = map(190.0);
|
||||
assert_eq!(map_of_box(&map_box(&turned, rect), rect, &turned).rotation, -170.0, "a turn wraps to ±180");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_offsets_keep_the_points_a_document_unit_converts_to() {
|
||||
// 10 mm, as the X and Y rows hand it over in points.
|
||||
let ten_mm = 10.0 * 72.0 / 25.4;
|
||||
let mut fields = DialogFields::new();
|
||||
store_map(&mut fields, 1, Some(&map(0.0)));
|
||||
assert_eq!(set_map_value(&mut fields, "mapX", json!(ten_mm)), Ok(()));
|
||||
assert_eq!(set_map_value(&mut fields, "mapY", json!(-ten_mm)), Ok(()));
|
||||
let stored = maps_of(&fields).into_iter().find(|m| m.surface == 1).map(|m| (m.x, m.y));
|
||||
assert_eq!(stored, Some((ten_mm, -ten_mm)), "the typed offset is stored unrounded");
|
||||
assert_eq!(set_map_value(&mut fields, "mapX", json!(GRAPHIC_MAX_OFFSET * 2.0)), Ok(()));
|
||||
assert_eq!(maps_of(&fields).first().map(|m| m.x), Some(GRAPHIC_MAX_OFFSET), "the offset still keeps to its bounds");
|
||||
|
||||
// A frame without a box edit leaves those numbers as they are.
|
||||
let rect = art_rect((20.0, 10.0));
|
||||
let typed = SurfaceMap { x: ten_mm, y: -ten_mm, ..map(0.0) };
|
||||
let drawn = map_box(&typed, rect);
|
||||
assert_eq!(map_after_edit(&drawn, &drawn, rect, &typed), None);
|
||||
let dragged = drawn.moved(Vec2::new(1.0, 0.0));
|
||||
assert!(map_after_edit(&dragged, &drawn, rect, &typed).is_some(), "a drag still edits the map");
|
||||
}
|
||||
}
|
||||
@@ -6648,8 +6648,6 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msg Script file could not be written No s’ha pogut escriure el fitxer de l’script
|
||||
@msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui
|
||||
@msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi
|
||||
@msg Script file is read-only El fitxer de l’script és només de lectura
|
||||
@msg Script file is open for writing El fitxer de l’script està obert per escriure-hi
|
||||
@msg Script file name is already in use El nom del fitxer de l’script ja està en ús
|
||||
@msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta
|
||||
@msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5430,8 +5430,6 @@ liquify-list-end {0}, {1} {0} a {1}
|
||||
@msg Script file could not be written Soubor skriptu nelze zapsat
|
||||
@msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví
|
||||
@msg Script file is not open for writing Soubor skriptu není otevřený pro zápis
|
||||
@msg Script file is read-only Soubor skriptu je jen pro čtení
|
||||
@msg Script file is open for writing Soubor skriptu je otevřený pro zápis
|
||||
@msg Script file name is already in use Název souboru skriptu se už používá
|
||||
@msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky
|
||||
@msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -88,8 +88,6 @@
|
||||
@msg Script file could not be written Scriptfilen kunne ikke skrives
|
||||
@msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person
|
||||
@msg Script file is not open for writing Scriptfilen er ikke åben for skrivning
|
||||
@msg Script file is read-only Scriptfilen er skrivebeskyttet
|
||||
@msg Script file is open for writing Scriptfilen er åben for skrivning
|
||||
@msg Script file name is already in use Scriptfilens navn er allerede i brug
|
||||
@msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe
|
||||
@msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5007,8 +5007,6 @@ liquify-list-end {0}, {1} {0} und {1}
|
||||
@msg Script file could not be written Skriptdatei konnte nicht geschrieben werden
|
||||
@msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet
|
||||
@msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet
|
||||
@msg Script file is read-only Skriptdatei ist schreibgeschützt
|
||||
@msg Script file is open for writing Skriptdatei ist zum Schreiben geöffnet
|
||||
@msg Script file name is already in use Name der Skriptdatei wird bereits verwendet
|
||||
@msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein
|
||||
@msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2839,8 +2839,6 @@ liquify-list-end {0}, {1} {0} και {1}
|
||||
@msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου
|
||||
@msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει
|
||||
@msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή
|
||||
@msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση
|
||||
@msg Script file is open for writing Το αρχείο του σεναρίου είναι ανοιχτό για εγγραφή
|
||||
@msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη
|
||||
@msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο
|
||||
@msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5117,8 +5117,6 @@ liquify-list-end {0}, {1} {0}, {1}
|
||||
@msg Script file could not be written No se pudo escribir el archivo del script
|
||||
@msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda
|
||||
@msg Script file is not open for writing El archivo del script no está abierto para escritura
|
||||
@msg Script file is read-only El archivo del script es de solo lectura
|
||||
@msg Script file is open for writing El archivo del script está abierto para escritura
|
||||
@msg Script file name is already in use El nombre del archivo del script ya está en uso
|
||||
@msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta
|
||||
@msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5360,8 +5360,6 @@ liquify-list-end {0}, {1} {0} ja {1}
|
||||
@msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa
|
||||
@msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö
|
||||
@msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten
|
||||
@msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa
|
||||
@msg Script file is open for writing Komentosarjan tiedosto on auki kirjoittamista varten
|
||||
@msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä
|
||||
@msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota
|
||||
@msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5074,8 +5074,6 @@ liquify-list-end {0}, {1} {0} et {1}
|
||||
@msg Script file could not be written Le fichier du script n’a pas pu être écrit
|
||||
@msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre
|
||||
@msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture
|
||||
@msg Script file is read-only Le fichier du script est en lecture seule
|
||||
@msg Script file is open for writing Le fichier du script est ouvert en écriture
|
||||
@msg Script file name is already in use Le nom du fichier du script est déjà utilisé
|
||||
@msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier
|
||||
@msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7857,8 +7857,6 @@ liquify-list-end {0}, {1} {0} और {1}
|
||||
@msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी
|
||||
@msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है
|
||||
@msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है
|
||||
@msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है
|
||||
@msg Script file is open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली है
|
||||
@msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है
|
||||
@msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए
|
||||
@msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5952,8 +5952,6 @@ liquify-list-end {0}, {1} {0} és {1}
|
||||
@msg Script file could not be written A parancsfájl fájlját nem sikerült írni
|
||||
@msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia
|
||||
@msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva
|
||||
@msg Script file is read-only A parancsfájl fájlja csak olvasható
|
||||
@msg Script file is open for writing A parancsfájl fájlja írásra meg van nyitva
|
||||
@msg Script file name is already in use A parancsfájl fájljának neve már használatban van
|
||||
@msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen
|
||||
@msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8920,8 +8920,6 @@ breakText Glyphs Glif
|
||||
@msg Script file could not be written File skrip tidak dapat ditulis
|
||||
@msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya
|
||||
@msg Script file is not open for writing File skrip tidak dibuka untuk ditulis
|
||||
@msg Script file is read-only File skrip hanya dapat dibaca
|
||||
@msg Script file is open for writing File skrip sedang dibuka untuk ditulis
|
||||
@msg Script file name is already in use Nama file skrip sudah digunakan
|
||||
@msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder
|
||||
@msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5145,8 +5145,6 @@ liquify-list-end {0}, {1} {0} e {1}
|
||||
@msg Script file could not be written Impossibile scrivere il file dello script
|
||||
@msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda
|
||||
@msg Script file is not open for writing Il file dello script non è aperto in scrittura
|
||||
@msg Script file is read-only Il file dello script è di sola lettura
|
||||
@msg Script file is open for writing Il file dello script è aperto in scrittura
|
||||
@msg Script file name is already in use Il nome del file dello script è già in uso
|
||||
@msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella
|
||||
@msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5981,8 +5981,6 @@ liquify-list-end {0}, {1} {0}、{1}
|
||||
@msg Script file could not be written スクリプトのファイルを書き込めませんでした
|
||||
@msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です
|
||||
@msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません
|
||||
@msg Script file is read-only スクリプトのファイルは読み取り専用です
|
||||
@msg Script file is open for writing スクリプトのファイルが書き込み用に開かれています
|
||||
@msg Script file name is already in use スクリプトのファイル名はすでに使用されています
|
||||
@msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください
|
||||
@msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8654,8 +8654,6 @@ liquify-list-end {0}, {1} {0} და {1}
|
||||
@msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა
|
||||
@msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს
|
||||
@msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის
|
||||
@msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია
|
||||
@msg Script file is open for writing სკრიპტის ფაილი ჩასაწერად გახსნილია
|
||||
@msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება
|
||||
@msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე
|
||||
@msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5910,8 +5910,6 @@ liquify-list-end {0}, {1} {0} 및 {1}
|
||||
@msg Script file could not be written 스크립트 파일을 쓸 수 없습니다
|
||||
@msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다
|
||||
@msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다
|
||||
@msg Script file is read-only 스크립트 파일이 읽기 전용입니다
|
||||
@msg Script file is open for writing 스크립트 파일이 쓰기용으로 열려 있습니다
|
||||
@msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다
|
||||
@msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다
|
||||
@msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -90,8 +90,6 @@
|
||||
@msg Script file could not be written Het scriptbestand kon niet worden geschreven
|
||||
@msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord
|
||||
@msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven
|
||||
@msg Script file is read-only Het scriptbestand is alleen-lezen
|
||||
@msg Script file is open for writing Het scriptbestand is geopend voor schrijven
|
||||
@msg Script file name is already in use De naam van het scriptbestand is al in gebruik
|
||||
@msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn
|
||||
@msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5247,8 +5247,6 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msg Script file could not be written Nie można zapisać pliku skryptu
|
||||
@msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie
|
||||
@msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu
|
||||
@msg Script file is read-only Plik skryptu jest tylko do odczytu
|
||||
@msg Script file is open for writing Plik skryptu jest otwarty do zapisu
|
||||
@msg Script file name is already in use Nazwa pliku skryptu jest już używana
|
||||
@msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu
|
||||
@msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6292,8 +6292,6 @@ liquify-list-end {0}, {1} {0} e {1}
|
||||
@msg Script file could not be written Não foi possível gravar o arquivo do script
|
||||
@msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las
|
||||
@msg Script file is not open for writing O arquivo do script não está aberto para gravação
|
||||
@msg Script file is read-only O arquivo do script é somente leitura
|
||||
@msg Script file is open for writing O arquivo do script está aberto para gravação
|
||||
@msg Script file name is already in use O nome do arquivo do script já está em uso
|
||||
@msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta
|
||||
@msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5142,8 +5142,6 @@ liquify-list-end {0}, {1} {0} и {1}
|
||||
@msg Script file could not be written Не удалось записать файл скрипта
|
||||
@msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек
|
||||
@msg Script file is not open for writing Файл скрипта не открыт для записи
|
||||
@msg Script file is read-only Файл скрипта доступен только для чтения
|
||||
@msg Script file is open for writing Файл скрипта открыт для записи
|
||||
@msg Script file name is already in use Имя файла скрипта уже используется
|
||||
@msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки
|
||||
@msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5015,8 +5015,6 @@ liquify-list-end {0}, {1} {0} och {1}
|
||||
@msg Script file could not be written Skriptets fil kunde inte skrivas
|
||||
@msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem
|
||||
@msg Script file is not open for writing Skriptets fil är inte öppen för skrivning
|
||||
@msg Script file is read-only Skriptets fil är skrivskyddad
|
||||
@msg Script file is open for writing Skriptets fil är öppen för skrivning
|
||||
@msg Script file name is already in use Namnet på skriptets fil används redan
|
||||
@msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp
|
||||
@msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4843,8 +4843,6 @@ liquify-list-end {0}, {1} {0} ve {1}
|
||||
@msg Script file could not be written Betiğin dosyası yazılamadı
|
||||
@msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir
|
||||
@msg Script file is not open for writing Betiğin dosyası yazmak için açık değil
|
||||
@msg Script file is read-only Betiğin dosyası salt okunur
|
||||
@msg Script file is open for writing Betiğin dosyası yazmak için açık
|
||||
@msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor
|
||||
@msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır
|
||||
@msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5129,8 +5129,6 @@ liquify-list-end {0}, {1} {0} і {1}
|
||||
@msg Script file could not be written Не вдалося записати файл скрипту
|
||||
@msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина
|
||||
@msg Script file is not open for writing Файл скрипту не відкрито для запису
|
||||
@msg Script file is read-only Файл скрипту доступний лише для читання
|
||||
@msg Script file is open for writing Файл скрипту відкрито для запису
|
||||
@msg Script file name is already in use Ім’я файлу скрипту вже використовується
|
||||
@msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки
|
||||
@msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5642,8 +5642,6 @@ liquify-list-end {0}, {1} {0} và {1}
|
||||
@msg Script file could not be written Không thể ghi tệp của tập lệnh
|
||||
@msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời
|
||||
@msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi
|
||||
@msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc
|
||||
@msg Script file is open for writing Tệp của tập lệnh đang được mở để ghi
|
||||
@msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng
|
||||
@msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục
|
||||
@msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5637,8 +5637,6 @@ liquify-list-end {0}, {1} {0}和{1}
|
||||
@msg Script file could not be written 无法写入脚本的文件
|
||||
@msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答
|
||||
@msg Script file is not open for writing 脚本的文件未以写入方式打开
|
||||
@msg Script file is read-only 脚本的文件为只读
|
||||
@msg Script file is open for writing 脚本的文件已以写入方式打开
|
||||
@msg Script file name is already in use 脚本的文件名已被使用
|
||||
@msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称
|
||||
@msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2978,8 +2978,6 @@ liquify-list-end {0}, {1} {0}和{1}
|
||||
@msg Script file could not be written 無法寫入指令碼的檔案
|
||||
@msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應
|
||||
@msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟
|
||||
@msg Script file is read-only 指令碼的檔案為唯讀
|
||||
@msg Script file is open for writing 指令碼的檔案已以寫入方式開啟
|
||||
@msg Script file name is already in use 指令碼的檔案名稱已在使用中
|
||||
@msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱
|
||||
@msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -147,9 +147,12 @@ fn track(app: &mut VectorcraftApp, path: &str, done: Receiver<Result<ReadFile, S
|
||||
}
|
||||
|
||||
/// May the active document change now ([`poll`])?
|
||||
pub(crate) fn may_switch(app: &VectorcraftApp) -> bool {
|
||||
pub(crate) fn may_switch(app: &mut VectorcraftApp) -> bool {
|
||||
if app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) {
|
||||
return false;
|
||||
}
|
||||
let s = &app.session;
|
||||
!(app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) || s.in_interaction() || (s.tool_busy() && s.pointer_held()))
|
||||
!(s.in_interaction() || (s.tool_busy() && s.pointer_held()))
|
||||
}
|
||||
|
||||
/// Open the files that are ready (each frame). Not while a dialog is open: a document that opens
|
||||
|
||||
@@ -852,6 +852,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
character and paragraph attributes, their links to each other and the stories they form, its character and
|
||||
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries, and
|
||||
`Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms.
|
||||
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a
|
||||
document's `fullName`, `path` and `saved`, and close it with `Document.close`.
|
||||
File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
|
||||
runs a script in a named engine whose globals last between runs,
|
||||
File › Scripts lists the scripts of the Scripts folder, and
|
||||
|
||||
+90
-22
@@ -2745,11 +2745,13 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
|
||||
while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256
|
||||
characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or
|
||||
assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File
|
||||
object; a document's `saveAs`, `exportFile` or `exportVariables` counts too, and so does `print` called on
|
||||
object; the same objects left out are not counted for the File-only functions `open`, `read`, `readch`,
|
||||
`readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not
|
||||
have; a document's `saveAs`, `exportFile` or `exportVariables` counts too, and so does `SaveOptions.SAVECHANGES`
|
||||
wherever the script reads it, since `close` given it saves the document to its file, and `print` called on
|
||||
`app.activeDocument`, `app.documents[i]`, `documents.add()`, `documents.getByName()` or `app.open()`, or on a
|
||||
variable that holds one of them; the same objects left out are not counted for the File-only functions `open`,
|
||||
`read`, `readch`, `readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder
|
||||
object does not have), `filesOpened` (files opened in other apps), `network`,
|
||||
variable that holds one of them, with each member name after a dot or as a string in brackets
|
||||
(`app['activeDocument']['print'](o)`)), `filesOpened` (files opened in other apps), `network`,
|
||||
`nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`,
|
||||
`new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed).
|
||||
- `problems` lists what would stop the script loading as written (strings, comments, regular expressions,
|
||||
@@ -3099,17 +3101,27 @@ through `$`:
|
||||
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
|
||||
themselves that this page does not describe are not defined yet and read as `undefined`.
|
||||
- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file.
|
||||
When the format is selected by a `.vctemplate` path, `saveAs` writes a template copy and leaves the document's
|
||||
file and saved state unchanged.
|
||||
`Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is.
|
||||
`app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document`
|
||||
Each method sends command warnings to the Script Console with its name as the prefix: `Document.saveAs: `,
|
||||
`Document.exportFile: ` or `app.open: `. Without options, `saveAs` selects the format from the supplied name before following a link.
|
||||
`app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document`; a file
|
||||
larger than 256 MiB throws `Script document exceeds 256 MiB` before it is read
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/).
|
||||
`file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the
|
||||
format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/);
|
||||
without options the path's extension picks it. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
|
||||
`exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and
|
||||
`compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`) of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`,
|
||||
`postScript`, `preview`, `overprint` and `compatibility` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to
|
||||
`compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`), `saveMultipleArtboards` and `artboardRange` of `.ai`;
|
||||
`cmykPostScript`, `includeDocumentThumbnails`, `postScript`, `preview`, `overprint`, `compatibility`,
|
||||
`saveMultipleArtboards` and `artboardRange` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to
|
||||
`ACROBAT8` as PDF 1.3 to 1.7), `artboardRange`, `preserveEditability`, `acrobatLayers` and `compressArt` of PDF.
|
||||
As the `.ai` and EPS help pages say, `artboardRange` is used only with `saveMultipleArtboards` true, and an
|
||||
empty range means every artboard. `Document.fullName` is a `File` for the document's file, `Document.saved` is
|
||||
true when the document has no unsaved changes and can be set, and `Document.close(saveOptions?)` closes the
|
||||
document with the given `SaveOptions` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/).
|
||||
`exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()`
|
||||
and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/),
|
||||
@@ -3118,11 +3130,23 @@ through `$`:
|
||||
`coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and
|
||||
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s
|
||||
`options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with
|
||||
`pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of
|
||||
`pageToOpen` and `pDFCropToBox`. These options require PDF content, including PDF-compatible `.ai` and `.ait` files.
|
||||
`app.open` rejects a file over 128 MiB before reading it.
|
||||
Optional arguments to `saveAs`, `exportFile`, `app.open` and `close` use defaults when omitted or `undefined`;
|
||||
explicit `null` throws a type error. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of
|
||||
each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`,
|
||||
`EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`.
|
||||
`EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as
|
||||
`"ExportType.PNG24"`. The enumerations of the options that keep their defaults (`OutputFlattening`,
|
||||
`CompressionQuality`, `ColorConversion`, `ColorDestination`, `ColorProfile`, `DownsampleMethod`,
|
||||
`MonochromeCompression`, `PageMarksTypes`, `PDFChangesAllowedEnum`, `PDFPrintAllowedEnum`, `PDFTrimMarkWeight`,
|
||||
`PDFXStandard`, `SVGCSSPropertyLocation`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and
|
||||
`SVGFontType`) are defined too: the default member is accepted, and another member throws as not available yet. A
|
||||
path whose real file name is not valid UTF-8 throws `Script file path is not valid UTF-8` before anything is written
|
||||
or opened.
|
||||
VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the
|
||||
command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open
|
||||
command runs. A resolved path that is not valid UTF-8 throws before the command runs. `app.open` keeps the
|
||||
supplied name for format detection, so a `.vctemplate` link to a native document opens an untitled copy.
|
||||
A path outside the script's folders throws `Script file access denied`, also when it is an open
|
||||
document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is
|
||||
read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs`
|
||||
and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the
|
||||
@@ -3132,10 +3156,42 @@ through `$`:
|
||||
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with
|
||||
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
|
||||
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and
|
||||
when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws
|
||||
an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help
|
||||
pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
|
||||
keeps the preset's value. A bad value throws an error before anything is written.
|
||||
when the script's folders refuse one of those files, or a file-type or destination-collision check fails, none of
|
||||
them is written. Destinations that resolve to the same file are refused. A write that fails once the
|
||||
first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws
|
||||
an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help
|
||||
pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and
|
||||
`parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
|
||||
keeps the preset's value. A `pDFPreset` in square brackets, such as `[Smallest File Size]`, names the built-in
|
||||
preset of the name inside them; the default preset's name in brackets names VectorCraft Default, and
|
||||
`[PDF/X-4:2008]` names PDF/X-4:2010. Any other name throws `unknown PDF preset`. `artboardRange` takes
|
||||
a whole number from 1 as well as a string, read as `String(number)` reads it; any other number throws. With `saveMultipleArtboards` true, a `.ai` range
|
||||
(every artboard when it is empty) goes to `file.saveAs`'s `separateArtboards`, which also writes each of its
|
||||
artboards to `<name>-<artboard name>.ai`, and an EPS range goes to `useArtboards`, which writes
|
||||
`<name>_<artboard name>.eps` for each of two or more artboards beside the file at the path, and for one artboard
|
||||
writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS
|
||||
`artboardRange` is not checked against the document's artboards, but one that is not written as a range of
|
||||
artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's
|
||||
file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of
|
||||
`""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw
|
||||
`Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved
|
||||
without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an
|
||||
undo step. Assigning its current value runs no command and adds no journal entry.
|
||||
With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`;
|
||||
`SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document
|
||||
was last saved in and after the same write-access check of the path as `saveAs`, and throws an error
|
||||
and leaves the document open when the document has no file (a converted or recovered document included) or when
|
||||
the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several
|
||||
artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with
|
||||
`useArtboards: false` omits artboards; a native file saved with `separateArtboards` and a `.ai` or `.ait` file other
|
||||
than a version 7 `.ai` file keep every artboard whatever their range names. An SVG file saved with Preserve
|
||||
Editing Capabilities carries the native document with every artboard, so `close(SaveOptions.SAVECHANGES)` does not
|
||||
refuse it for omitted artboards. The SVG drawing still shows one artboard, or the art bounds with
|
||||
`useArtboards: false`, and the SVG save still refuses a range that selects several artboards.
|
||||
`SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot
|
||||
show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that
|
||||
`saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name
|
||||
(`Document.saveAs: …`, `Document.exportFile: …`, `app.open: …`, `Document.close: …`).
|
||||
- `Document.print(options?)` runs `file.print` on the document, with the options a script assigned over the
|
||||
document's print settings, or over the preset's when `printPreset` is assigned. The document's print settings
|
||||
stay as they are, and `print` adds no undo step
|
||||
@@ -3161,23 +3217,28 @@ through `$`:
|
||||
`PrintPosition`, `PrintTiling`, `PrintArtworkDesignation`, `PrintingBounds`, `PrintFontDownloadMode`,
|
||||
`FontSubstitutionPolicy`, `PageMarksTypes`, `PostScriptImageCompressionType` and `PrinterPostScriptLevelEnum` hold
|
||||
strings such as `"PrintTiling.TILEFULLPAGES"`. VectorCraft's own rules: `print` writes the file `jobOptions.file`
|
||||
names, checked as `saveAs` checks its file: PostScript when the name ends with `.ps` or `postScriptLevel` is
|
||||
names. `jobOptions.file` keeps the assigned File object and uses its current path when printing.
|
||||
The file is checked as `saveAs` checks its file: PostScript when the name ends with `.ps` (any case, including `.ps` alone) or `postScriptLevel` is
|
||||
assigned, a print-ready PDF otherwise, also when that name is a link to a file with another extension. The
|
||||
PostScript is level 2 when `postScriptLevel` is not assigned, the default it reads as. Without a file it throws `Printing to a printer is not available to scripts yet`, and `app.printerList` throws an error
|
||||
that says it is not available yet. `fitToPage` set to true wins over the scale factors and the tiling mode. With
|
||||
`printAllArtboards` false, `artboardRange` picks the artboards, and without a range every artboard prints. With
|
||||
`printAllArtboards` not assigned, an assigned `artboardRange` replaces the range of the settings `print` starts
|
||||
from, which prints when those settings print a range. `print` starts from the preset's settings when `printPreset`
|
||||
is assigned, otherwise from the document's saved settings. When those settings ignore the artboards, an assigned
|
||||
from, which prints when those settings print a range. An assigned empty or whitespace-only range prints every
|
||||
artboard. `print` starts from the preset's settings when `printPreset` is assigned, otherwise from the document's
|
||||
saved settings. When those settings ignore the artboards, an assigned
|
||||
`printArea` prints the artboards an assigned `artboardRange` names, or each artboard without a range. With one of
|
||||
`horizontalScale` and `verticalScale` assigned, the other keeps its value in the settings `print` starts from. `print` throws before anything is written when an assigned `artboardRange` names an
|
||||
`horizontalScale` and `verticalScale` assigned, the other keeps its value in the settings `print` starts from.
|
||||
With no scale or tiling assigned, `fitToPage = false` clears a base fit mode and preserves other base scaling modes.
|
||||
`print` throws before anything is written when an assigned `artboardRange` names an
|
||||
artboard the document does not have, also with `printAllArtboards` true, when `printPreset` or `flattenerPreset`
|
||||
is not a preset's name (any case), when `colorManagementOptions.name` is not an RGB or CMYK profile's name (any
|
||||
case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom`
|
||||
and `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, or holds `/`, `\` or
|
||||
and `width` or `height` is assigned above 0. `CUSTOMPROFILE` requires an assigned profile name or a profile in
|
||||
the base settings; otherwise `print` throws before writing. An assigned name that is empty or only spaces, or holds `/`, `\` or
|
||||
a control character (also at either end), throws too, and each checked name is sent without the spaces around it. `printerName` and `PPDName` take only `""`. A listed option that is not mapped, or a value that is not mapped such as
|
||||
`PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION`, `PSLEVEL1` or a scale above 1000, throws an error that says it
|
||||
is not available yet. Each value is checked when it is assigned: a wrong type, a number that is not finite or is
|
||||
`PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION` or `PSLEVEL1`, throws an error that says it
|
||||
is not available yet. Print scale factors must be from 1 to 1000 percent. Each value is checked when it is assigned: a wrong type, a number that is not finite or is
|
||||
out of range, a string longer than 4,096 bytes, an option object of the wrong class or from an earlier run, and a
|
||||
path given as a string all throw. A run makes at most 256 option objects. Each warning `file.print` gives goes to
|
||||
the Script Console as a line that starts with `Document.print: `. `vc.run` still cannot run `file.print` or
|
||||
@@ -10621,7 +10682,9 @@ document. With no document open they fail with "no document open". `document.act
|
||||
the current one. `document.move {from?, to}` reorders open documents the way dragging a document tab along the tab strip
|
||||
does: `from` defaults to the current document, `to` is the destination index, documents between them shift by one, the
|
||||
current document stays current, and each document keeps its own view (#5663). It is an engine command, so headless and
|
||||
remote `command_list` both list it. `file.close {index}` on a document other than the current one leaves the current
|
||||
remote `command_list` both list it. `document.setSaved {index?, saved}` records a document as saved (`true`) or as
|
||||
having unsaved changes (`false`) without saving it and without an undo step; a script's `Document.saved = value` runs
|
||||
it. `file.close {index}` on a document other than the current one leaves the current
|
||||
document current, and its tool keeps its state; closing the current document makes the document in the next tab
|
||||
current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first,
|
||||
to ask whether to save it.
|
||||
@@ -17674,6 +17737,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid
|
||||
| `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. |
|
||||
| `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` |
|
||||
| `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). |
|
||||
| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` |
|
||||
| `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) |
|
||||
| `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` |
|
||||
| `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` |
|
||||
@@ -17683,6 +17747,9 @@ active view so the selection's visual bounds fill the window with a margin, as `
|
||||
and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs
|
||||
(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose
|
||||
fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies.
|
||||
Match Objects… opens a dialog of its own in the same way, keyed by its command, whose fields are the command's
|
||||
parameters, with Preview; it opens on the key object when the selection has one, else on the top object, and OK is
|
||||
off while nothing is chosen to match or the source is the key object and there is none.
|
||||
Offset Objects… opens one the same way (`ui.menuDialog {command: "addon.arrange.offset"}`), with Direction, Gap, Order
|
||||
and Reverse Order.
|
||||
|
||||
@@ -17691,6 +17758,7 @@ and Reverse Order.
|
||||
{"name":"run_command","arguments":{"command":"addon.arrange.offset","params":{"direction":"column","gap":6,"order":"position"}}}
|
||||
{"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}}
|
||||
{"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}}
|
||||
{"name":"run_command","arguments":{"command":"addon.arrange.match","params":{"source":"key","size":"both","rotate":true}}}
|
||||
```
|
||||
|
||||
## Document Tools add-on
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Scripts return usable File objects from print job options, select Save As formats before resolving links, and report save, export, and open warnings in the Script Console. Saves and exports reject generated targets that already name directories before writing any output. Print options preserve base tiling when fitToPage is false and validate scale factors from 1 to 1000 percent at assignment. New message keys use English fallback text.
|
||||
+1
-1
@@ -206,7 +206,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
|
||||
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
|
||||
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 |
|
||||
| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
|
||||
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
|
||||
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
|
||||
|
||||
@@ -1120,8 +1120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets. Printing to a printer from a script and `app.printerList` are not available yet (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets. Printing to a printer from a script and `app.printerList` are not available yet (`docs/mcp.md`). Check Script counts `print` on a document as a file write, with the document's member names after dots or as strings in brackets (`app['activeDocument'].print(o)`, `app.documents['Draft'].print(o)`). `crates/engine/src/tests/script_print.rs`, `crates/scriptcheck/src/tests.rs` (`print_writes_a_file`, `print_on_bracketed_document_chains_writes_a_file`).
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
|
||||
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
|
||||
@@ -1129,6 +1128,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
|
||||
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
`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`, 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`.
|
||||
@@ -3149,6 +3149,10 @@ scaling, replace with each fit and kept originals in stacking order, size with p
|
||||
undo step, off states, bad params refused), `addons::arrange::tests` in `vectorcraft-ui-egui` (the submenu, the
|
||||
dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on.
|
||||
|
||||
## Arrange Tools add-on: Match Objects (2026-11-29)
|
||||
|
||||
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (a clipping path keeps its place, so such a match is refused). Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on.
|
||||
|
||||
## Arrange Tools add-on: Group Overlapping Objects (2026-11-01)
|
||||
|
||||
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the top-level selected objects wherever their visual bounds overlap or touch, chains included (A overlapping B and B overlapping C makes one group of three), only among objects of the same layer or group; objects that overlap nothing stay as they are, each new group takes its frontmost member's place in the stacking order, and the groups and the loose objects stay selected. One undo step; at most 20000 objects, compared by a sweep along x with union-find. Tests: `group_overlapping_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (chains, loners, stacking order, layers kept apart, visual bounds, no step when nothing overlaps, many objects), `group_overlapping_objects_runs_directly` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on.
|
||||
|
||||
@@ -564,6 +564,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
|
||||
| Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` |
|
||||
| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer that is not a template and whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` |
|
||||
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |
|
||||
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Match Objects… gives the other selected objects the size (Width, Height or Width and Height), the bounding-box angle (Rotation) and the stacking place (Stacking Order) of the source, chosen in Match To (Key Object, Top Object, Bottom Object); the reference point, Scale Strokes & Effects, Transform Patterns; Preview; one undo step | done | `addon.arrange.match`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |
|
||||
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored |
|
||||
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |
|
||||
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |
|
||||
|
||||
Reference in new issue
Block a user