//! Saving, exporting and opening documents in the script object model: `Document.saveAs`,
//! `Document.exportFile`, `Document.fullName`, `Document.path`, `Document.saved`,
//! `Document.close`, `app.open` and `app.userInteractionLevel`, with the option classes the
//! help pages ,
//! ,
//! ,
//! ,
//! ,
//! ,
//! ,
//! ,
//! and
//! describe.
//!
//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's
//! transaction. The file is a `File` object, and the method reads and writes only where that
//! `File` may ([`super::super::files`]): the path is checked before the command runs, and the
//! command's own reads and writes leave out the files of the open documents that `vc.run`'s
//! commands may use.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - `saveAs` without options saves in the format the path's extension names; it writes the file
//! at the path as given. 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.
//! `exportFile` adds the format's extension unless the name already ends
//! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes
//! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art.
//! An SVG 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
//! `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, `-.ai`. An EPS save of a range of two or
//! more artboards writes the file at the path and `_.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 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.
//! - `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. 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.
//! - `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.
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::{
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.
pub const MAX_SCALE_PERCENT: f64 = 776.19;
/// The least a scale factor of a raster export takes, in percent: `document.export` writes at least
/// 0.01 pixels per point.
pub const MIN_SCALE_PERCENT: f64 = 1.0;
/// What the run keeps for these members: whether `userInteractionLevel` is `DONTDISPLAYALERTS`.
#[derive(Default)]
pub(in crate::script) struct State {
quiet: Cell,
}
/// 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",
&[
"ILLUSTRATOR8",
"ILLUSTRATOR9",
"ILLUSTRATOR10",
"ILLUSTRATOR11",
"ILLUSTRATOR12",
"ILLUSTRATOR13",
"ILLUSTRATOR14",
"ILLUSTRATOR15",
"ILLUSTRATOR16",
"ILLUSTRATOR17",
"ILLUSTRATOR19",
"JAPANESEVERSION3",
],
),
("PDFCompatibility", &["ACROBAT4", "ACROBAT5", "ACROBAT6", "ACROBAT7", "ACROBAT8"]),
("PDFBoxType", &["PDFARTBOX", "PDFBLEEDBOX", "PDFBOUNDINGBOX", "PDFCROPBOX", "PDFMEDIABOX", "PDFTRIMBOX"]),
("EPSPreview", &["BWTIFF", "COLORTIFF", "TRANSPARENTCOLORTIFF", "None"]),
("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"]),
];
/// 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";
/// The default a listed option that is not mapped keeps: a value equal to it is accepted.
#[derive(Clone, Copy)]
enum Default {
Bool(bool),
Num(f64),
Text(&'static str),
/// An enumerated value, by its enumeration and member (`("DownsampleMethod", "NODOWNSAMPLE")` for
/// `DownsampleMethod.NODOWNSAMPLE`).
Member(&'static str, &'static str),
/// White as an RGB color: an object whose `red`, `green` and `blue` are 255 (its `typename`, when
/// it has one, `RGBColor`).
White,
/// The help page gives no default: any value throws.
Unset,
}
impl Default {
fn matches(self, d: &Data) -> bool {
match (self, d) {
(Default::Bool(a), Data::Bool(b)) => a == *b,
(Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9,
(Default::Text(a), Data::String(b)) => a == b,
(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 full = |c: &str| items.iter().any(|(k, v)| k == c && matches!(v, Data::Number(n) if (n - 255.0).abs() < 1e-9));
let rgb = items.iter().all(|(k, v)| match k.as_str() {
"typename" => matches!(v, Data::String(s) if s == "RGBColor"),
"red" | "green" | "blue" => true,
_ => false,
});
rgb && ["red", "green", "blue"].into_iter().all(full)
}
_ => false,
}
}
}
/// A mapped option: from its name and value into the command's params, `Ok(false)` for a name it
/// does not map.
type Mapper = fn(&str, &Data, &mut Map) -> std::result::Result;
/// An option class: its name, its mapped options, its listed options that are not mapped, and the
/// defaults a new object starts with.
struct OptionClass {
name: &'static str,
map: Mapper,
kept: &'static [(&'static str, Default)],
starts: fn() -> Vec<(&'static str, Data)>,
}
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 {
match d {
Data::Number(n) => {
whole(*n).filter(|n| (lo..=hi).contains(n)).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from {lo} to {hi}")))
}
_ => Err(HostError::Type(format!("{what} must be a number"))),
}
}
/// The member of `enumeration` that `d` names (`"Enumeration.MEMBER"`), one of `members`.
fn member<'a>(d: &'a Data, enumeration: &str, members: &[&str], what: &str) -> std::result::Result<&'a str, HostError> {
let bad = || HostError::Type(format!("{what} must be a {enumeration} value"));
let Data::String(s) = d else { return Err(bad()) };
let m = s.strip_prefix(enumeration).and_then(|r| r.strip_prefix('.')).ok_or_else(bad)?;
if members.contains(&m) { Ok(m) } else { Err(bad()) }
}
/// A `Compatibility` value: the versions from 17 on are the file VectorCraft writes; older ones are
/// not available.
fn compatibility(class: &str, d: &Data) -> std::result::Result<(), HostError> {
let all = ENUMS.iter().find(|(n, _)| *n == "Compatibility").map_or(&[][..], |(_, m)| *m);
match member(d, "Compatibility", all, &format!("{class}.compatibility"))? {
"ILLUSTRATOR17" | "ILLUSTRATOR19" => Ok(()),
_ => Err(not_available(class, "compatibility")),
}
}
/// 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) -> std::result::Result<(), HostError> {
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")));
}
if !s.trim().is_empty() {
p.insert("range".into(), json!(s));
}
Ok(())
}
// ---- Save options ----
fn ai_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result {
let what = format!("IllustratorSaveOptions.{name}");
match name {
"compressed" => p.insert("compress".into(), json!(boolean(d, &what)?)),
"pdfCompatible" => p.insert("pdfCompatible".into(), json!(boolean(d, &what)?)),
"embedICCProfile" => p.insert("embedProfiles".into(), json!(boolean(d, &what)?)),
"compatibility" => {
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) -> std::result::Result {
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) -> 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