mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 20:18:38 -05:00
Merge pull request #9266 from dotCooCoo/feat/scripts-export-autocad
Scripts: exportFile writes DXF with ExportOptionsAutoCAD
This commit is contained in:
13 files changed
+529
-37
No files matched your search
@@ -602,6 +602,8 @@ pub struct SaveJob {
|
||||
stamped: Option<i64>,
|
||||
/// The artboards also saved to files of their own (`separateArtboards`).
|
||||
boards: Vec<usize>,
|
||||
/// The client did not give the path: a file the file access refuses before anything is
|
||||
/// written is named as [`super::access::naming_in_error`] names it ([`SaveJob::naming_refusals`]).
|
||||
redact_paths: bool,
|
||||
}
|
||||
|
||||
@@ -972,6 +974,14 @@ impl SaveJob {
|
||||
&self.plan
|
||||
}
|
||||
|
||||
/// The job for a save whose path the client did not give: a file the file access refuses
|
||||
/// before anything is written is named in the error as the request being served may see it
|
||||
/// ([`super::access::naming_in_error`]).
|
||||
pub(crate) fn naming_refusals(mut self) -> Self {
|
||||
self.redact_paths = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The document when the job was made (what counts as saved once the file is written).
|
||||
pub(crate) fn snapshot(&self) -> &Arc<Document> {
|
||||
&self.snapshot
|
||||
@@ -1245,10 +1255,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 mut job = save_job(s, plan)?;
|
||||
let uid = s.doc()?.uid;
|
||||
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
|
||||
job.redact_paths = !given;
|
||||
let job = save_job(s, plan)?;
|
||||
let job = if given { job } else { job.naming_refusals() };
|
||||
let uid = s.doc()?.uid;
|
||||
// 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) })
|
||||
|
||||
@@ -510,7 +510,8 @@ pub fn check_write(path: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_write`] without recording `path` as written.
|
||||
/// [`check_write`] without adding `path` to the files a script run reports as written, for a
|
||||
/// check made before anything is written.
|
||||
pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)
|
||||
|
||||
@@ -3191,7 +3191,9 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name);
|
||||
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/> describe.
|
||||
//!
|
||||
//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's
|
||||
@@ -26,6 +27,12 @@
|
||||
//! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art.
|
||||
//! An SVG with `embedRasterImages` false also writes the document's embedded images beside it,
|
||||
//! and when one of those files may not be written, none of them is.
|
||||
//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF
|
||||
//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not
|
||||
//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page
|
||||
//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to
|
||||
//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one
|
||||
//! `unit`, more than 0 and at most 1000.
|
||||
//! - An option the classes here map is applied; a listed option that is not mapped is accepted at
|
||||
//! the default its help page gives and throws an error that says it is not available yet at any
|
||||
//! other value; a property the help pages do not list throws an error that names it, unless it is
|
||||
@@ -40,8 +47,8 @@
|
||||
//! save of one artboard writes only the file at the path, holding that artboard. Without
|
||||
//! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of
|
||||
//! artboard numbers throws.
|
||||
//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no
|
||||
//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`.
|
||||
//! - `Document.path` is a `Folder` for the folder of the document's file. A file saved or opened
|
||||
//! under a relative path is in the process's working folder. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`.
|
||||
//! `fullName` and `path` of a document whose file the automation read roots do not allow throw
|
||||
//! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`.
|
||||
//! Assigning its current value runs no command.
|
||||
@@ -64,6 +71,7 @@ use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{
|
||||
@@ -86,6 +94,15 @@ pub(in crate::script) struct State {
|
||||
/// The enumerations these members use, as `dom`'s are made.
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]),
|
||||
("AutoCADColors", &["Max8Colors", "Max16Colors", "Max256Colors", "TrueColors"]),
|
||||
(
|
||||
"AutoCADCompatibility",
|
||||
&["AutoCADRelease13", "AutoCADRelease18", "AutoCADRelease14", "AutoCADRelease21", "AutoCADRelease15", "AutoCADRelease24"],
|
||||
),
|
||||
("AutoCADExportFileFormat", &["DXF", "DWG"]),
|
||||
("AutoCADExportOption", &["PreserveAppearance", "MaximizeEditability"]),
|
||||
("AutoCADRasterFormat", &["PNG", "JPEG"]),
|
||||
("AutoCADUnit", &["Points", "Picas", "Inches", "Millimeters", "Centimeters", "Pixels"]),
|
||||
(
|
||||
"Compatibility",
|
||||
&[
|
||||
@@ -182,6 +199,10 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]),
|
||||
];
|
||||
|
||||
/// Other names of enumeration members: `(enumeration, name, member)` makes `enumeration.name` the
|
||||
/// same value as `enumeration.member`.
|
||||
pub(super) const ALIASES: &[(&str, &str, &str)] = &[("ExportType", "AUTOCAD", "AutoCAD")];
|
||||
|
||||
const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS";
|
||||
const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS";
|
||||
|
||||
@@ -196,7 +217,8 @@ enum Default {
|
||||
Member(&'static str, &'static str),
|
||||
/// The help page gives no default: any value throws.
|
||||
Unset,
|
||||
/// White as an `RGBColor`: red, green and blue each 255.
|
||||
/// White as an `RGBColor`: red, green and blue each 255 (its `typename`, when it has one,
|
||||
/// `RGBColor`).
|
||||
White,
|
||||
}
|
||||
|
||||
@@ -209,7 +231,7 @@ impl Default {
|
||||
(Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m),
|
||||
(Default::White, Data::Object(items)) => {
|
||||
let get = |k: &str| items.iter().find(|(name, _)| name == k).map(|(_, v)| v);
|
||||
matches!(get("typename"), Some(Data::String(t)) if t == "RGBColor")
|
||||
get("typename").is_none_or(|t| matches!(t, Data::String(t) if t == "RGBColor"))
|
||||
&& ["red", "green", "blue"].iter().all(|k| matches!(get(k), Some(Data::Number(n)) if *n == 255.0))
|
||||
}
|
||||
_ => false,
|
||||
@@ -656,9 +678,118 @@ fn svg_starts() -> Vec<(&'static str, Data)> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The members of the enumeration `name` in [`ENUMS`].
|
||||
fn members_of(name: &str) -> &'static [&'static str] {
|
||||
ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m)
|
||||
}
|
||||
|
||||
fn autocad_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("ExportOptionsAutoCAD.{name}");
|
||||
let pick = |enumeration: &str| member(d, enumeration, members_of(enumeration), &what);
|
||||
match name {
|
||||
"alterPathsForAppearance" => {
|
||||
p.insert("alterPaths".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"colors" => {
|
||||
let colors = match pick("AutoCADColors")? {
|
||||
"Max8Colors" => json!(8),
|
||||
"Max16Colors" => json!(16),
|
||||
"Max256Colors" => json!(256),
|
||||
_ => json!("true"),
|
||||
};
|
||||
p.insert("colors".into(), colors);
|
||||
}
|
||||
"convertTextToOutlines" => {
|
||||
p.insert("outlineText".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"exportFileFormat" => {
|
||||
if pick("AutoCADExportFileFormat")? == "DWG" {
|
||||
return Err(HostError::Error(
|
||||
"AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
"exportOption" => {
|
||||
let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" };
|
||||
p.insert("preserve".into(), json!(preserve));
|
||||
}
|
||||
"exportSelectedArtOnly" => {
|
||||
p.insert("selectedOnly".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"rasterFormat" => {
|
||||
p.insert("rasterFormat".into(), json!(if pick("AutoCADRasterFormat")? == "JPEG" { "jpeg" } else { "png" }));
|
||||
}
|
||||
"scaleLineweights" => {
|
||||
p.insert("scaleLineweights".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"unit" => {
|
||||
let unit = match pick("AutoCADUnit")? {
|
||||
"Points" => Unit::Points,
|
||||
"Picas" => Unit::Picas,
|
||||
"Inches" => Unit::Inches,
|
||||
"Millimeters" => Unit::Millimeters,
|
||||
"Centimeters" => Unit::Centimeters,
|
||||
_ => Unit::Pixels,
|
||||
};
|
||||
p.insert("unit".into(), json!(unit.key()));
|
||||
}
|
||||
"unitScaleRatio" => {
|
||||
let n = match d {
|
||||
Data::Number(n) if n.is_finite() => *n,
|
||||
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
};
|
||||
if !(n > 0.0 && n <= 1000.0) {
|
||||
return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000")));
|
||||
}
|
||||
p.insert("scale".into(), json!(n));
|
||||
}
|
||||
"version" => {
|
||||
let version = match pick("AutoCADCompatibility")? {
|
||||
"AutoCADRelease13" => "R13",
|
||||
"AutoCADRelease14" => "R14",
|
||||
"AutoCADRelease15" => "2000",
|
||||
"AutoCADRelease18" => "2004",
|
||||
"AutoCADRelease21" => "2007",
|
||||
_ => "2010",
|
||||
};
|
||||
p.insert("version".into(), json!(version));
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn autocad_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("alterPathsForAppearance", Data::Bool(false)),
|
||||
("convertTextToOutlines", Data::Bool(false)),
|
||||
("exportFileFormat", text("AutoCADExportFileFormat.DWG")),
|
||||
("exportOption", text("AutoCADExportOption.MaximizeEditability")),
|
||||
("exportSelectedArtOnly", Data::Bool(false)),
|
||||
("scaleLineweights", Data::Bool(false)),
|
||||
("version", text("AutoCADCompatibility.AutoCADRelease24")),
|
||||
]
|
||||
}
|
||||
|
||||
/// The options object `d` with the options of a new `class` object it leaves out, or holds as
|
||||
/// `undefined`, added.
|
||||
fn with_starts(class: &OptionClass, d: &Data) -> Data {
|
||||
let Data::Object(items) = d else { return d.clone() };
|
||||
let mut items = items.clone();
|
||||
for (k, v) in (class.starts)() {
|
||||
match items.iter_mut().find(|(n, _)| n == k) {
|
||||
Some((_, held)) if matches!(held, Data::Undefined) => *held = v,
|
||||
Some(_) => {}
|
||||
None => items.push((k.to_string(), v)),
|
||||
}
|
||||
}
|
||||
Data::Object(items)
|
||||
}
|
||||
|
||||
const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts };
|
||||
const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts };
|
||||
const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts };
|
||||
const AUTOCAD: OptionClass = OptionClass { name: "ExportOptionsAutoCAD", map: autocad_map, kept: &[], starts: autocad_starts };
|
||||
|
||||
/// An `ExportType`: the format `document.export` writes, the extensions a file name may already
|
||||
/// end with (the first is added), and its option class (`None`: no options are taken).
|
||||
@@ -669,9 +800,9 @@ struct ExportKind {
|
||||
}
|
||||
|
||||
fn export_kind(d: &Data) -> std::result::Result<ExportKind, HostError> {
|
||||
let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m);
|
||||
let raster = |format, extensions| ExportKind { format, extensions, options: None };
|
||||
Ok(match member(d, "ExportType", all, "exportType")? {
|
||||
Ok(match member(d, "ExportType", members_of("ExportType"), "exportType")? {
|
||||
"AutoCAD" => ExportKind { format: "dxf", extensions: &["dxf"], options: Some(&AUTOCAD) },
|
||||
"PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) },
|
||||
"JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) },
|
||||
"SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) },
|
||||
@@ -848,11 +979,26 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
None => Map::new(),
|
||||
},
|
||||
Some(o) => match kind.options {
|
||||
// An AutoCAD option left out takes its help page's default, not the DXF writer's.
|
||||
Some(class) if class.name == AUTOCAD.name => options_params(class, &with_starts(class, o))?,
|
||||
Some(class) => options_params(class, o)?,
|
||||
None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())),
|
||||
None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))),
|
||||
},
|
||||
};
|
||||
// A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed
|
||||
// colors, and `AutoCADColors.TrueColors` with it throws.
|
||||
if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) {
|
||||
match p.get("colors") {
|
||||
None => {
|
||||
p.insert("colors".into(), json!(256));
|
||||
}
|
||||
Some(c) if c.as_str() == Some("true") => {
|
||||
return Err(HostError::Error("AutoCADColors.TrueColors needs AutoCADRelease18 or a later version".into()));
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0));
|
||||
@@ -860,7 +1006,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into()));
|
||||
}
|
||||
// A raster file has one pixel per point at 100%, whatever the document's raster effects resolution.
|
||||
if kind.format != "svg" {
|
||||
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`.
|
||||
if !matches!(kind.format, "svg" | "dxf") {
|
||||
p.insert("scale".into(), json!(hs / 100.0));
|
||||
}
|
||||
let format = if svgz { "svgz" } else { kind.format };
|
||||
@@ -1140,7 +1287,7 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its
|
||||
/// help page gives for the options mapped here.
|
||||
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]);
|
||||
let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG, &AUTOCAD]);
|
||||
all.map(|c| {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
|
||||
@@ -339,13 +339,17 @@ fn omitted_options_are_a_new_options_objects_defaults() {
|
||||
d.exportFile(new File(dir + '/j2'), ExportType.JPEG, new ExportOptionsJPEG());\n\
|
||||
d.exportFile(new File(dir + '/p1'), ExportType.PNG24);\n\
|
||||
d.exportFile(new File(dir + '/p2'), ExportType.PNG24, new ExportOptionsPNG24());\n\
|
||||
var j3 = new ExportOptionsJPEG(); j3.matteColor = {{red: 255, green: 255, blue: 255}};\n\
|
||||
d.exportFile(new File(dir + '/j3'), ExportType.JPEG, j3);\n\
|
||||
var p3 = new ExportOptionsPNG24(); p3.matteColor = {{typename: 'RGBColor', red: 255, green: 255, blue: 255}};\n\
|
||||
d.exportFile(new File(dir + '/p3'), ExportType.PNG24, p3);\n\
|
||||
d.exportFile(new File(dir + '/s1'), ExportType.SVG);\n\
|
||||
d.exportFile(new File(dir + '/s2'), ExportType.SVG, new ExportOptionsSVG());\n\
|
||||
d.saveAs(new File(dir + '/a1.pdf'));\n\
|
||||
d.saveAs(new File(dir + '/a2.pdf'), new PDFSaveOptions());"
|
||||
),
|
||||
);
|
||||
for (one, two) in [("j1.jpg", "j2.jpg"), ("p1.png", "p2.png"), ("s1.svg", "s2.svg")] {
|
||||
for (one, two) in [("j1.jpg", "j2.jpg"), ("j1.jpg", "j3.jpg"), ("p1.png", "p2.png"), ("p1.png", "p3.png"), ("s1.svg", "s2.svg")] {
|
||||
assert!(std::fs::read(dir.join(one)).unwrap() == std::fs::read(dir.join(two)).unwrap(), "{one} and {two} differ");
|
||||
}
|
||||
for name in ["a1.pdf", "a2.pdf"] {
|
||||
@@ -523,6 +527,85 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The value of the DXF header variable `name` (the group after its name).
|
||||
fn dxf_header(dxf: &str, name: &str) -> Option<String> {
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
lines.iter().position(|l| *l == name).and_then(|i| lines.get(i + 2)).map(|v| v.to_string())
|
||||
}
|
||||
|
||||
/// The largest x coordinate (group code 10) in the entities of a DXF.
|
||||
fn dxf_widest(dxf: &str) -> f64 {
|
||||
dxf_xs(dxf).into_iter().reduce(f64::max).expect("DXF contains polyline vertices")
|
||||
}
|
||||
|
||||
/// The smallest x coordinate (group code 10) in the entities of a DXF.
|
||||
fn dxf_leftmost(dxf: &str) -> f64 {
|
||||
dxf_xs(dxf).into_iter().reduce(f64::min).expect("DXF contains polyline vertices")
|
||||
}
|
||||
|
||||
/// The x coordinates (group code 10) of the polyline vertices in a DXF. A hatch's code 10 is its
|
||||
/// elevation point, so hatches are left out.
|
||||
fn dxf_xs(dxf: &str) -> Vec<f64> {
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
// The section's name is a value; the group codes start on the line after it.
|
||||
let start = lines.iter().position(|l| *l == "ENTITIES").map_or(0, |i| i + 1);
|
||||
let mut entity = "";
|
||||
let mut xs = Vec::new();
|
||||
for p in lines[start..].chunks(2).filter(|p| p.len() == 2) {
|
||||
match p[0] {
|
||||
"0" => entity = p[1],
|
||||
"10" if entity == "LWPOLYLINE" => xs.extend(p[1].parse::<f64>().ok()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
xs
|
||||
}
|
||||
|
||||
/// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and
|
||||
/// DWG, the help page's default format, throws without writing a file.
|
||||
#[test]
|
||||
fn an_autocad_export_writes_a_dxf_with_its_options() {
|
||||
let base = folder("autocad");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let d = quoted(&dir);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\
|
||||
var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\
|
||||
try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\
|
||||
o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\
|
||||
o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\
|
||||
d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\
|
||||
o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\
|
||||
o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\
|
||||
var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\
|
||||
d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!(["ExportOptionsAutoCAD", "AutoCADExportFileFormat.DWG", "AutoCADCompatibility.AutoCADRelease24", true]));
|
||||
assert!(out[1].as_str().is_some_and(|e| e.contains("DWG is not available")), "{}", out[1]);
|
||||
assert!(!dir.join("w.dxf").exists() && !dir.join("w.dwg").exists() && !dir.join("w").exists(), "DWG writes nothing");
|
||||
let a = std::fs::read_to_string(dir.join("a.dxf")).unwrap();
|
||||
let b = std::fs::read_to_string(dir.join("b.DXF")).unwrap();
|
||||
assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it");
|
||||
assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format");
|
||||
assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each");
|
||||
assert!(dxf_widest(&a) > dxf_widest(&b) * 20.0, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b));
|
||||
for name in ["c.dxf", "u.dxf"] {
|
||||
let dxf = std::fs::read_to_string(dir.join(name)).unwrap();
|
||||
assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24");
|
||||
// The rectangle is 10 pt (3.5 mm) from the artboard's left edge.
|
||||
assert!(dxf_leftmost(&dxf).abs() < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf));
|
||||
}
|
||||
let p = std::fs::read_to_string(dir.join("p.dxf")).unwrap();
|
||||
assert!(dxf_widest(&p) > dxf_widest(&b) * 5.0, "a pica is a sixth of an inch: {} and {}", dxf_widest(&p), dxf_widest(&b));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and
|
||||
/// an option the script changes applies over the preset.
|
||||
#[test]
|
||||
@@ -606,7 +689,7 @@ fn an_export_writes_nothing_when_a_folder_is_where_one_of_its_files_goes() {
|
||||
}
|
||||
|
||||
/// When the writer a save is given does not check the file access itself, a save of several files
|
||||
/// whose file access refuses one of them hands none of them to the writer.
|
||||
/// whose last file is refused hands none of them to the writer, the refused one included.
|
||||
#[test]
|
||||
fn a_refused_file_stops_a_save_whose_writer_does_not_check() {
|
||||
use crate::cmd::fileio::{SaveMode, save_job, save_plan};
|
||||
@@ -643,9 +726,10 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() {
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
let e = r.unwrap_err().to_string();
|
||||
let refused = refused.unwrap();
|
||||
assert_eq!(written, Vec::<String>::new(), "no file went to the writer, the refused one ({refused}) included");
|
||||
assert!(e.contains(DENIED) && e.contains(&refused), "{e}");
|
||||
assert!(written.is_empty(), "no file went to the writer: {written:?}");
|
||||
let mut perms = std::fs::metadata(&refused).unwrap().permissions();
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
@@ -948,6 +1032,12 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
(format!("var o = new EPSSaveOptions(); o.postScript = 'LEVEL2'; app.activeDocument.saveAs({f}, o);"), "EPSPostScriptLevelEnum"),
|
||||
(format!("app.activeDocument.exportFile({f}, 'PNG24');"), "ExportType"),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.FLASH);"), "is not available yet"),
|
||||
(
|
||||
format!(
|
||||
"var p = new ExportOptionsPNG24(); p.matteColor = {{red: 255, green: 0, blue: 255}}; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"
|
||||
),
|
||||
"ExportOptionsPNG24.matteColor is not available yet",
|
||||
),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.PNG24, new ExportOptionsJPEG());"), "ExportOptionsPNG24"),
|
||||
(
|
||||
format!(
|
||||
@@ -970,6 +1060,41 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
"from 0 to 100",
|
||||
),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.AutoCAD);"), "DWG is not available"),
|
||||
(
|
||||
format!("var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"),
|
||||
"DWG is not available",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 2000; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"at most 1000",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"AutoCADCompatibility",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.colors = 256; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"AutoCADColors",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScale = 2; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"ExportOptionsAutoCAD has no option unitScale",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease14; o.colors = AutoCADColors.TrueColors; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"TrueColors needs AutoCADRelease18",
|
||||
),
|
||||
(format!("app.open({f}, 'RGB');"), "DocumentColorSpace"),
|
||||
(format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"),
|
||||
(format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"),
|
||||
@@ -1274,6 +1399,51 @@ fn full_name_path_saved_and_close_follow_the_documents_file() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A document whose file was saved under a relative name is in the working folder the file was
|
||||
/// written in.
|
||||
#[test]
|
||||
fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() {
|
||||
let base = folder("relative");
|
||||
let mut s = session(&base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.active_mut().unwrap().path = Some("drawing.svg".into());
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName, d.fullName.fsName]);",
|
||||
);
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
assert_eq!(out[0][0], json!(true), "{out}");
|
||||
let same = |shown: &str, want: &Path| {
|
||||
let shown = PathBuf::from(shown);
|
||||
shown == want || std::fs::canonicalize(&shown).ok().zip(std::fs::canonicalize(want).ok()).is_some_and(|(a, b)| a == b)
|
||||
};
|
||||
assert!(same(out[0][1].as_str().unwrap(), &cwd), "{out} is not in {cwd:?}");
|
||||
let file = out[0][2].as_str().unwrap();
|
||||
assert!(Path::new(file).is_absolute() && Path::new(file).file_name() == Some("drawing.svg".as_ref()), "{file}");
|
||||
assert!(same(&Path::new(file).parent().unwrap().to_string_lossy(), &cwd), "{file} is not in {cwd:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The warnings a save gives, such as editing data left out of a PDF of one artboard of several, go
|
||||
/// to the Script Console.
|
||||
#[test]
|
||||
fn a_saves_warnings_go_to_the_console() {
|
||||
let base = folder("warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let save = format!(
|
||||
"Folder.userData; var o = new PDFSaveOptions(); o.preserveEditability = true; o.artboardRange = '1';\n\
|
||||
app.activeDocument.saveAs(new File({}), o);",
|
||||
quoted(&dir.join("one.pdf"))
|
||||
);
|
||||
let r = run(&mut s, &base, &save).unwrap();
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("saveAs: "))), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A document without unsaved changes closes with `SaveOptions.SAVECHANGES` and with no argument.
|
||||
#[test]
|
||||
fn a_document_without_unsaved_changes_closes_with_any_save_options() {
|
||||
|
||||
@@ -244,6 +244,13 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \
|
||||
SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel",
|
||||
),
|
||||
("", "AutoCADColors AutoCADCompatibility AutoCADExportFileFormat AutoCADExportOption AutoCADRasterFormat AutoCADUnit"),
|
||||
("AutoCADColors.", "Max16Colors Max256Colors Max8Colors TrueColors"),
|
||||
("AutoCADCompatibility.", "AutoCADRelease13 AutoCADRelease14 AutoCADRelease15 AutoCADRelease18 AutoCADRelease21 AutoCADRelease24"),
|
||||
("AutoCADExportFileFormat.", "DWG DXF"),
|
||||
("AutoCADExportOption.", "MaximizeEditability PreserveAppearance"),
|
||||
("AutoCADRasterFormat.", "JPEG PNG"),
|
||||
("AutoCADUnit.", "Centimeters Inches Millimeters Picas Pixels Points"),
|
||||
("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"),
|
||||
(
|
||||
"ColorDestination.",
|
||||
@@ -282,7 +289,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
),
|
||||
("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"),
|
||||
("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"),
|
||||
("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"),
|
||||
("ExportType.", "AUTOCAD AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"),
|
||||
("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"),
|
||||
("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"),
|
||||
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
|
||||
@@ -517,7 +524,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
/// option classes.
|
||||
const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \
|
||||
IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem \
|
||||
cmykColor EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions";
|
||||
cmykColor EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \
|
||||
PDFSaveOptions";
|
||||
|
||||
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
|
||||
/// own API, and what `vc.run` does depends on the command it runs.
|
||||
|
||||
@@ -152,7 +152,8 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
/// 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) {
|
||||
let o = i.object(id)?;
|
||||
if o.proto != Some(c.file_proto) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(match own_path(i, id)? {
|
||||
|
||||
@@ -204,7 +204,8 @@ struct Reading {
|
||||
path: Vec<Step>,
|
||||
function: Rc<str>,
|
||||
/// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under
|
||||
/// [`crate::FILE_REF_KEY`], and a plain object that has either key is refused.
|
||||
/// [`crate::FILE_REF_KEY`], and a plain object that has one of the keys, or
|
||||
/// [`crate::FOLDER_REF_KEY`], is refused.
|
||||
hosted: bool,
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,9 @@ pub(crate) struct Known {
|
||||
/// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts
|
||||
/// as a Folder object whatever the path names.
|
||||
pub unsure: bool,
|
||||
/// The script includes another file ([`Declared::includes`]), whose code may give a file's
|
||||
/// variables values the scan of that file does not read.
|
||||
pub others: bool,
|
||||
}
|
||||
|
||||
impl Known {
|
||||
@@ -75,6 +78,7 @@ impl Known {
|
||||
/// object only when both sides say so; otherwise it may hold a File object.
|
||||
pub fn add(&mut self, other: Known, entries: usize) {
|
||||
self.unsure |= other.unsure;
|
||||
self.others |= other.others;
|
||||
for (name, chain) in other.bound {
|
||||
if self.bound.len() < entries || self.bound.contains_key(&name) {
|
||||
self.bound.entry(name).or_insert(chain);
|
||||
@@ -286,8 +290,8 @@ struct ObjectValue {
|
||||
/// 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.
|
||||
/// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do`, a
|
||||
/// loop's parentheses or a label: 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)>,
|
||||
@@ -696,6 +700,8 @@ struct Analyzer<'s, 'a, 'l> {
|
||||
/// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver
|
||||
/// that is not such a variable.
|
||||
index_receiver: u8,
|
||||
/// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`].
|
||||
others: bool,
|
||||
/// The variables that may get another value when code read elsewhere runs: assigned inside a
|
||||
/// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]).
|
||||
/// None of them joins [`Analyzer::writers`].
|
||||
@@ -783,6 +789,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
objects: vec![],
|
||||
closed: None,
|
||||
index_receiver: 0,
|
||||
others: known.others || declared.includes,
|
||||
later: HashSet::new(),
|
||||
later_full: false,
|
||||
unsure: known.unsure || declared.unsure,
|
||||
@@ -1518,10 +1525,21 @@ 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.
|
||||
/// No variable joins when code the scan does not follow at that point may give it another value:
|
||||
/// a function body that assigns its name ([`Declared::body_assigned`], [`Analyzer::later`]), a
|
||||
/// member assignment of a property of that name, which may be the global object's
|
||||
/// ([`Declared::rebound`]), a function body that assigns a `saveAs` or `exportFile` property of
|
||||
/// any object ([`Declared::body_writer_assigned`]), code given as text or a `with` statement
|
||||
/// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that
|
||||
/// 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.unsure
|
||||
&& !self.others
|
||||
&& !self.declared.rebound.contains(&name)
|
||||
&& !self.declared.body_assigned.contains(name.as_str())
|
||||
&& !self.declared.body_writer_assigned
|
||||
&& !self.later_full
|
||||
&& !self.later.contains(&name)
|
||||
&& !self.declared.looped_full
|
||||
@@ -1855,7 +1873,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),
|
||||
files: std::mem::take(&mut self.files),
|
||||
folders,
|
||||
unsure: self.unsure,
|
||||
others: self.others,
|
||||
};
|
||||
(std::mem::take(&mut self.includes), module, known)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
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};
|
||||
use super::{
|
||||
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark,
|
||||
unquote, word,
|
||||
};
|
||||
|
||||
/// The names that give variables values the analysis doesn't read: a `with` statement makes an
|
||||
/// object's properties stand for names in its body (ECMA-262 3rd edition, section 12.10), and `eval`,
|
||||
@@ -67,6 +70,19 @@ 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 names a function body assigns by name (`d = …`, `d += …`, `d++`, `for (d in …)`) other than
|
||||
/// in a `var` statement's declarations, unless a body around the assignment declared the name with
|
||||
/// `var` before it. The function may run at any time after it is defined,
|
||||
/// also before its body in the text when it is a declaration, so a variable of that name may lose
|
||||
/// the value an assignment the analysis read gave it.
|
||||
pub(super) body_assigned: HashSet<&'s str>,
|
||||
/// A function body assigns a property named as one of [`catalog::DOM_FILE_WRITES`]
|
||||
/// (`o.saveAs = …`, `this['exportFile'] = …`). The function may run at any time after it is
|
||||
/// defined, and the object may be any variable's, so no variable's method of that name stays
|
||||
/// the script's own.
|
||||
pub(super) body_writer_assigned: bool,
|
||||
/// The file has an `#include` line: the included file's code may give its variables values.
|
||||
pub(super) includes: bool,
|
||||
/// The variables assigned inside a loop, its parentheses included (`name = …`), each by the
|
||||
/// 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`.
|
||||
@@ -197,7 +213,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
for t in lexer.by_ref() {
|
||||
match breaks.read(&t) {
|
||||
Read::Skip => {}
|
||||
Read::Directive => d.directive(),
|
||||
Read::Directive => d.directive(&t),
|
||||
Read::Token(sig) => d.token(sig),
|
||||
}
|
||||
}
|
||||
@@ -270,9 +286,43 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if t.word("function") && !member_mark(h0) && !word(h0, "function") {
|
||||
self.function = Some(depth);
|
||||
}
|
||||
if !self.bodies.is_empty() || self.untracked.is_some() {
|
||||
self.body_assignment(&t, depth);
|
||||
}
|
||||
self.h = [Some(t), h0, h1];
|
||||
}
|
||||
|
||||
/// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one
|
||||
/// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`].
|
||||
fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) {
|
||||
let [h0, h1, _] = self.h;
|
||||
let name = |s: Option<Sig<'s>>| s.filter(|s| s.kind == T::Ident).map(|s| s.text);
|
||||
let declares = word(h1, "var") || (is(h1, ",") && self.var_depth == Some(depth));
|
||||
let assigned = if t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")) {
|
||||
// `d = …`, `d += …` and `d++`, not `o.d = …` (a member: [`Declared::rebound`]) or `var d = …`.
|
||||
name(h0).filter(|_| !member_mark(h1) && !(t.text == "=" && declares))
|
||||
} else if t.kind == T::Ident && (is(h0, "++") || is(h0, "--")) {
|
||||
// `++d`.
|
||||
Some(t.text)
|
||||
} else if t.word("in") && (is(h1, "(") || word(h1, "var")) {
|
||||
// `for (d in …)`.
|
||||
name(h0)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A name the innermost body around `t` has declared with `var` before it is that body's own. A
|
||||
// name only an outer body declared is that body's variable, which a nested function may assign
|
||||
// before a call in the outer body runs.
|
||||
let own = |name: &str| self.untracked.is_none() && self.bodies.last().is_some_and(|b| b.names.contains(name));
|
||||
if let Some(name) = assigned.filter(|n| !own(n)) {
|
||||
if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) {
|
||||
self.out.body_assigned.insert(name);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `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`]).
|
||||
@@ -507,6 +557,9 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
None
|
||||
};
|
||||
if let Some(name) = property {
|
||||
if (!self.bodies.is_empty() || self.untracked.is_some()) && catalog::DOM_FILE_WRITES.contains(&name.as_str()) {
|
||||
self.out.body_writer_assigned = true;
|
||||
}
|
||||
if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) {
|
||||
self.out.rebound.insert(name);
|
||||
} else {
|
||||
@@ -613,7 +666,10 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
/// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. Inside a
|
||||
/// property's name in brackets it hides the tokens before the name (`this[`, a line, `'eval']`),
|
||||
/// so the name may be any.
|
||||
fn directive(&mut self) {
|
||||
fn directive(&mut self, t: &Token<'s>) {
|
||||
if directives::parse(t.text).known == Some("include") {
|
||||
self.out.includes = true;
|
||||
}
|
||||
if self.keys.iter().any(|k| k.member) {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
|
||||
@@ -868,7 +868,8 @@ fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() {
|
||||
|
||||
/// 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`.
|
||||
/// the variable `d`. A member assignment of a property `g` (`holder.this.g = …`) may be the global
|
||||
/// object's, so `g.saveAs` writes a file.
|
||||
#[test]
|
||||
fn labels_hidden_globals_and_other_objects_keep_writes_known() {
|
||||
let r = report(concat!(
|
||||
@@ -893,7 +894,7 @@ fn labels_hidden_globals_and_other_objects_keep_writes_known() {
|
||||
"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][..]));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17, 20][..]));
|
||||
}
|
||||
|
||||
/// Only a `var` statement directly in a function body or the global code that gives its first name
|
||||
@@ -925,6 +926,61 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() {
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..]));
|
||||
}
|
||||
|
||||
/// A literal's `saveAs` stays the script's own only while no code the check does not follow may give
|
||||
/// the variable another value: a declaration after a label, which `if` may skip, a function body that
|
||||
/// assigns the variable (its own method's, or a declaration's that runs before its text), a member
|
||||
/// assignment of a property of that name, which may be the global object's, a function body that
|
||||
/// assigns a `saveAs` or `exportFile` property of any object, code given as text, a `with` statement
|
||||
/// and an included file each leave the write reported. A function that declares its own variable of the
|
||||
/// name, or assigns another property of it, leaves it the script's own. A nested function that assigns
|
||||
/// a variable its enclosing body declared leaves the write reported too.
|
||||
#[test]
|
||||
fn a_save_as_other_code_may_replace_writes_a_file() {
|
||||
let cases: [(&str, &[usize]); 16] = [
|
||||
("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]),
|
||||
(
|
||||
"var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n",
|
||||
&[10],
|
||||
),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\nswap();\nd.saveAs(f);\nfunction swap() { d = app.activeDocument; }\n", &[4]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\nthis.d = app.activeDocument;\nd.saveAs(f);\n", &[4]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\neval(s);\nd.saveAs(f);\n", &[4]),
|
||||
("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\n#include \"other.jsx\"\nd.saveAs(f);\n", &[4]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\nwith ({d: app.activeDocument}) {\n d.saveAs(f);\n}\n", &[4]),
|
||||
(
|
||||
"var f = new File(p);\nfunction replace() { d.saveAs = app.activeDocument.saveAs; }\nvar d = {saveAs: function () {}};\nreplace();\nd.saveAs(f);\n",
|
||||
&[5],
|
||||
),
|
||||
(
|
||||
"var f = new File(p);\nfunction replace(o) { o['exportFile'] = w; }\nvar d = {exportFile: function () {}};\nreplace(d);\nd.exportFile(f);\n",
|
||||
&[5],
|
||||
),
|
||||
("var f = new File(p);\nfunction note() { d.n = 1; }\nvar d = {saveAs: function () {}};\nnote();\nd.saveAs(f);\n", &[]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]),
|
||||
(
|
||||
"var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d = app.activeDocument; }\n}\nrun();\n",
|
||||
&[5],
|
||||
),
|
||||
(
|
||||
"var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d += 1; }\n}\n",
|
||||
&[5],
|
||||
),
|
||||
(
|
||||
"var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d++; }\n}\n",
|
||||
&[5],
|
||||
),
|
||||
(
|
||||
"var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { for (d in o) {} }\n}\n",
|
||||
&[5],
|
||||
),
|
||||
];
|
||||
for (src, lines) in cases {
|
||||
let r = report(src);
|
||||
assert_eq!(feature(&r, "file.write").map_or(&[][..], |f| f.lines.as_slice()), lines, "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_calls_after_many_assignment_loops_have_bounded_work() {
|
||||
for reinitialize in [false, true] {
|
||||
|
||||
+21
-6
@@ -3322,7 +3322,20 @@ through `$`:
|
||||
with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to
|
||||
776.19; 100 writes one pixel per point whatever the raster effects resolution) for PNG24 and JPEG, `matteColor` (PNG24 and JPEG; only white, an `RGBColor` of 255, 255, 255, is accepted, and another color is an error), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and
|
||||
`coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and
|
||||
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s
|
||||
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `AutoCAD` (also written
|
||||
`ExportType.AUTOCAD`) takes `new ExportOptionsAutoCAD()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/)
|
||||
and writes a DXF file, as `document.export {format: dxf}` does, with `exportFileFormat`, `version`
|
||||
(`AutoCADRelease13`, `14`, `15`, `18`, `21` and `24` as the R13, R14, 2000, 2004, 2007 and 2010 formats), `unit`,
|
||||
`unitScaleRatio` (the drawing units for one `unit`, more than 0 and at most 1000), `colors`, `rasterFormat`,
|
||||
`exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`.
|
||||
An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and
|
||||
`unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values.
|
||||
`AutoCADRelease13`, `14` and `15` hold no true color: with them `colors` defaults to `Max256Colors`, and
|
||||
`AutoCADColors.TrueColors` throws an error.
|
||||
`AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an
|
||||
AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`,
|
||||
`AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit`
|
||||
hold the members the scripting constants page lists. `app.open`'s
|
||||
`options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with
|
||||
`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.
|
||||
@@ -3345,12 +3358,13 @@ through `$`:
|
||||
files a command reads or writes besides the one named, such as an SVG's linked files, are
|
||||
read and written only where the script's folders allow. `userInteractionLevel` does not change what a command
|
||||
does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the
|
||||
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with
|
||||
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.dxf`, `.svgz` with
|
||||
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
|
||||
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and
|
||||
when the script's folders refuse one of those files, none of them is written; a write that fails once the
|
||||
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and a
|
||||
DXF of a drawing with placed raster images writes each image it exports beside it as a PNG file, or a JPEG
|
||||
file with `rasterFormat` `AutoCADRasterFormat.JPEG`; those files must travel with the DXF. When the script's folders refuse one of those files, none of them is written; 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
|
||||
an error that says it is not available yet, as does `ExportType.FLASH`. 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
|
||||
@@ -3363,7 +3377,8 @@ through `$`:
|
||||
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
|
||||
file. A relative path that a file is saved or opened under is resolved against the working folder of the process that wrote or read it,
|
||||
for `fullName`, `path` and `close` alike. 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
|
||||
|
||||
@@ -1126,6 +1126,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- 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.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.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/).
|
||||
|
||||
Reference in new issue
Block a user