diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 51d7590f35..21424f7bdc 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -126,6 +126,12 @@ pub use screens::{ preset_rows as screen_preset_rows, }; pub(crate) use svg::lost_artboards_warning as svg_lost_artboards_warning; + +/// Does a save in `format` (a format id) with options `p` write a legacy version 7 `.ai` file, +/// which holds the artboards its own options pick? An unknown version counts as one. +pub(crate) fn saves_legacy_ai(format: &str, p: &serde_json::Value) -> bool { + format == "ai" && formats::format(format).is_none_or(|f| legacy_ai::wanted("file.saveAs", f, p).unwrap_or(true)) +} pub use svg::options_map as svg_options; /// Atomic file writes (a temporary file renamed over the target: a failed write never damages the /// file it replaces), for the apps' own writers too. diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index bf49aae883..9106158e60 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -665,6 +665,17 @@ fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { r } +/// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s +/// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or +/// a linked image an open could not read. → the command's answer. +fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer { + let (answer, value) = super::super::command_value(h, id, p)?; + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + Ok(answer) +} + /// The path to give a command for the real path `real`. fn plain(real: std::path::PathBuf) -> String { crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() @@ -728,7 +739,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -782,7 +793,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -831,7 +842,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(std::path::PathBuf::from(path)))); - let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), @@ -925,12 +936,24 @@ const NO_FILE_TO_SAVE: &str = const SAVES_SOME_ARTBOARDS: &str = "the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; -/// Whether saving `st` with its remembered options would omit artboards. +/// Whether the file that saving `st` with its remembered options writes would omit artboards. A +/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai` +/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its +/// `range` names only the separate files. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { let options = Value::Object(crate::cmd::fileio::remembered_save_options(st)); if matches!(st.format, "svg" | "svgz") && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() { return true; } + if st.format == "pdf" && options.get("useArtboards") == Some(&Value::Bool(false)) { + return true; + } + if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") + && options.get("separateArtboards") == Some(&Value::Bool(true)) + && !crate::cmd::fileio::saves_legacy_ai(st.format, &options) + { + return false; + } let count = st.doc.artboards.len(); let pick = serde_json::from_value::(options); match pick.map_err(|e| e.to_string()).and_then(|p| p.resolve(count)) { @@ -969,7 +992,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; let p = json!({"path": plain(real), "format": format}); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8c09da874c..da96519b6e 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -1010,6 +1010,42 @@ fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() { let _ = std::fs::remove_dir_all(base); } +/// The artboard check of `close(SaveOptions.SAVECHANGES)` follows the file the save writes: a PDF +/// last saved without its artboards (`useArtboards: false`) is refused, and a `.ai` file whose +/// `range` names only the separate artboard files keeps every artboard and is saved. +#[test] +fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { + let base = folder("closeencoder"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pdf = dir.join("art.pdf"); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + s.execute("document.save", &json!({"path": pdf.to_string_lossy(), "useArtboards": false})).unwrap(); + let before = std::fs::read(&pdf).unwrap(); + let e = failure( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(e.contains("some of its artboards"), "{e}"); + assert_eq!(std::fs::read(&pdf).unwrap(), before, "the PDF is left as it was"); + let mut s = session(&base); + data_folder(&mut s, &base); + let ai = dir.join("all.ai"); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + s.execute("document.save", &json!({"path": ai.to_string_lossy(), "separateArtboards": true, "range": "2"})).unwrap(); + let before = std::fs::read(&ai).unwrap(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty(), "the .ai file keeps every artboard, so it closes"); + assert_ne!(std::fs::read(&ai).unwrap(), before, "and the change is saved"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() { let base = folder("closesvgboards"); @@ -1098,6 +1134,43 @@ fn setting_saved_records_the_saved_state() { let _ = std::fs::remove_dir_all(base); } +/// The warnings of a save go to the console after the method's name. +#[test] +fn save_as_writes_its_warnings_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": 100, "height": 50, "artboards": 2})).unwrap(); + let r = run(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("two.svg")))).unwrap(); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ")), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A point change that waits to be written counts as an unsaved change for `saved` and `close`. +#[test] +fn waiting_point_changes_count_as_unsaved_changes() { + let base = folder("pendingpoints"); + 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 d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/a.svg'));\n\ + d.pathItems[0].pathPoints[0].anchor = [1, 2]; vc.log(d.saved);\n\ + d.saved = true; d.pathItems[0].pathPoints[0].anchor = [3, 4];\n\ + var e = ''; try {{ d.close(); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);" + ), + ); + assert_eq!(out[0], json!(false), "a waiting point change is unsaved"); + assert!(out[1][0].as_str().unwrap().contains("unsaved changes"), "{}", out[1]); + assert_eq!(out[1][1], json!(1), "close() keeps the document open"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn unchanged_saved_assignments_do_not_record_commands() { let base = folder("savednoop"); diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 869938027f..a66b20ef06 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -531,6 +531,8 @@ impl Chain { /// member chain or a File object assigned in it to an outer name stays. struct Scope { depth: usize, + /// The offset of the body's `{` in the text, which [`Declared::looped`] names it by. + start: usize, saved: HashMap, /// The bracket depth of the `var` statement the body is in, if any: it goes on when the body /// closes. @@ -1234,7 +1236,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if body { let params = self.params.take().map(|(_, names)| names).unwrap_or_default(); if self.scopes.len() < self.acc.limits.nesting { - self.scopes.push(Scope { depth: self.depth(), saved: HashMap::new(), var_depth: self.var_depth.take() }); + self.scopes.push(Scope { depth: self.depth(), start: t.start, saved: HashMap::new(), var_depth: self.var_depth.take() }); // The parameters are the body's own names, and so are the names it declares. for name in params { self.acc.steps = self.acc.steps.saturating_add(1); @@ -1454,11 +1456,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` /// closes a function body, so a literal given to the body's own variable stays inside the body. + /// Calls inside a loop that assigns the variable use [`Declared::looped`] to classify its methods. fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) && !self.later_full && !self.later.contains(&name) + && !self.declared.looped_full && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 48f071d2ac..9079c352ef 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,6 +1,6 @@ //! The names declared, read before the analysis. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; @@ -14,6 +14,10 @@ const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_E /// The property a function reaches `Function` through. const CONSTRUCTOR: &str = "constructor"; +/// The statements whose parentheses the rest of the statement follows, so a line break after them +/// does not end a loop's body without braces. +const HEADS: &[&str] = &["if", "while", "for", "with", "switch"]; + /// The longest property name, in characters, that [`Declared::rebound`] keeps. A string literal in /// brackets that spells a longer one sets [`Declared::unsure`]. const PROPERTY_CHARS: usize = 256; @@ -36,6 +40,16 @@ pub(crate) struct Declared<'s> { /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be /// the global object, so a variable of that name may get a value the analysis doesn't read. pub(super) rebound: HashSet, + /// The variables assigned inside a loop, its parentheses included (`name = …`), each by the + /// offset of the `{` of the function body that declares it (`None`: the global code's), with the + /// outermost loops that assign it, entries of `loop_spans`. + pub(super) looped: HashMap<(Option, &'s str), Vec>, + /// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at + /// the end of the text). + pub(super) loop_spans: Vec<(usize, usize)>, + /// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any + /// variable may be assigned in a loop. + pub(super) looped_full: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or /// a `constructor` property used, a property read, called or assigned whose name in brackets is /// not one string or number literal, which may be a variable's name on the global object @@ -48,12 +62,14 @@ pub(crate) struct Declared<'s> { /// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in /// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement -/// the body is in, which goes on when the body closes. +/// the body is in, which goes on when the body closes, and the names assigned in a loop inside it +/// so far, each with its loops ([`Declared::looped`]). struct Body<'s> { depth: usize, index: usize, names: HashSet<&'s str>, var_depth: Option, + looped: HashMap<&'s str, Vec>, } /// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in @@ -87,9 +103,43 @@ struct Declarations<'s, 'a, 'l> { untracked: Option, /// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`]. keys: Vec, + /// The loops being read, the innermost last, up to [`crate::Limits::nesting`]. + loops: Vec, out: Declared<'s>, } +/// A loop [`Declarations`] is reading: the bracket depth of its keyword, how far it has been read, +/// and, for a body without braces, whether the last `{` at that depth opened a block (not an object +/// literal), whether an `if`, `while`, `for` or `with` at that depth waits for its `)`, and whether +/// the last token was that `)`. +struct Loop { + depth: usize, + stage: Stage, + block: bool, + head: bool, + after_head: bool, + /// The loop starts with `do` and has a trailing condition. + do_loop: bool, +} + +/// How far a [`Loop`] has been read. +#[derive(Clone, Copy, PartialEq)] +enum Stage { + /// The parentheses after `for` or `while`. + Head, + /// The parentheses after the `while` of a `do` loop. + DoHead, + /// The body's first token is next. + Start, + /// A body in braces. + Block, + /// A body that is one statement without braces. + Statement, + /// The statement of a body without braces has reached its end: the loop ends at the next token, + /// unless it is `else`, which goes on with the statement. + Tail, +} + /// What `src` declares ([`Declared`]), read in one pass over its tokens. pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { let mut lexer = Lexer::new(src, acc.limits.nesting); @@ -103,6 +153,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { bodies: vec![], untracked: None, keys: vec![], + loops: vec![], out: Declared::default(), }; let mut breaks = LineBreaks::default(); @@ -113,6 +164,10 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { Read::Token(sig) => d.token(sig), } } + // A body the file does not close keeps its names assigned in a loop as well. + while let Some(body) = d.bodies.pop() { + d.settle_looped(body); + } let mut out = d.out; out.unsure |= out.rebound.contains(catalog::FOLDER); acc.steps = acc.steps.saturating_add(lexer.steps); @@ -138,12 +193,22 @@ impl<'s> Declarations<'s, '_, '_> { if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) { self.var_depth = None; } + self.loop_start(&t); if t.kind == T::Punct { self.bracket(&t); } else if t.kind == T::Ident { self.declaration(&t); } let depth = self.depth(); + self.loop_end(&t, depth); + if t.is("=") + && !self.loops.is_empty() + && !member_mark(h1) + && !is(h1, "@") + && let Some(name) = h0.filter(|s| s.kind == T::Ident) + { + self.looped(name.text); + } if let Some(after_new) = self.assign.take() { if t.word("new") && !after_new { self.assign = Some(true); @@ -167,6 +232,191 @@ impl<'s> Declarations<'s, '_, '_> { self.h = [Some(t), h0, h1]; } + /// `t`, a token before the brackets are followed past it: the body of the innermost loop starts + /// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any + /// variable may be assigned in one ([`Declared::looped_full`]). + fn loop_start(&mut self, t: &Sig<'s>) { + let [h0, ..] = self.h; + let depth = self.depth(); + while let Some(l) = self.loops.last_mut() { + let after_head = std::mem::take(&mut l.after_head); + match l.stage { + Stage::Start => { + l.stage = if t.is("{") { Stage::Block } else { Stage::Statement }; + l.head = HEADS.iter().any(|w| t.word(w)) && !member_mark(h0); + break; + } + // A line break ends a body of one statement where the tokens on either side of it + // don't go on with it, as in [`Analyzer::token`], and it does not follow the + // parentheses of an `if` or another statement that the body goes on with. + Stage::Statement + if t.nl && depth == l.depth && !goes_on_after(h0) && !goes_on_with(t) && !after_head && !word(h0, "else") && !word(h0, "do") => + { + l.stage = Stage::Tail; + } + Stage::Statement => { + if depth == l.depth { + if t.is("{") { + l.block = t.stmt || after_head || word(h0, "else"); + } else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) { + l.head = true; + } + } + break; + } + Stage::Tail if l.do_loop && t.word("while") => { + l.stage = Stage::DoHead; + return; + } + Stage::Tail if t.word("else") => { + l.stage = Stage::Statement; + break; + } + Stage::Tail => { + self.pop_loop(t.start); + // A body of one statement that is this loop ends with it. + if let Some(outer) = self.loops.last_mut() + && outer.stage == Stage::Statement + && outer.depth == depth + { + outer.stage = Stage::Tail; + } + } + _ => break, + } + } + let stage = if (t.word("for") || t.word("while")) && !member_mark(h0) { + Stage::Head + } else if t.word("do") && !member_mark(h0) { + Stage::Start + } else { + return; + }; + if self.loops.len() >= self.acc.limits.nesting || (self.loops.is_empty() && !self.acc.room(self.out.loop_spans.len())) { + self.out.looped_full = true; + } else { + if self.loops.is_empty() { + self.out.loop_spans.push((t.start, usize::MAX)); + } + self.loops.push(Loop { depth, stage, block: false, head: false, after_head: false, do_loop: t.word("do") }); + } + } + + /// Ends the innermost loop at offset `at`, which ends the outermost one in + /// [`Declared::loop_spans`]. + fn pop_loop(&mut self, at: usize) { + self.loops.pop(); + if self.loops.is_empty() + && let Some((_, end)) = self.out.loop_spans.last_mut() + { + *end = at; + } + } + + /// `t`, after the brackets are followed past it to `depth`: the parentheses of a loop end at the + /// `)` back at its depth, and a body in braces at the `}` back at it. A body of one statement + /// reaches its end ([`Stage::Tail`]) at a `;` at the loop's depth, at a `}` there that closes a + /// block, or with a loop that is that statement. A bracket closing below a loop's depth ends it. + fn loop_end(&mut self, t: &Sig<'s>, depth: usize) { + let mut inner = false; + while let Some(l) = self.loops.last_mut() { + let ended = depth < l.depth + || match l.stage { + Stage::Head => { + if t.is(")") && depth == l.depth { + l.stage = Stage::Start; + } + false + } + Stage::DoHead => t.is(")") && depth == l.depth, + Stage::Block => { + if t.is("}") && depth == l.depth && l.do_loop { + l.stage = Stage::Tail; + false + } else { + t.is("}") && depth == l.depth + } + } + Stage::Statement => { + if depth == l.depth { + if t.is(";") || (t.is("}") && l.block) || inner { + l.stage = Stage::Tail; + } else if t.is(")") && l.head { + l.head = false; + l.after_head = true; + } + } + false + } + Stage::Start | Stage::Tail => false, + }; + if !ended { + break; + } + self.pop_loop(t.start); + inner = true; + } + } + + /// `name` is assigned in the loops being read: kept with the outermost one for the innermost + /// function body that declares it when that body closes ([`Self::settle_looped`]), or for the + /// global code. + fn looped(&mut self, name: &'s str) { + let id = self.out.loop_spans.len().saturating_sub(1); + match self.bodies.last_mut() { + Some(body) if body.looped.contains_key(name) || self.acc.room(body.looped.len()) => { + let ids = body.looped.entry(name).or_default(); + if !ids.contains(&id) { + ids.push(id); + } + } + Some(_) => self.out.looped_full = true, + None => self.keep_looped(None, name, vec![id]), + } + } + + /// The names assigned in a loop inside `body`, which is closing: the body's own are kept for it, + /// and the others go to the body around it, or to the global code. + fn settle_looped(&mut self, body: Body<'s>) { + let start = self.out.bodies.get(body.index).map(|(at, _)| *at); + for (name, ids) in body.looped { + if body.names.contains(name) { + self.keep_looped(start, name, ids); + } else if let Some(outer) = self.bodies.last_mut() { + if outer.looped.contains_key(name) || self.acc.room(outer.looped.len()) { + let kept = outer.looped.entry(name).or_default(); + for id in ids { + if !kept.contains(&id) { + kept.push(id); + } + } + } else { + self.out.looped_full = true; + } + } else { + self.keep_looped(None, name, ids); + } + } + } + + /// Keeps `name` of `body` as assigned in outermost loops `ids`. + fn keep_looped(&mut self, body: Option, name: &'s str, ids: Vec) { + let len = self.out.looped.len(); + match self.out.looped.get_mut(&(body, name)) { + Some(kept) => { + for id in ids { + if !kept.contains(&id) { + kept.push(id); + } + } + } + None if self.acc.room(len) => { + self.out.looped.insert((body, name), ids); + } + None => self.out.looped_full = true, + } + } + /// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and /// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read. fn unread_binding(&mut self, t: &Sig<'s>) { @@ -234,7 +484,13 @@ impl<'s> Declarations<'s, '_, '_> { if self.bodies.len() < self.acc.limits.nesting { let index = self.out.bodies.len(); self.out.bodies.push((t.start, vec![])); - self.bodies.push(Body { depth: self.depth(), index, names: HashSet::new(), var_depth: self.var_depth.take() }); + self.bodies.push(Body { + depth: self.depth(), + index, + names: HashSet::new(), + var_depth: self.var_depth.take(), + looped: HashMap::new(), + }); } else if self.untracked.is_none() { self.untracked = Some(self.depth()); } @@ -261,6 +517,7 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; + self.settle_looped(body); } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index bf808469e5..8b6b4c5f1d 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -292,8 +292,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. - "[" => self.index_receiver = self.writer_bits(h0, h1), - "(" => self.call(line), + "[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)), + "(" => self.call(t, line), // `Name.prototype["+"] = …` defines an operator. "=" => { let operator = || h1.filter(|s| s.kind == T::Str).is_some_and(|s| catalog::OPERATORS.contains(&unquote(s.text, 4).as_str())); @@ -308,7 +308,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } /// `(` after a name: a call. - fn call(&mut self, line: Option) { + fn call(&mut self, t: &Sig<'s>, line: Option) { let [h0, h1, h2, h3] = self.h; // `doc['saveAs'](f)`: a document method named by a string literal in brackets. if is(h0, "]") @@ -342,7 +342,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); } else if (file && catalog::FILE_WRITES.contains(&n)) - || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3), n)) + || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n)) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -369,9 +369,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The methods that `receiver`, which `before` comes before, defines when it is a variable holding /// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name; /// 0 for anything else. A receiver the check does not follow may be a document. - fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { + /// At call offset `at`, a variable assigned in a loop containing that offset may be a document. + fn writer_bits(&self, receiver: Option>, before: Option>, at: Option) -> u8 { match receiver { - Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), + Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => { + let looped = at.is_some_and(|at| { + self.declared.looped_full + || self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| { + ids.iter().any(|id| self.declared.loop_spans.get(*id).is_some_and(|(start, end)| *start <= at && at < *end)) + }) + }); + if looped { 0 } else { self.writers.get(r.text).copied().unwrap_or(0) } + } _ => 0, } } @@ -400,7 +409,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.reassigned_later(&name); } } - let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); + let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text); let escaped = if word(h0, "delete") { // `delete local…` writer(Some(*t), h0) diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 0493014da0..a580c3d311 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -698,6 +698,69 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..])); } +/// A variable assigned in a loop may hold a document when a later iteration calls its `saveAs`, +/// before the assignment in the text: the call writes a file. One assigned only after a loop does +/// not. +#[test] +fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n", + "var d = {saveAs: function () {}};\n", + "for (var i = 0; i < 2; i++) { a.saveAs(f); a = app.activeDocument; }\n", + "while (n--) b.saveAs(f), b = app.activeDocument;\n", + "do { c.saveAs(f); } while ((c = next()));\n", + "for (;;) { d.saveAs(f); break; }\n", + "d = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 6][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[4, 5, 6][..])]); + // The `else` of a body without braces is in the loop; a statement after a line break that ends + // such a body is not, and neither is a variable of the same name that a function declares. + let r = report(concat!( + "var f = new File(p);\n", + "var e = {saveAs: function () {}}; var g = {saveAs: function () {}}; var h = {saveAs: function () {}};\n", + "while (n--) if (n) e.saveAs(f); else e = app.activeDocument;\n", + "while (n--) g.saveAs(f), n\n", + "g = app.activeDocument\n", + "function k() { var h; for (;;) h = app.activeDocument; }\n", + "h.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + // An object literal's `}` does not end a body without braces, a call's `)` before a line break + // does, and a literal given after the last loop that assigns its variable is the script's own. + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "while (n--) a.saveAs(f), t = {}, a = app.activeDocument;\n", + "b.saveAs(f);\n", + "while (n--) tick()\n", + "b = app.activeDocument\n", + "for (;;) { c = app.activeDocument; }\n", + "var c = {saveAs: function () {}};\n", + "c.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}};\n", + "while (n--) if (n)\n", + " a.saveAs(f), a = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..])); + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "a.saveAs(f); b['saveAs'](f);\n", + "while (n--) { a.saveAs(f); a = app.activeDocument; }\n", + "while (n--) { b['saveAs'](f); b = app.activeDocument; }\n", + "var a = {saveAs: function () {}};\n", + "a.saveAs(f);\n", + "while (n--) { a.saveAs(f); a = app.activeDocument; }\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment diff --git a/docs/mcp.md b/docs/mcp.md index 2fcb2dc34f..c073a93f02 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3168,9 +3168,13 @@ through `$`: was last saved in and after the same write-access check of the path as `saveAs`, and throws an error and leaves the document open when the document has no file (a converted or recovered document included) or when the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several - artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. + artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with + `useArtboards: false` omits artboards; a native or `.ai` file (other than a version 7 `.ai` file) saved with + `separateArtboards` keeps every artboard whatever its range names. `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot - show the prompt. A bad value throws an error before anything is written. + show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that + `saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name + (`saveAs: …`). - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, `getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 13d8c9200e..2ed9a978e8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1127,7 +1127,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.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, and read and write only where the script's `File` objects may; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.