diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 8ffb3f8133..954a345ae0 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -22,6 +22,8 @@ pub struct LoadOptions { pub pages: Option, /// The box each page's artboard (or placed frame) gets. pub crop: CropTo, + /// Whether the options explicitly request the crop box. + pub explicit_crop_box: bool, /// The password of an encrypted PDF. pub password: Option, /// The colour mode the document opens in, its colours converted as Document Color Mode does @@ -67,6 +69,7 @@ impl Default for LoadOptions { Self { pages: None, crop: CropTo::default(), + explicit_crop_box: false, password: None, color_mode: None, grays: Grays::default(), @@ -147,6 +150,7 @@ impl LoadOptions { Ok(Self { pages, crop, + explicit_crop_box: crop == CropTo::Crop && crop_to.or(crop_alias).is_some(), password, color_mode, grays, @@ -173,14 +177,14 @@ impl LoadOptions { } /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible - /// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes, - /// its editor's artboards, with the bleed round them (its crop box takes the bleed in). + /// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default, + /// with the bleed around them. An explicit crop-box request uses its crop box. fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { None => None, Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?), }; - let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data(); + let is_ai = !self.explicit_crop_box && self.crop == CropTo::Crop && opened.has_illustrator_data(); Ok(ImportOptions { pages, crop: if is_ai { CropTo::Trim } else { self.crop }, diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 9106158e60..09c438040c 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -939,8 +939,12 @@ const SAVES_SOME_ARTBOARDS: &str = /// 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. +/// `range` names only the separate files. An EPS file embeds the whole document in its main file, +/// so its `artboardRange` never omits an artboard from what reopens. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { + if st.format == "eps" { + return false; + } 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; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index da96519b6e..68183e8637 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -741,6 +741,34 @@ fn crop_only_options_apply_to_an_editable_pdf() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn explicit_crop_box_opens_the_bleed_outside_an_editable_files_trim_box() { + let base = folder("explicitcropbox"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for extension in ["ai", "pdf"] { + let file = dir.join(format!("editable.{extension}")); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": file.to_string_lossy(), "format": "ai", "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&file).unwrap(), None)); + let path = quoted(&file); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + let default = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}), undefined, {{pDFCropToBox: PDFBoxType.PDFTRIMBOX}});")); + let trim = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}), undefined, {{pDFCropToBox: PDFBoxType.PDFCROPBOX}});")); + let crop = s.active().unwrap().doc.artboards[0].rect; + assert_eq!((default.width(), default.height()), (trim.width(), trim.height()), "{extension}"); + assert!(crop.width() > trim.width() && crop.height() > trim.height(), "{extension}"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_document_open_rejects_files_over_the_read_limit() { let base = folder("openreadlimit"); @@ -1046,6 +1074,43 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn closing_with_save_changes_keeps_all_eps_artboards_for_subset_ranges() { + let base = folder("closeepsboards"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for (name, range) in [("single", "2"), ("several", "1-2")] { + let file = dir.join(format!("{name}.eps")); + let path = quoted(&file); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 100, 50);\n\ + vc.run('artboard.new', {{x: 150, y: 0, width: 100, height: 50}});\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 100, height: 50}});\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 20, height: 20}});\n\ + var o = new EPSSaveOptions(); o.saveMultipleArtboards = true; o.artboardRange = '{range}';\n\ + d.saveAs(new File({path}), o);" + ), + ); + let before = std::fs::read(&file).unwrap(); + let nodes = s.active().unwrap().doc.node_count(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 40, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty(), "{range}"); + assert_ne!(std::fs::read(&file).unwrap(), before, "{range}"); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 3, "{range}"); + assert!(s.active().unwrap().doc.node_count() > nodes, "{range}"); + logged(&mut s, &base, "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() { let base = folder("closesvgboards"); diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 9079c352ef..03ad43ab10 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -22,6 +22,33 @@ const HEADS: &[&str] = &["if", "while", "for", "with", "switch"]; /// brackets that spells a longer one sets [`Declared::unsure`]. const PROPERTY_CHARS: usize = 256; +#[cfg(not(test))] +type LoopSpans = Vec<(usize, usize)>; + +#[cfg(test)] +#[derive(Default)] +pub(super) struct LoopSpans { + spans: Vec<(usize, usize)>, + reads: std::cell::Cell, +} + +#[cfg(test)] +impl std::ops::Deref for LoopSpans { + type Target = Vec<(usize, usize)>; + + fn deref(&self) -> &Self::Target { + self.reads.set(self.reads.get() + 1); + &self.spans + } +} + +#[cfg(test)] +impl std::ops::DerefMut for LoopSpans { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.spans + } +} + /// The names a file's function bodies and its global code declare, read before the analysis. A /// function's `var` statements and the function declarations directly in its body make the names /// they declare the function's own before any statement in it runs, and the function declarations @@ -46,7 +73,7 @@ pub(crate) struct Declared<'s> { 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)>, + pub(super) loop_spans: LoopSpans, /// `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, @@ -60,6 +87,13 @@ pub(crate) struct Declared<'s> { pub(super) unsure: bool, } +#[cfg(test)] +impl Declared<'_> { + pub(crate) fn loop_span_reads(&self) -> usize { + self.loop_spans.reads.get() + } +} + /// 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, and the names assigned in a loop inside it @@ -169,6 +203,10 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { d.settle_looped(body); } let mut out = d.out; + for ids in out.looped.values_mut() { + ids.sort_unstable(); + ids.dedup(); + } out.unsure |= out.rebound.contains(catalog::FOLDER); acc.steps = acc.steps.saturating_add(lexer.steps); out diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 8b6b4c5f1d..48db72caad 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -373,13 +373,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { 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) => { + let Some(bits) = self.writers.get(r.text).copied() else { return 0 }; + if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) { + return 0; + } 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)) + let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at); + next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok()) }) }); - if looped { 0 } else { self.writers.get(r.text).copied().unwrap_or(0) } + if looped { 0 } else { bits } } _ => 0, } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index a580c3d311..2991b1c23f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -790,6 +790,34 @@ 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][..])); } +#[test] +fn writer_calls_after_many_assignment_loops_have_bounded_work() { + for reinitialize in [false, true] { + let mut src = "var d = {saveAs: function () {}};\n".to_string(); + for _ in 0..512 { + src.push_str("while (n--) { d = next(); }\n"); + } + if reinitialize { + src.push_str("var d = {saveAs: function () {}};\n"); + } + src.push_str("var local = {saveAs: function () {}};\n"); + for _ in 0..2048 { + src.push_str("d.saveAs(f); local.saveAs(f);\n"); + } + let limits = Limits::default(); + let mut acc = report::Acc::new(&limits); + let declared = analyze::declarations(&src, &mut acc); + let before = declared.loop_span_reads(); + analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc); + let reads = declared.loop_span_reads() - before; + if reinitialize { + assert!(reads < 16 * 2048, "{reads} span accesses for 2048 calls on d"); + } else { + assert_eq!(reads, 0); + } + } +} + /// 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. @@ -810,6 +838,25 @@ fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); } +#[test] +fn captured_writer_receivers_can_change_before_each_call() { + for method in ["saveAs", "exportFile"] { + for call in [format!("d.{method}(f)"), format!("d['{method}'](f)")] { + for (prefix, suffix) in [("", ""), ("function outer() {\n", "}\nouter();\n")] { + let src = format!( + "{prefix}var d = {{{method}: function () {{}}}};\n\ + function save(f) {{ {call}; }}\n\ + d = app.activeDocument; save(f);\n{suffix}" + ); + let r = report(&src); + let line = if prefix.is_empty() { 2 } else { 3 }; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[line][..]), "{src}"); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[line][..])], "{src}"); + } + } + } +} + #[test] fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() { let r = report(concat!(