diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index cf00d4194a..7c185352a0 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,15 +1071,14 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. A refused file is not handed to `write`, so a writer that does not check the + // file access writes none of the files; the error is the file access's own refusal, as + // the writers that check it give. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) { - write(p, bytes)?; - // A writer that does not check the file access writes none of the others. - return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); + return Err(refused); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 6400b32f73..8d282ce7bb 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -896,12 +896,29 @@ const UNSAVED_CHANGES: &str = const NO_FILE_TO_SAVE: &str = "the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; +/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes whose +/// last save named some of its artboards: saving with those options again could leave changes out. +const SAVES_SOME_ARTBOARDS: &str = + "the document was last saved with some of its artboards named: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; + +/// Whether the options `st` was last saved with name artboards (`artboard`, `artboards`, or a +/// `range` other than all of them), so that a save with them may write only some of the artboards. +fn picks_artboards(st: &crate::doc_state::DocState) -> bool { + let options = crate::cmd::fileio::remembered_save_options(st); + crate::cmd::fileio::ARTBOARD_PARAMS.iter().any(|k| match options.get(*k) { + None | Some(Value::Null) => false, + Some(Value::String(r)) if *k == "range" => !(r.trim().is_empty() || r.trim().eq_ignore_ascii_case("all")), + Some(_) => true, + }) +} + /// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved /// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES` /// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with /// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of /// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] -/// for a document that has no file, a converted or recovered one included; and +/// for a document that has no file, a converted or recovered one included, and +/// [`SAVES_SOME_ARTBOARDS`] before writing when the document's last save named some of its artboards; and /// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script /// cannot show the prompt. fn doc_close(h: &Host, a: &[Data]) -> Answer { @@ -910,13 +927,16 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, None => "PROMPTTOSAVECHANGES", }; - let (dirty, file, format) = - super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format)); + let (dirty, file, format, picked) = + super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format, picks_artboards(st))); if dirty { match how { "DONOTSAVECHANGES" => {} "SAVECHANGES" => { let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + if picked { + return Err(HostError::Error(SAVES_SOME_ARTBOARDS.into())); + } // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index a3f937a244..9ce5c2f820 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -208,7 +208,7 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { } /// When the writer a save is given does not check the file access itself, a save of several files -/// still writes none of them after the refused one. +/// whose file access refuses one of them hands none of them to the writer. #[test] fn a_refused_file_stops_a_save_whose_writer_does_not_check() { use crate::cmd::fileio::{SaveMode, save_job, save_plan}; @@ -247,7 +247,7 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { }); assert!(r.is_err(), "{r:?}"); let refused = refused.unwrap(); - assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + assert_eq!(written, Vec::::new(), "no file went to the writer, the refused one ({refused}) included"); let mut perms = std::fs::metadata(&refused).unwrap().permissions(); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); @@ -722,10 +722,49 @@ fn closing_with_save_changes_keeps_the_documents_format() { ); let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default(); assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format"); + let pdf = vectorcraft_pdf::import(&bytes).unwrap(); + let mut sizes = vec![]; + for l in &pdf.layers { + l.walk(&mut |n| sizes.extend(n.geometric_bounds().map(|b| (b.width(), b.height())))); + } + let near = |(w, h): (f64, f64), (x, y): (f64, f64)| (w - x).abs() < 0.01 && (h - y).abs() < 0.01; + assert!(sizes.iter().any(|&s| near(s, (5.0, 5.0))), "the file holds the rectangle drawn after the first save: {sizes:?}"); + assert!(sizes.iter().any(|&s| near(s, (50.0, 20.0))), "and the first one: {sizes:?}"); assert!(s.documents().is_empty()); let _ = std::fs::remove_dir_all(base); } +/// `close(SaveOptions.SAVECHANGES)` on a document whose last save named some of its artboards +/// throws before writing and leaves the document open, so no change is left out of its file. +#[test] +fn closing_with_save_changes_refuses_a_save_of_some_artboards() { + let base = folder("closerange"); + 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('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + var o = new PDFSaveOptions(); o.artboardRange = '2'; d.saveAs(new File({d} + '/r.pdf'), o);\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}});\n\ + var e = ''; try {{ d.close(SaveOptions.SAVECHANGES); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);" + ), + ); + assert!(out[0][0].as_str().unwrap().contains("some of its artboards"), "{}", out[0]); + assert_eq!(out[0][1], json!(1), "the document stays open"); + let pdf = vectorcraft_pdf::import(&std::fs::read(dir.join("r.pdf")).unwrap()).unwrap(); + let mut drawn = 0; + for l in &pdf.layers { + l.walk(&mut |n| drawn += usize::from(n.geometric_bounds().is_some_and(|b| (b.width() - 5.0).abs() < 0.01))); + } + assert_eq!(drawn, 0, "the file is left as the first save wrote it"); + assert!(s.active().unwrap().is_dirty(), "the change is still unsaved"); + let _ = std::fs::remove_dir_all(base); +} + /// Setting `Document.saved` records the document's saved state without saving it: `true` lets /// `close()` close a document with edits, and `false` makes an untouched one ask. #[test] diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 8765501507..7a596f5633 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -647,6 +647,12 @@ 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 variables that may get another value when code read elsewhere runs: assigned inside a + /// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]). + /// None of them joins [`Analyzer::writers`]. + later: HashSet, + /// `later` ran out of room: no variable joins [`Analyzer::writers`]. + later_full: bool, /// This file or what the scan started with gives names values the analysis doesn't read /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. unsure: bool, @@ -727,6 +733,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + later: HashSet::new(), + later_full: false, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -1417,9 +1425,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // A name after `.`, `..`, `.@`, `::` or `@` is a property's or an attribute's; any other // name before `=` is a variable, at the start of a statement or inside an expression. if !member_mark(h1) && !is(h1, "@") { + if !self.scopes.is_empty() && !self.declared_in_body(name.text) { + self.reassigned_later(name.text); + } self.assign = Some(Assign { name: name.text.to_string(), after_new: false }); } } + if let Some((name, _)) = self.updated(t) + && !self.scopes.is_empty() + && !self.declared_in_body(name) + { + self.reassigned_later(name); + } match self.updated(t) { // The value on the right is read at this depth, and the name holds nothing the check // follows once that value ends ([`Analyzer::settle_groups`]). @@ -1435,12 +1452,34 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { 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.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); } } + /// `name` may get another value when code read elsewhere runs: a function body assigns it without + /// declaring it, and the function may be called before or after any line, or it is assigned as a + /// property of `this`. Its object literal's methods are no longer known, now or later. + fn reassigned_later(&mut self, name: &str) { + self.writers.remove(name); + if !self.later.contains(name) { + if self.acc.room(self.later.len()) { + self.later.insert(name.to_string()); + } else { + self.later_full = true; + } + } + } + + /// Whether `name` is declared in a function body this token is inside (`var name`, `function + /// name`, a parameter). + fn declared_in_body(&self, name: &str) -> bool { + self.scopes.iter().any(|s| s.saved.get(name).is_some_and(|v| v.local)) + } + /// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single /// function expression directly inside its braces as the whole value of a key that names a /// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`) diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 48303c173e..9a99338da4 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -376,9 +376,24 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `local[k] = w`, `delete local.saveAs`). fn writer_use(&mut self, t: &Sig<'s>) { let [h0, h1, h2, h3] = self.h; - let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); let key = t.is(":") && (is(h1, "{") || is(h1, ",")); + // `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a + // function called without a receiver (ECMA-262 3rd edition, sections 10.2.1 and 10.2.3), so the + // global variable of that name may get another value. + if changes { + let global = if is(h1, ".") && word(h2, "this") { + h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string()) + } else if is(h0, "]") && is(h2, "[") && word(h3, "this") { + h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64)) + } else { + None + }; + if let Some(name) = global { + 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 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 1524d4d7ae..422679f803 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -664,6 +664,46 @@ 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 function body read before the literal that assigns its variable without declaring it may run +/// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the +/// name assigns its own variable. +#[test] +fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() { + let r = report(concat!( + "var f = new File(p);\n", + "function choose() { d = app.activeDocument; }\n", + "var d = {saveAs: function () {}};\n", + "choose(); d.saveAs(f);\n", + "function bump() { e++; }\n", + "var e = {saveAs: function () {}};\n", + "e.saveAs(f);\n", + "function own() { var g; g = app.activeDocument; }\n", + "var g = {saveAs: function () {}};\n", + "g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); +} + +/// Assigning a property of `this`, the global object in the global code and in a function called +/// without a receiver, may give the global variable of that name another value, before or after +/// its literal. +#[test] +fn assigning_a_property_of_this_keeps_save_as_writing() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = {saveAs: function () {}};\n", + "this.d = app.activeDocument;\n", + "d.saveAs(f);\n", + "function swap() { this['e'] = app.activeDocument; }\n", + "var e = {saveAs: function () {}};\n", + "swap(); e.saveAs(f);\n", + "var g = {saveAs: function () {}};\n", + "this.other = 1;\n", + "g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); +} + /// A `saveAs` key's value is a method of the script's own only when the whole value is one function /// expression: a value that goes on after the function's body, and a literal inside another, leave /// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body diff --git a/docs/mcp.md b/docs/mcp.md index 5c2c05d8fe..c3794b55b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2935,7 +2935,8 @@ other files through `$`: format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and - when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws + when the script's folders refuse one of those files, none of them is written; a write that fails once the + first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help 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 @@ -2956,7 +2957,8 @@ other files through `$`: undo step. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document was last saved in and after the same write-access check of the path as `saveAs`, and throws an error - and leaves the document open when the document has no file (a converted or recovered document included); and + and leaves the document open when the document has no file (a converted or recovered document included) or when + its last save named some of its artboards, without writing anything; and `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. - `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/)