mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 12:35:48 -05:00
Merge main into feat/scripts-api-d8c-rasterize-capture
This commit is contained in:
commit
7b433a52fe
21 files changed
+978
-48
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
|
||||
@@ -1261,10 +1271,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) })
|
||||
|
||||
@@ -71,9 +71,163 @@ fn export(s: &mut Session, p: Value) -> (Vec<u8>, Vec<String>) {
|
||||
(bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect())
|
||||
}
|
||||
|
||||
/// The transparency `pdf` has, in its dictionaries.
|
||||
/// Whether `b` ends a PDF token: white space or a delimiter.
|
||||
fn ends_token(b: u8) -> bool {
|
||||
b.is_ascii_whitespace() || b"()<>[]{}/%".contains(&b)
|
||||
}
|
||||
|
||||
/// The offset of object `number generation` in the cross-reference tables of `pdf`, starting at the
|
||||
/// `startxref` at `startxref` and following `/Prev`.
|
||||
fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) -> Option<usize> {
|
||||
let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::<usize>().ok()?;
|
||||
let mut visited = vec![];
|
||||
loop {
|
||||
if visited.contains(&offset) {
|
||||
return None;
|
||||
}
|
||||
visited.push(offset);
|
||||
let table = String::from_utf8_lossy(pdf.get(offset..)?);
|
||||
let mut words = table.split_ascii_whitespace();
|
||||
if words.next()? != "xref" {
|
||||
return None;
|
||||
}
|
||||
loop {
|
||||
let first = words.next()?;
|
||||
if first == "trailer" {
|
||||
break;
|
||||
}
|
||||
let first = first.parse::<usize>().ok()?;
|
||||
let count = words.next()?.parse::<usize>().ok()?;
|
||||
for index in 0..count {
|
||||
let at = words.next()?.parse::<usize>().ok()?;
|
||||
let entry_generation = words.next()?.parse::<usize>().ok()?;
|
||||
let status = words.next()?;
|
||||
if first.checked_add(index)? == number {
|
||||
return (status == "n" && entry_generation == generation).then_some(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
let trailer = table.split_once("trailer")?.1.split_once(">>")?.0;
|
||||
let mut words = trailer.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty());
|
||||
words.find(|&w| w == "Prev")?;
|
||||
offset = words.next()?.parse().ok()?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary
|
||||
/// after the object's `obj` keyword. The keyword counts only at the start of `text` or after white
|
||||
/// space, so a name such as `/Tag/obj` is not taken for it. An indirect length is read from its
|
||||
/// object in `pdf`. `None` when it is missing or cannot be read.
|
||||
fn stream_length(text: &[u8], pdf: &[u8]) -> Option<usize> {
|
||||
let from = text
|
||||
.windows(3)
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find(|&(at, w)| w == b"obj" && (at == 0 || matches!(text[at - 1], b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' ')))
|
||||
.map_or(0, |(at, _)| at + 3);
|
||||
let dict = &text[from..];
|
||||
let mut i = dict.windows(2).position(|w| w == b"<<")? + 2;
|
||||
let mut depth = 1usize;
|
||||
let mut length = None;
|
||||
while i < dict.len() && depth > 0 {
|
||||
let rest = &dict[i..];
|
||||
if rest.starts_with(b"<<") {
|
||||
depth += 1;
|
||||
i += 2;
|
||||
} else if rest.starts_with(b">>") {
|
||||
depth -= 1;
|
||||
i += 2;
|
||||
} else if rest[0] == b'<' {
|
||||
// A hex string.
|
||||
i += rest.iter().position(|&b| b == b'>').map_or(rest.len(), |at| at + 1);
|
||||
} else if depth == 1 && rest.starts_with(b"/Length") && rest.get(7).is_none_or(|&b| ends_token(b)) {
|
||||
let value = String::from_utf8_lossy(&rest[7..]);
|
||||
let words: Vec<&str> = value.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()).take(3).collect();
|
||||
length = match words[..] {
|
||||
// `n g R` is an indirect length: the integer in object `n g`.
|
||||
[n, g, "R", ..] => {
|
||||
let header = format!("{n} {g} obj");
|
||||
let read_length = |at: usize| {
|
||||
let body = String::from_utf8_lossy(&pdf[at + header.len()..]);
|
||||
match body.split_ascii_whitespace().take(2).collect::<Vec<_>>()[..] {
|
||||
[n, "endobj"] => n.parse::<usize>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
if let Some(startxref) = pdf.windows(b"startxref".len()).rposition(|w| w == b"startxref") {
|
||||
let at =
|
||||
xref_offset(pdf, n.parse().ok()?, g.parse().ok()?, startxref).expect("stream /Length reference is missing from xref");
|
||||
let object = pdf.get(at..).expect("stream /Length xref offset is outside the file");
|
||||
assert!(object.starts_with(header.as_bytes()), "stream /Length xref offset has a different object");
|
||||
read_length(at)
|
||||
} else {
|
||||
pdf.windows(header.len())
|
||||
.enumerate()
|
||||
// An object header starts a line, and the length object holds one integer.
|
||||
.filter(|&(at, w)| w == header.as_bytes() && (at == 0 || matches!(pdf[at - 1], b'\r' | b'\n')))
|
||||
.find_map(|(at, _)| read_length(at))
|
||||
}
|
||||
}
|
||||
[n, ..] => n.parse::<usize>().ok(),
|
||||
[] => None,
|
||||
};
|
||||
i += 7;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
length
|
||||
}
|
||||
|
||||
/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out:
|
||||
/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time
|
||||
/// and can spell `/BM`.
|
||||
fn transparency(pdf: &[u8]) -> Vec<&'static str> {
|
||||
let text = String::from_utf8_lossy(pdf);
|
||||
let mut text = Vec::with_capacity(pdf.len());
|
||||
let mut i = 0;
|
||||
while i < pdf.len() {
|
||||
let rest = &pdf[i..];
|
||||
// A keyword follows white space or a dictionary's `>>`; after `/` it is part of a name.
|
||||
let keyword_start = i == 0 || pdf[i - 1].is_ascii_whitespace() || pdf[i - 1] == b'>';
|
||||
if keyword_start && rest.starts_with(b"endstream") {
|
||||
text.extend_from_slice(b"endstream");
|
||||
i += b"endstream".len();
|
||||
} else if keyword_start && rest.starts_with(b"stream") && matches!(rest.get(b"stream".len()), Some(b'\r' | b'\n')) {
|
||||
// Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to
|
||||
// `endstream`); its bytes are not PDF syntax.
|
||||
let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 };
|
||||
i = match stream_length(&text, pdf) {
|
||||
Some(n) => {
|
||||
let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream");
|
||||
while matches!(pdf.get(end), Some(b'\r' | b'\n')) {
|
||||
end += 1;
|
||||
}
|
||||
assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream");
|
||||
end
|
||||
}
|
||||
None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").expect("stream has no endstream"),
|
||||
};
|
||||
} else if rest[0] == b'(' {
|
||||
// A literal string: balanced parentheses, with `\` escaping the next byte.
|
||||
let mut depth = 0usize;
|
||||
while i < pdf.len() {
|
||||
match pdf[i] {
|
||||
b'\\' => i += 1,
|
||||
b'(' => depth += 1,
|
||||
b')' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
text.push(rest[0]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let text = String::from_utf8_lossy(&text);
|
||||
let mut found = vec![];
|
||||
for (what, there) in [
|
||||
("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")),
|
||||
@@ -193,3 +347,79 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() {
|
||||
s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check
|
||||
/// reads the file's dictionaries only, not its strings or its XMP packet.
|
||||
#[test]
|
||||
fn the_transparency_check_skips_strings_and_metadata() {
|
||||
let pdf = b"%PDF-1.3\n5 0 obj\n<</Title(a/BM/SMask/CA 0.5)>>\nendobj\n6 0 obj\n<</Type/Metadata>>\nstream\n<?xpacket begin=\"\"?><x>q/BMx/S/Transparency</x><?xpacket end=\"r\"?>\nendstream\nendobj\ntrailer\n<</ID[(hIX/BMcE)(hIX/BMcE)]>>\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
assert_eq!(transparency(b"<</ExtGState<</G<</BM/Multiply/CA 0.5>>>>>>"), vec!["blend modes", "opacity"]);
|
||||
// A `(` in image data starts no string, and nested and escaped parentheses end where the
|
||||
// string does.
|
||||
let pdf = b"<</Length 3>>\nstream\n(\x00(\nendstream\n<</T(a(b)c\\)d)/SMask 9 0 R>>\n<</S/Transparency>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]);
|
||||
// Stream data is skipped by its length, even when it holds `endstream` itself.
|
||||
let pdf = b"1 0 obj\n<</Length 15>>\nstream\nendstream (/BM\nendstream\nendobj\n<</BM/Multiply>>";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Length 13>>\nstream\nendstream /BM\nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabc\r\nendstream\nendobj\n<</SMask 9 0 R>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabcendstream\nendobj\n<</BM/Multiply>>";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
// Only the stream dictionary's own `/Length` counts, not one in a nested dictionary.
|
||||
let pdf = b"1 0 obj\n<</Length 4/DecodeParms<</Length 1>>>>\nstream\n/BM \nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
// `stream` inside a name is not the keyword.
|
||||
let pdf = b"1 0 obj\n<</Type/Upstream\n/BM/Multiply>>\nendobj\n";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Type/stream\n/SMask 9 0 R>>\nendobj\n";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
// An indirect length is read from its object, so `endstream` in the data does not end it.
|
||||
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nendstream /BM\nendstream\nendobj\n2 0 obj\n13\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
let payload = b"2 0 obj\n13\nendobj\nendstream /BM";
|
||||
let mut pdf = b"%PDF-1.3\n".to_vec();
|
||||
let stream_at = pdf.len();
|
||||
pdf.extend_from_slice(b"1 0 obj\n<</Length 2 0 R>>\nstream\n");
|
||||
pdf.extend_from_slice(payload);
|
||||
pdf.extend_from_slice(b"\nendstream\nendobj\n");
|
||||
let length_at = pdf.len();
|
||||
pdf.extend_from_slice(format!("2 0 obj\n{}\nendobj\n", payload.len()).as_bytes());
|
||||
let catalog_at = pdf.len();
|
||||
pdf.extend_from_slice(b"3 0 obj\n<</Type/Catalog/Pages 4 0 R>>\nendobj\n");
|
||||
let pages_at = pdf.len();
|
||||
pdf.extend_from_slice(b"4 0 obj\n<</Type/Pages/Kids[]/Count 0>>\nendobj\n");
|
||||
let xref_at = pdf.len();
|
||||
pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n");
|
||||
for at in [stream_at, length_at, catalog_at, pages_at] {
|
||||
pdf.extend_from_slice(format!("{at:010} 00000 n\r\n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<</Size 5/Root 3 0 R>>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes());
|
||||
assert_eq!(transparency(&pdf), Vec::<&str>::new());
|
||||
// A stream with no length and no `endstream` fails rather than hiding the rest of the file.
|
||||
let pdf = b"1 0 obj\n<<>>\nstream\nabc\n<</SMask 9 0 R>>";
|
||||
assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err());
|
||||
for length in [2, 20, 999, usize::MAX] {
|
||||
let pdf = format!("1 0 obj\n<</Length {length}>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R/BM/Multiply>>");
|
||||
let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic");
|
||||
let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::<String>().map(String::as_str));
|
||||
assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A name that ends in `obj`, such as `/Tag/obj`, is not the object's `obj` keyword, so the
|
||||
/// stream's `/Length` is still read from the outer dictionary.
|
||||
#[test]
|
||||
fn the_stream_length_skips_names_that_end_in_obj() {
|
||||
let text = b"1 0 obj\n<</Length 5/Tag/obj>>\nstream\n";
|
||||
assert_eq!(stream_length(text, text), Some(5));
|
||||
// NUL is PDF white space, so it may separate the generation number from `obj`.
|
||||
let text = b"1 0 obj\n<</Length 9>>\nstream\nabc\nendstream\nendobj\n2 0\0obj\n<</Length 5>>\nstream\n";
|
||||
assert_eq!(stream_length(text, text), Some(5));
|
||||
let pdf = b"1 0 obj\n<</Length 13/Tag/obj>>\nstream\nendstream /BM\nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
}
|
||||
@@ -692,7 +692,19 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio
|
||||
}
|
||||
}
|
||||
}
|
||||
let png = img.to_png().map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
// The PNG is written with fast compression: the exports that flatten (EPS, PDF 1.3) decode it
|
||||
// again right away.
|
||||
let raw = craft_image_codecs::Image::from_raw(
|
||||
img.width,
|
||||
img.height,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
img.to_straight(),
|
||||
)
|
||||
.map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
|
||||
let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts)
|
||||
.map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip })
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -3194,7 +3194,9 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
for (name, members) in
|
||||
ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(raster_capture::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
|
||||
@@ -27,6 +28,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
|
||||
@@ -41,8 +48,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.
|
||||
@@ -65,6 +72,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::{
|
||||
@@ -87,6 +95,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",
|
||||
&[
|
||||
@@ -183,6 +200,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";
|
||||
|
||||
@@ -197,7 +218,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,
|
||||
}
|
||||
|
||||
@@ -210,7 +232,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,
|
||||
@@ -657,9 +679,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).
|
||||
@@ -670,9 +801,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) },
|
||||
@@ -867,11 +998,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));
|
||||
@@ -879,7 +1025,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 };
|
||||
@@ -1159,7 +1306,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>| {
|
||||
|
||||
@@ -350,6 +350,41 @@ fn gradients_rasterize_and_flat_areas_stay_vector() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A rasterized area is stored as a PNG written with fast compression: its zlib header (RFC 1950)
|
||||
/// gives compression level 0, the fastest.
|
||||
#[test]
|
||||
fn rasterized_areas_are_png_with_fast_compression() {
|
||||
let _settings = settings_lock();
|
||||
let mut s = session();
|
||||
let g = rect(&mut s, 10.0, 10.0, 100.0, 100.0, "#000000");
|
||||
run(
|
||||
&mut s,
|
||||
"paint.setFill",
|
||||
json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}),
|
||||
);
|
||||
run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40}));
|
||||
let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "preset": "high"}));
|
||||
assert_eq!(rasterized, 1);
|
||||
let mut keys = vec![];
|
||||
node(&s, ids[0]).walk(&mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind {
|
||||
keys.push(im.key.clone());
|
||||
}
|
||||
});
|
||||
let [key] = &keys[..] else { panic!("one image: {keys:?}") };
|
||||
let png = &s.doc().unwrap().doc.images[key].bytes;
|
||||
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG");
|
||||
let mut at = 8;
|
||||
let level = loop {
|
||||
let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) else { panic!("a PNG with image data") };
|
||||
if kind == b"IDAT" {
|
||||
break png[at + 9] >> 6;
|
||||
}
|
||||
at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize;
|
||||
};
|
||||
assert_eq!(level, 0, "zlib FLEVEL of the stored PNG");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_rasterized_area_is_placed_whole() {
|
||||
let _settings = settings_lock();
|
||||
|
||||
@@ -439,13 +439,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"] {
|
||||
@@ -623,6 +627,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]
|
||||
@@ -706,7 +789,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};
|
||||
@@ -743,9 +826,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);
|
||||
@@ -1048,6 +1132,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!(
|
||||
@@ -1070,6 +1160,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"),
|
||||
@@ -1374,6 +1499,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() {
|
||||
|
||||
@@ -245,6 +245,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.",
|
||||
@@ -283,7 +290,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"),
|
||||
@@ -523,8 +530,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
/// rasterize and image capture 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 \
|
||||
ImageCaptureOptions RasterizeOptions";
|
||||
cmykColor EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \
|
||||
PDFSaveOptions ImageCaptureOptions RasterizeOptions";
|
||||
|
||||
/// 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;
|
||||
}
|
||||
|
||||
@@ -883,7 +883,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!(
|
||||
@@ -908,7 +909,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
|
||||
@@ -940,6 +941,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] {
|
||||
|
||||
@@ -301,6 +301,28 @@ pub(crate) fn column_of<'a>(layout: &'a Layout<String>, panel: &str) -> Option<(
|
||||
Some((edge, column))
|
||||
}
|
||||
|
||||
/// Where the dock last drew the docked column holding `panel`; none until the dock has drawn it, and while `panel`
|
||||
/// floats or is closed.
|
||||
pub(crate) fn column_rect(app: &VectorcraftApp, panel: &str) -> Option<egui::Rect> {
|
||||
let (Some(_), column) = column_of(layout_of(&app.ui), panel)? else { return None };
|
||||
app.dock_rt.columns.iter().find(|(first, _)| column.panels().any(|p| p == first)).map(|(_, rect)| *rect)
|
||||
}
|
||||
|
||||
/// The top left a new floating window of `panel` takes beside the docked column holding `beside`: level with the
|
||||
/// column's top, the cascade inset away from it on the side toward the middle of the float space. None until the dock
|
||||
/// has drawn that column.
|
||||
pub(crate) fn float_origin_beside(app: &VectorcraftApp, panel: &str, beside: &str) -> Option<egui::Pos2> {
|
||||
let column = column_rect(app, beside)?;
|
||||
let space = command_space(app);
|
||||
let x = if column.center().x <= space.area.center().x {
|
||||
column.right() + space.inset
|
||||
} else {
|
||||
let width = space.size_of(&DragUnit::Panel(panel.to_owned()), None).x;
|
||||
column.left() - space.inset - width
|
||||
};
|
||||
Some(egui::pos2(x, column.top()))
|
||||
}
|
||||
|
||||
/// Is the dock's outer column of panels (Properties · Layers · Libraries) collapsed to icons?
|
||||
pub(crate) fn dock_collapsed(ui: &UiState) -> bool {
|
||||
dock_columns(layout_of(ui)).first().is_some_and(|c| c.iconic)
|
||||
|
||||
@@ -146,7 +146,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option<Rgba>) {
|
||||
}
|
||||
|
||||
/// The app's sizes over the framework's size sets (`sizes.json`): push buttons have the app's 4-point corners
|
||||
/// where the sets give pills, the Home title is 26-point with a 36-point call to action, 28-point New and Open with 16
|
||||
/// where the sets give pills, the Home title is 24-point on a 29-point line (its nominal 26 points on 32 at the 92%
|
||||
/// the body type below is set at) with a 36-point call to action, 28-point New and Open with 16
|
||||
/// points beside their labels and 24-point link rows. Home's margin and the gaps between its title, actions, sections,
|
||||
/// headings and links are the framework's page tokens, which follow its spacing scale (`space.gap.*`). The compact set
|
||||
/// takes the reference app's metrics:
|
||||
@@ -159,8 +160,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option<Rgba>) {
|
||||
const SIZES: &[u8] = br#"{
|
||||
"all": {
|
||||
"radius.button": 4,
|
||||
"typography.display.size": 26,
|
||||
"typography.display.line_height": 32,
|
||||
"typography.display.size": 24,
|
||||
"typography.display.line_height": 29,
|
||||
"size.page.action": 36,
|
||||
"size.page.button": 28,
|
||||
"size.page.button_side": 16,
|
||||
@@ -236,6 +237,37 @@ mod tests {
|
||||
assert!(AppSizes::parse(SIZES).is_ok_and(|sizes| !sizes.is_empty()));
|
||||
}
|
||||
|
||||
/// The Home title (the display type) is set at the same scale as the compact body type, so it keeps the nominal
|
||||
/// 26-point title over a 13-point body proportion, and its line keeps the framework's display line proportion.
|
||||
#[test]
|
||||
fn the_home_title_is_scaled_with_the_body_type() {
|
||||
use craft::theme::Size;
|
||||
use craft::ui::runtime::env::{Env, RootEnv};
|
||||
use craft::ui::testing::Fixture;
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
const NOMINAL_TITLE_OVER_BODY: f32 = 26.0 / 13.0;
|
||||
let typography = |sizes: Arc<AppSizes>| {
|
||||
let seen = Rc::new(Cell::new(None));
|
||||
let seen_in = Rc::clone(&seen);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let t = Env::of(ui).tokens.tokens().typography;
|
||||
seen_in.set(Some((t.display, t.body)));
|
||||
});
|
||||
let mut root = RootEnv::new().density(Size::Compact);
|
||||
root.sizes = sizes;
|
||||
fixture.root(root);
|
||||
fixture.frame(vec![]);
|
||||
seen.get().expect("the fixture drew a frame")
|
||||
};
|
||||
let (display, body) = typography(app_sizes());
|
||||
let ratio = display.size / body.size;
|
||||
assert!((ratio - NOMINAL_TITLE_OVER_BODY).abs() < 0.05, "a {}-point title over a {}-point body", display.size, body.size);
|
||||
let (framework, _) = typography(Arc::new(AppSizes::default()));
|
||||
let (line, framework_line) = (display.line_height / display.size, framework.line_height / framework.size);
|
||||
assert!((line - framework_line).abs() < 0.05, "a {}-point line for a {}-point title", display.line_height, display.size);
|
||||
}
|
||||
|
||||
/// Home's margin and gaps are the framework's page tokens: no size set gives them points of its own, so they follow
|
||||
/// the framework's spacing scale.
|
||||
#[test]
|
||||
|
||||
@@ -294,11 +294,17 @@ pub(crate) fn is_floating(app: &VectorcraftApp, toolbar: Option<&str>, key: &str
|
||||
strips(app, toolbar).iter().any(|g| g.first() == Some(&key))
|
||||
}
|
||||
|
||||
/// Float the group `first` of `owner` as a strip at `at` (none: the canvas's corner).
|
||||
/// Float the group `first` of `owner` as a strip at `at`. Without `at` the strip opens at the canvas's corner, or,
|
||||
/// before a view has been laid out, beside `owner`'s docked rail, else beside the Tools panel's.
|
||||
fn place_strip(app: &mut VectorcraftApp, owner: &Owner, first: &str, at: Option<Pos2>) -> Result<(), String> {
|
||||
let at = at.unwrap_or_else(|| app.canvas_view().map_or(Pos2::ZERO, |v| v.rect.min));
|
||||
let id = strip_id(owner, first);
|
||||
let at = at
|
||||
.or_else(|| app.canvas_view().map(|v| v.rect.min))
|
||||
.or_else(|| crate::panel_docking::float_origin_beside(app, &id, &owner.panel()))
|
||||
.or_else(|| crate::panel_docking::float_origin_beside(app, &id, TOOLS))
|
||||
.unwrap_or(Pos2::ZERO);
|
||||
// A width of 0 leaves the window's width to the panel's grid.
|
||||
crate::panel_docking::place_floating(app, &strip_id(owner, first), at, 0.0)
|
||||
crate::panel_docking::place_floating(app, &id, at, 0.0)
|
||||
}
|
||||
|
||||
/// Float the toolbar group (of the current layout) holding `tool` as a strip of tool buttons, put
|
||||
|
||||
@@ -483,6 +483,30 @@ fn window_float_tools_floats_and_puts_back_a_group() {
|
||||
assert!(strip_rect(&app, "rectangle").is_none() && !is_floating(&app, None, "pen"));
|
||||
}
|
||||
|
||||
/// `window.floatTools` run before a view has been laid out (right after a document opens, or with none open) floats the
|
||||
/// strip beside the docked Tools rail, not over it, and the strip stays clear of the rail once the frames are drawn.
|
||||
#[test]
|
||||
fn a_strip_floated_before_a_view_is_laid_out_opens_beside_the_tools_rail() {
|
||||
for (case, document) in [("document just opened", true), ("no document", false)] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let ctx = crate::testing::ui_context();
|
||||
settled(&mut app, &ctx, 0.0, 900.0);
|
||||
if document {
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
}
|
||||
assert!(app.canvas_view().is_none(), "{case}: no view has been laid out yet");
|
||||
let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail is docked"));
|
||||
app.run("window.floatTools", json!({"tool": "pen"})).unwrap();
|
||||
let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip floats"));
|
||||
assert!(strip.left() >= rail.right(), "{case}: the strip {strip:?} opens right of the rail {rail:?}");
|
||||
assert!((strip.top() - rail.top()).abs() <= f32::EPSILON, "{case}: the strip {strip:?} is level with the rail {rail:?}");
|
||||
settled(&mut app, &ctx, 1.0, 900.0);
|
||||
let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail stays docked"));
|
||||
let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip still floats"));
|
||||
assert!(!strip.intersects(rail), "{case}: the strip {strip:?} is clear of the rail {rail:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A floated group is a panel of the workspace's layout: a saved workspace brings it back, the built-in ones have none.
|
||||
#[test]
|
||||
fn workspaces_keep_floating_flyouts_and_reset_puts_them_back() {
|
||||
|
||||
@@ -64,6 +64,10 @@ pub struct WorkspaceRecord {
|
||||
/// Tabs closed together by a panel shortcut.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub docking_hidden_groups: Vec<Vec<String>>,
|
||||
/// The panel open from a column collapsed to icons (built-in workspaces: the panel the
|
||||
/// workspace is for; workspaces saved without this field: none).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub open_panel: Option<String>,
|
||||
/// The tool each flyout group of the main Tools shows (built-in workspaces: the first).
|
||||
pub tools_last_used: LastUsed<String>,
|
||||
/// The toolbars made with New Toolbar in this workspace (built-in workspaces: none).
|
||||
@@ -87,6 +91,7 @@ impl Default for WorkspaceRecord {
|
||||
status_bar: true,
|
||||
help_bar: true,
|
||||
docking_hidden_groups: Vec::new(),
|
||||
open_panel: None,
|
||||
tools_last_used: LastUsed::default(),
|
||||
toolbars: Vec::new(),
|
||||
}
|
||||
@@ -245,25 +250,30 @@ pub fn builtins() -> Vec<Builtin> {
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.task_bar = false;
|
||||
x.open_panel = Some("color".into());
|
||||
}),
|
||||
w("Automation", &["layers", "actions"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("actions".into());
|
||||
}),
|
||||
w("Layout", &["layers", "align"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("align".into());
|
||||
}),
|
||||
w("Painting", &["brushes"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("brushes".into());
|
||||
})
|
||||
.double_tools(),
|
||||
w("Printing and Proofing", &["info"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("info".into());
|
||||
}),
|
||||
w("Tracing", &["layers"], &|x| {
|
||||
x.control_bar = true;
|
||||
@@ -274,16 +284,19 @@ pub fn builtins() -> Vec<Builtin> {
|
||||
x.control_bar = true;
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("character".into());
|
||||
}),
|
||||
w("Web", &["symbols"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("symbols".into());
|
||||
}),
|
||||
w(TOUCH, &["align"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.task_bar = true;
|
||||
x.open_panel = Some("align".into());
|
||||
}),
|
||||
]
|
||||
}
|
||||
@@ -387,6 +400,7 @@ pub fn record(ui: &UiState) -> WorkspaceRecord {
|
||||
status_bar: ui.status_bar,
|
||||
help_bar: ui.help_bar,
|
||||
docking_hidden_groups: ui.docking_hidden_groups.clone(),
|
||||
open_panel: ui.open_panel.clone(),
|
||||
tools_last_used: ui.tools_last_used.clone(),
|
||||
toolbars: ui.custom_toolbars.clone(),
|
||||
}
|
||||
@@ -412,6 +426,7 @@ fn apply_record(ui: &mut UiState, w: &WorkspaceRecord) {
|
||||
ui.status_bar = w.status_bar;
|
||||
ui.help_bar = w.help_bar;
|
||||
ui.docking_hidden_groups = w.docking_hidden_groups.clone();
|
||||
ui.open_panel = w.open_panel.clone();
|
||||
ui.tools_last_used = w.tools_last_used.clone();
|
||||
ui.custom_toolbars = w.toolbars.clone();
|
||||
crate::custom_toolbars::sanitize(&mut ui.custom_toolbars);
|
||||
@@ -450,10 +465,19 @@ pub fn switch(app: &mut VectorcraftApp, key: &str) -> Result<String, String> {
|
||||
let w = ui.workspaces.edited.get(&id).cloned().unwrap_or_else(|| saved_record(&ui.workspaces, &id));
|
||||
apply_record(ui, &w);
|
||||
crate::panel_docking::reconcile(&mut ui.dock_workspace);
|
||||
close_stale_flyout(ui);
|
||||
crate::panel_docking::show_panels(app);
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Close the open panel when the layout now in use does not show it from a column collapsed to
|
||||
/// icons (it was moved, expanded or closed).
|
||||
fn close_stale_flyout(ui: &mut UiState) {
|
||||
if ui.open_panel.as_ref().is_some_and(|panel| !crate::panel_docking::layout_of(ui).opens_in_flyout(panel)) {
|
||||
ui.open_panel = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset the current workspace to the way it was saved, dropping its changes.
|
||||
pub fn reset(app: &mut VectorcraftApp) -> String {
|
||||
let ui = &mut app.ui;
|
||||
@@ -467,6 +491,7 @@ pub fn reset(app: &mut VectorcraftApp) -> String {
|
||||
apply_record(ui, &w);
|
||||
ui.custom_toolbars = toolbars;
|
||||
crate::panel_docking::reconcile(&mut ui.dock_workspace);
|
||||
close_stale_flyout(ui);
|
||||
crate::panel_docking::show_panels(app);
|
||||
current_name(&app.ui).to_string()
|
||||
}
|
||||
@@ -715,12 +740,64 @@ mod tests {
|
||||
switch(&mut app, "Essentials Classic").unwrap();
|
||||
assert!(app.ui.control_bar && app.ui.view.rulers && app.ui.toolbar_advanced);
|
||||
assert!(front(&app.ui, "color"));
|
||||
assert_eq!(app.ui.open_panel.as_deref(), Some("color"));
|
||||
assert_eq!(current_name(&app.ui), "Essentials Classic");
|
||||
switch(&mut app, "essentials").unwrap();
|
||||
assert!(!app.ui.control_bar && !app.ui.view.rulers);
|
||||
assert_eq!(app.ui.open_panel, None);
|
||||
assert_eq!(app.ui.brightness, crate::theme::Brightness::Light);
|
||||
}
|
||||
|
||||
/// A built-in workspace shows the panel it is for, from its collapsed column too: the second
|
||||
/// panel it brings forward (Automation's Actions) as well as the only one (Painting's
|
||||
/// Brushes). A panel closed there stays closed when the workspace is left and switched back
|
||||
/// to, and Reset opens it again.
|
||||
#[test]
|
||||
fn builtin_workspaces_show_their_panel_after_switch_and_reset() {
|
||||
let showing = crate::panel_docking::showing;
|
||||
let mut app = app();
|
||||
for (name, panel) in [("Painting", "brushes"), ("Automation", "actions"), ("Essentials Classic", "color")] {
|
||||
switch(&mut app, name).unwrap();
|
||||
assert!(showing(&app.ui, panel), "{name} shows {panel}");
|
||||
}
|
||||
assert!(crate::panel_docking::layout_of(&app.ui).opens_in_flyout(&"color".to_string()), "Classic's Color opens from its icon");
|
||||
app.ui.open_panel = None;
|
||||
switch(&mut app, ESSENTIALS).unwrap();
|
||||
assert!(!showing(&app.ui, "color"), "Essentials opens no panel");
|
||||
switch(&mut app, "Essentials Classic").unwrap();
|
||||
assert!(!showing(&app.ui, "color"), "Classic comes back as it was left");
|
||||
reset(&mut app);
|
||||
assert!(showing(&app.ui, "color"), "Reset Essentials Classic shows Color again");
|
||||
}
|
||||
|
||||
/// A saved workspace keeps the panel open from its icons, through the preferences' JSON too; a
|
||||
/// workspace saved without that field opens none, and one naming a panel its layout does not
|
||||
/// show from icons opens none either.
|
||||
#[test]
|
||||
fn saved_workspaces_restore_the_open_panel() {
|
||||
let mut app = app();
|
||||
switch(&mut app, "Essentials Classic").unwrap();
|
||||
save_as(&mut app.ui, "Colors").unwrap();
|
||||
switch(&mut app, ESSENTIALS).unwrap();
|
||||
assert_eq!(app.ui.open_panel, None);
|
||||
switch(&mut app, "Colors").unwrap();
|
||||
assert_eq!(app.ui.open_panel.as_deref(), Some("color"));
|
||||
let id = id_of(&app.ui, "Colors");
|
||||
let back: UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
|
||||
assert_eq!(back.workspaces.records[&id].open_panel.as_deref(), Some("color"));
|
||||
let mut old = serde_json::to_value(&back.workspaces.records[&id]).unwrap();
|
||||
assert!(old.as_object_mut().unwrap().remove("openPanel").is_some());
|
||||
let old: WorkspaceRecord = serde_json::from_value(old).unwrap();
|
||||
assert_eq!(old.open_panel, None);
|
||||
switch(&mut app, ESSENTIALS).unwrap();
|
||||
app.ui.workspaces.edited.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into());
|
||||
switch(&mut app, "Colors").unwrap();
|
||||
assert_eq!(app.ui.open_panel, None, "switching opens no panel the layout's icons lack");
|
||||
app.ui.workspaces.records.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into());
|
||||
reset(&mut app);
|
||||
assert_eq!(app.ui.open_panel, None, "Reset opens no panel the layout's icons lack");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_apply_round_trip() {
|
||||
let mut app = app();
|
||||
|
||||
+23
-7
@@ -3323,7 +3323,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.
|
||||
@@ -3346,13 +3359,15 @@ 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, or one is a folder or an existing read-only file, 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, or one is a folder or an existing read-only file, 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
|
||||
@@ -3365,7 +3380,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
|
||||
|
||||
@@ -1127,6 +1127,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