diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 550a848721..8d4460cb4b 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -25,6 +25,8 @@ //! `exportFile` adds the format's extension unless the name already ends //! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes //! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. +//! An SVG export writes a compressed file when `compressed` is true, which adds `.svgz`, and +//! when the name ends with `.svgz`. //! 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. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at @@ -672,11 +674,15 @@ fn file_command(h: &Host, id: &str, params: &Value) -> Answer { Ok(data) } -/// 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() +/// The path to give a command for the real path `real`, or an error naming `path` when the real +/// path has no UTF-8 form. +fn plain(real: std::path::PathBuf, path: &str) -> std::result::Result { + crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| refused(NOT_UNICODE, path)) } +/// The error a real path with no UTF-8 form gives. +const NOT_UNICODE: &str = "Script file path is not valid Unicode"; + /// The built-in preset names scripts use that VectorCraft's built-in presets name otherwise, and the /// preset each one names here (`Default` is VectorCraft's default preset, as /// [`vectorcraft_pdf::builtin_preset`] reads it). @@ -731,7 +737,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))); + p.insert("path".into(), json!(plain(real, path)?)); exactly(h, || on_doc(h, doc.uid, false, |h| file_command(h, "file.saveAs", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -763,7 +769,9 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, }; - let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false); + // An SVG export to a name that ends with `.svgz` writes a compressed file, whatever `compressed` holds. + let svgz_name = path.rsplit(['/', '\\']).next().is_some_and(|n| n.to_lowercase().ends_with(".svgz")); + let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false) || (kind.format == "svg" && svgz_name); 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)); if (hs - vs).abs() > 1e-9 { @@ -785,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))); + p.insert("path".into(), json!(plain(real, &named)?)); exactly(h, || on_doc(h, doc.uid, false, |h| file_command(h, "document.export", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -831,7 +839,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } } let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; - p.insert("path".into(), json!(plain(real))); + p.insert("path".into(), json!(plain(real, path)?)); let r = exactly(h, || file_command(h, "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { @@ -931,7 +939,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { // 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))?; - let p = json!({"path": plain(real), "format": format}); + let p = json!({"path": plain(real, &name)?, "format": format}); exactly(h, || on_doc(h, doc.uid, false, |h| file_command(h, "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), diff --git a/crates/engine/src/script/dom/save_open/screens.rs b/crates/engine/src/script/dom/save_open/screens.rs index 825e509445..cee80dbf32 100644 --- a/crates/engine/src/script/dom/save_open/screens.rs +++ b/crates/engine/src/script/dom/save_open/screens.rs @@ -462,7 +462,7 @@ fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer { }; let real = h.disk.borrow().folder_target(folder).map_err(|m| refused(m, folder))?; let mut base = Map::new(); - base.insert("folder".into(), json!(plain(real))); + base.insert("folder".into(), json!(plain(real, folder)?)); base.insert("folders".into(), json!("none")); base.insert("formats".into(), json!([Value::Object(row)])); if let Some(prefix) = prefix { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 944a3dd5f6..276e44c63d 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -715,8 +715,15 @@ impl Disk { /// The real path of the folder `path` that an export writes its files into, as a `File` /// opened for writing there would reach it ([`Disk::target`]), or why it may not: a file is - /// not a folder. + /// not a folder. A root (`/`, `E:\`) has no name of its own: its real path must be inside a + /// folder the script may write to and the automation write roots in force. pub(crate) fn folder_target(&self, path: &str) -> Result { + let p = self.checked(path)?; + if p.file_name().is_none() { + let real = std::fs::canonicalize(p).map_err(|_| ACCESS_DENIED)?; + let writable = crate::file_access::check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_ok(); + return if self.writes.allows(&real) && writable { Ok(real) } else { Err(ACCESS_DENIED) }; + } let real = self.target(path, true)?; match std::fs::metadata(&real) { Ok(m) if !m.is_dir() => Err(NOT_FOLDER), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 2de01e9279..815534cadc 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -38,13 +38,27 @@ fn file_wrappers_report_encoder_warnings_without_changing_their_return_values() } } -/// A fresh folder for test `name`, by its real path, with `main` for the script. -fn folder(name: &str) -> PathBuf { - let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&base); - std::fs::create_dir_all(base.join("main")).unwrap(); - std::fs::create_dir_all(base.join("outside")).unwrap(); - std::fs::canonicalize(&base).unwrap() +/// A test's folder, by its real path, removed with everything in it when dropped, also when the +/// test fails. +struct Workspace { + _dir: vectorcraft_testkit::TempDir, + real: PathBuf, +} + +impl std::ops::Deref for Workspace { + type Target = PathBuf; + fn deref(&self) -> &PathBuf { + &self.real + } +} + +/// A fresh folder for test `name`, with `main` for the script and `outside`. +fn folder(name: &str) -> Workspace { + let dir = vectorcraft_testkit::TempDir::new(&format!("script-save-{name}")); + std::fs::create_dir_all(dir.join("main")).unwrap(); + std::fs::create_dir_all(dir.join("outside")).unwrap(); + let real = std::fs::canonicalize(&*dir).unwrap(); + Workspace { _dir: dir, real } } /// A session whose scripts keep their data folders in `base/settings/Script Data`. @@ -118,7 +132,6 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { assert!(dir.join("e.JPG").is_file() && !dir.join("e.JPG.jpg").exists(), "a name that ends with the extension keeps it"); assert!(std::fs::read(dir.join("f.svgz")).unwrap().starts_with(&[0x1f, 0x8b])); assert_eq!(s.documents().len(), 2); - let _ = std::fs::remove_dir_all(base); } /// Without options, a save or export writes what an untouched new options object of its class gives. @@ -151,7 +164,6 @@ fn omitted_options_are_a_new_options_objects_defaults() { let pdf = std::fs::read(dir.join(name)).unwrap(); assert!(pdf.starts_with(b"%PDF-1.4"), "{name}: PDFCompatibility.ACROBAT5 is PDF 1.4, {:?}", String::from_utf8_lossy(&pdf[..8])); } - let _ = std::fs::remove_dir_all(base); } /// A raster export at 100% has one pixel per point, whatever the document's raster effects @@ -178,7 +190,6 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() { let image = image::open(dir.join(name)).unwrap(); assert_eq!((image.width(), image.height()), (200, 100), "{name}"); } - 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 @@ -203,7 +214,6 @@ fn a_pdf_preset_keeps_its_settings_unless_an_option_changes() { let pdf = std::fs::read(dir.join(name)).unwrap(); assert!(pdf.starts_with(version), "{name}: {:?}", String::from_utf8_lossy(&pdf[..8])); } - let _ = std::fs::remove_dir_all(base); } /// A save that writes several files, such as an EPS with a file per artboard, writes none of them @@ -232,7 +242,6 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); std::fs::set_permissions(&board, perms).unwrap(); - let _ = std::fs::remove_dir_all(base); } /// When the writer a save is given does not check the file access itself, a save of several files @@ -280,7 +289,6 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); std::fs::set_permissions(&refused, perms).unwrap(); - let _ = std::fs::remove_dir_all(base); } /// Every path goes through the script's file grants, as a `File` opened for reading or writing. @@ -326,7 +334,6 @@ fn save_as_export_file_and_open_refuse_paths_outside_the_grants() { #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap(); - let _ = std::fs::remove_dir_all(base); } /// The file of an open document is not written or read through a script method unless the @@ -344,7 +351,6 @@ fn an_open_documents_file_is_not_saved_over_without_a_grant() { let e = failure(&mut s, &base, &format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&path))); assert!(e.contains(DENIED), "{e}"); assert_eq!(std::fs::read(&path).unwrap(), before); - let _ = std::fs::remove_dir_all(base); } /// A save or export to a file a `File` object holds open for writing throws, so the object's bytes @@ -370,7 +376,6 @@ fn a_file_open_for_writing_is_not_saved_over() { assert_eq!(std::fs::read_to_string(dir.join(name)).unwrap(), "pending", "{name}: the File's own bytes"); assert_eq!(s.active().unwrap().path, None, "{name}: the document's file is unchanged"); } - let _ = std::fs::remove_dir_all(base); } /// A file `open` reads besides the one it names, here an SVG's linked image, is read only where @@ -411,7 +416,6 @@ fn open_reads_linked_files_only_where_the_script_may() { std::fs::copy(dir.join("page.svg"), dir.join("copy.svg")).unwrap(); s.execute("document.open", &json!({"path": dir.join("copy.svg").to_string_lossy()})).unwrap(); assert!(ims(&s).is_empty() && kinds(&s).iter().any(|k| k.starts_with("Path")), "{:?}", kinds(&s)); - let _ = std::fs::remove_dir_all(base); } /// An SVG export with `embedRasterImages` false writes the document's embedded image beside the @@ -442,7 +446,6 @@ fn an_svg_export_writes_nothing_when_one_of_its_files_is_refused() { #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); std::fs::set_permissions(&image, perms).unwrap(); - let _ = std::fs::remove_dir_all(base); } /// An export does not write a file it writes besides the one named, here an SVG's image, while a @@ -474,7 +477,6 @@ fn an_svg_export_does_not_write_an_image_a_file_holds_open() { assert!(log[0].as_str().unwrap().contains(DENIED), "{log}"); assert!(!svg.exists(), "the SVG is not written when its image may not be"); assert_eq!(std::fs::read_to_string(&image).unwrap(), "pending", "the File's own bytes"); - let _ = std::fs::remove_dir_all(base); } /// A link inside a granted folder that leads out of it is followed and refused. @@ -497,7 +499,6 @@ fn a_link_out_of_the_granted_folder_is_refused() { assert!(e.contains(DENIED), "{e}"); assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1, "nothing is written outside"); assert_eq!(s.documents().len(), 1); - let _ = std::fs::remove_dir_all(base); } /// Bad arguments throw before anything is written or opened. @@ -576,7 +577,6 @@ fn bad_arguments_are_refused_with_an_error() { assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written"); assert_eq!(s.documents().len(), 1); assert_eq!(s.active().unwrap().path, None); - let _ = std::fs::remove_dir_all(base); } /// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a @@ -613,7 +613,6 @@ fn a_forged_file_is_refused() { assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1); assert_eq!(s.documents().len(), 1, "nothing is opened"); assert_eq!(s.active().unwrap().path, None); - let _ = std::fs::remove_dir_all(base); } /// A document from an earlier run is stale, and saving it throws. @@ -627,7 +626,6 @@ fn a_stale_document_is_not_saved() { let e = failure(&mut s, &base, &format!("#targetengine keep\nFolder.userData; held.saveAs(new File({}));", quoted(&dir.join("x.svg")))); assert!(e.contains("Stale document"), "{e}"); assert!(!dir.join("x.svg").exists()); - let _ = std::fs::remove_dir_all(base); } /// `open` applies the page and crop box of its options to a PDF. @@ -636,9 +634,13 @@ fn open_takes_the_page_and_crop_box_of_its_options() { let base = folder("pdf"); let mut s = session(&base); let dir = data_folder(&mut s, &base); - s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + // Page 2 is 200 × 400 pt with a 180 × 380 pt crop box, unlike page 1's 100 × 100 pt. + let mut second = vectorcraft_testkit::pdf::PdfPage::new(200.0, 400.0, "0 0 1 rg 20 30 40 50 re f"); + second.crop = Some([10.0, 10.0, 190.0, 390.0]); + let pages = [vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"), second]; let pdf = dir.join("two.pdf"); - s.execute("file.saveAs", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap(); + std::fs::write(&pdf, vectorcraft_testkit::pdf::pdf(&pages, None)).unwrap(); + let size = |s: &Session| s.active().map(|st| st.doc.artboards.iter().map(|a| (a.rect.width(), a.rect.height())).collect::>()); let out = logged( &mut s, &base, @@ -649,6 +651,9 @@ fn open_takes_the_page_and_crop_box_of_its_options() { ), ); assert_eq!(out, json!(["DocumentColorSpace.CMYK"])); + assert_eq!(size(&s), Some(vec![(200.0, 400.0)]), "page 2 on its media box"); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 2}});", quoted(&pdf))); + assert_eq!(size(&s), Some(vec![(180.0, 380.0)]), "page 2 on its crop box, the default"); let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 3}});", quoted(&pdf))); assert!(!e.is_empty(), "a page the file does not have"); assert_eq!(s.documents().len(), 2); @@ -658,7 +663,59 @@ fn open_takes_the_page_and_crop_box_of_its_options() { logged(&mut s, &base, &undefined); assert_eq!(s.documents().len(), 3); assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages"); - let _ = std::fs::remove_dir_all(base); +} + +/// An SVG export to a name that ends with `.svgz` writes a compressed file at that name, without +/// options and with `compressed` false; a name without the suffix stays a plain SVG. +#[test] +fn export_file_keeps_an_svgz_name_compressed() { + let base = folder("svgz"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 20, 20);\n\ + vc.run('shape.rectangle', {{x: 2, y: 2, width: 10, height: 10}});\n\ + d.exportFile(new File(dir + '/logo.svgz'), ExportType.SVG);\n\ + var o = new ExportOptionsSVG(); o.compressed = false;\n\ + d.exportFile(new File(dir + '/plain.SVGZ'), ExportType.SVG, o);\n\ + d.exportFile(new File(dir + '/page'), ExportType.SVG);" + ), + ); + for name in ["logo.svgz", "plain.SVGZ"] { + assert!(std::fs::read(dir.join(name)).unwrap().starts_with(&[0x1f, 0x8b]), "{name}"); + assert!(!dir.join(format!("{name}.svg")).exists(), "{name}"); + } + assert!(std::fs::read_to_string(dir.join("page.svg")).unwrap().contains(" PathBuf { let base = std::env::temp_dir().join(format!("vc-script-screens-{name}-{}", std::process::id()));