mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 12:35:48 -05:00
Scripts: refuse read-only export files, hidden rasterize sources and capture over write-only documents
- A multi-file export checks every destination before writing and refuses an existing read-only file, as save does, so no file is written. - object.rasterize and Document.rasterize refuse an id that is hidden or in a hidden layer or group, as they refuse locked ones. - imageCapture compares open documents and linked files that only a write root covers, so it no longer replaces such a document's file. - The blank-capture test also checks the pixel count, as test-lint asks.
This commit is contained in:
1 parent
b14d841476
commit
b91beb68fd
6 files changed
+89
-17
No files matched your search
@@ -88,9 +88,13 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
if files.len() > 1 {
|
||||
for (p, _) in &files {
|
||||
super::may_write(p)?;
|
||||
if std::path::Path::new(p.as_str()).is_dir() {
|
||||
let Ok(meta) = std::fs::metadata(p) else { continue };
|
||||
if meta.is_dir() {
|
||||
return Err(EngineError::Other(format!("{p}: is a folder, not a file")));
|
||||
}
|
||||
if meta.is_file() && meta.permissions().readonly() {
|
||||
return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied)));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
|
||||
@@ -59,6 +59,33 @@ fn readonly_sidecar_leaves_every_save_destination_unchanged() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_export_file_leaves_every_export_destination_unchanged() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("export-readonly-sidecar");
|
||||
let mut session = Session::new();
|
||||
session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap();
|
||||
let doc = session.doc().unwrap().doc.clone();
|
||||
let enc = super::Encoded { files: vec![(None, b"new main".to_vec()), (Some(1), b"new board".to_vec())], ..Default::default() };
|
||||
let path = dir.join("Poster.svg").to_string_lossy().into_owned();
|
||||
let files: Vec<String> = enc.named(&doc, &path).into_iter().map(|(p, _)| p).collect();
|
||||
assert_eq!(files.len(), 2);
|
||||
for file in &files {
|
||||
std::fs::write(file, b"old").unwrap();
|
||||
}
|
||||
let sidecar = &files[1];
|
||||
let original = std::fs::metadata(sidecar).unwrap().permissions();
|
||||
let mut readonly = original.clone();
|
||||
readonly.set_readonly(true);
|
||||
std::fs::set_permissions(sidecar, readonly).unwrap();
|
||||
let result = super::write_encoded(Some(&path), "Poster.svg", &doc, &enc, json!({}));
|
||||
std::fs::set_permissions(sidecar, original).unwrap();
|
||||
let error = result.unwrap_err();
|
||||
assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}");
|
||||
for file in &files {
|
||||
assert_eq!(std::fs::read(file).unwrap(), b"old", "{file}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_failed_save_keeps_document_and_options() {
|
||||
let mut session = Session::new();
|
||||
|
||||
@@ -124,7 +124,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rasterize…",
|
||||
["Object"],
|
||||
None,
|
||||
"{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
|
||||
"{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, off locked artboards, and visible in visible layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
|
||||
has_selection,
|
||||
rasterize
|
||||
),
|
||||
@@ -1014,6 +1014,9 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
if locks.holds_id(*id) {
|
||||
return Err(bad(cmd, format!("id {} is on a locked artboard", id.0)));
|
||||
}
|
||||
if up.iter().any(|a| d.node(*a).is_some_and(|n| !n.visible)) {
|
||||
return Err(bad(cmd, format!("id {} is hidden or in a hidden layer or group", id.0)));
|
||||
}
|
||||
roots.push(*id);
|
||||
}
|
||||
Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d))
|
||||
|
||||
@@ -299,8 +299,13 @@ fn sources_on_disk(h: &Host) -> Vec<Placed> {
|
||||
paths.iter().filter_map(|p| source_place(p)).collect()
|
||||
}
|
||||
|
||||
/// An open document or linked file inside the automation read or write roots: one that only a write
|
||||
/// root covers is compared too, since a capture may write there. A path outside both is left out
|
||||
/// before it is looked up, as no capture can write it; the refusal names only the requested path.
|
||||
fn source_place(path: &str) -> Option<Placed> {
|
||||
crate::file_access::check_read(path).ok()?;
|
||||
if crate::file_access::check_read(path).is_err() && crate::file_access::check_write_unrecorded(path).is_err() {
|
||||
return None;
|
||||
}
|
||||
placed(std::path::Path::new(path))
|
||||
}
|
||||
|
||||
@@ -507,18 +512,28 @@ mod source_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn capture_sources_exclude_files_outside_automation_roots() {
|
||||
fn capture_sources_keep_files_outside_automation_read_roots() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("capture-source-roots");
|
||||
let allowed = dir.join("allowed");
|
||||
std::fs::create_dir(&allowed).unwrap();
|
||||
let inside = allowed.join("doc.vectorcraft");
|
||||
let outside = dir.join("linked.png");
|
||||
let readable = dir.join("readable");
|
||||
let writable = dir.join("writable");
|
||||
std::fs::create_dir(&readable).unwrap();
|
||||
std::fs::create_dir(&writable).unwrap();
|
||||
let inside = readable.join("doc.vectorcraft");
|
||||
// An open document that only a write root covers: a capture to its path must still be
|
||||
// refused.
|
||||
let outside = writable.join("other.vectorcraft");
|
||||
// Outside every root: no capture can write it, so it is not looked up.
|
||||
let elsewhere = dir.join("linked.png");
|
||||
std::fs::write(&inside, b"document").unwrap();
|
||||
std::fs::write(&outside, b"linked").unwrap();
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&allowed], &[&allowed]).unwrap();
|
||||
std::fs::write(&outside, b"document").unwrap();
|
||||
std::fs::write(&elsewhere, b"linked").unwrap();
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&readable], &[&writable]).unwrap();
|
||||
crate::file_access::confine(roots.as_ref(), || {
|
||||
assert!(source_place(&inside.to_string_lossy()).is_some());
|
||||
assert!(source_place(&outside.to_string_lossy()).is_none());
|
||||
assert!(source_place(&elsewhere.to_string_lossy()).is_none());
|
||||
let source = source_place(&outside.to_string_lossy()).expect("a source outside the read roots is still compared");
|
||||
let target = placed(&outside).unwrap();
|
||||
assert!(same_file(&target, &source));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -267,6 +267,25 @@ fn script_rasterize_rejects_groups_with_locked_descendants() {
|
||||
s.execute("object.rasterize", &json!({"ids": [outer], "ppi": 72})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_rejects_explicit_hidden_art() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.setProps", &json!({"id": a.0, "visible": false})).unwrap();
|
||||
s.execute("object.setProps", &json!({"id": group, "visible": false})).unwrap();
|
||||
for id in [a.0, b.0] {
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let undo = undo_steps(&s);
|
||||
let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string();
|
||||
assert!(e.contains("hidden"), "{e}");
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
}
|
||||
s.execute("object.setProps", &json!({"id": a.0, "visible": true})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ids": [a.0], "ppi": 72})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_rejects_explicit_art_on_a_locked_artboard() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -527,6 +546,7 @@ fn image_capture_of_bounds_without_art_is_blank() {
|
||||
for (name, blank) in [("blank.png", [255, 255, 255, 255]), ("clear.png", [0, 0, 0, 0])] {
|
||||
let img = png(&dir.join(name));
|
||||
assert_eq!((img.width(), img.height()), (50, 50), "{name}");
|
||||
assert_eq!(img.pixels().len(), 2500, "{name}");
|
||||
assert!(img.pixels().all(|p| p.0 == blank), "{name}: every pixel is {blank:?}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document");
|
||||
|
||||
+9
-6
@@ -3273,7 +3273,8 @@ 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 the script's folders refuse one of those files, none of them is written; a write that fails once the
|
||||
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
|
||||
pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and
|
||||
@@ -3671,8 +3672,8 @@ through `$`:
|
||||
below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture`
|
||||
writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another
|
||||
document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in
|
||||
a locked layer or group or on a locked artboard throw an error, and nothing changes. An object containing
|
||||
locked descendants also throws an error.
|
||||
a locked layer or group or on a locked artboard, and one that is hidden or in a hidden layer or group throw an
|
||||
error, and nothing changes. An object containing locked descendants also throws an error.
|
||||
Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional
|
||||
dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name.
|
||||
`rasterize` keeps the selection, less the art it replaces. With
|
||||
@@ -3684,8 +3685,9 @@ through `$`:
|
||||
opened for writing is checked, and a path that is an open document's file or a file one of them links throws an
|
||||
error, also when that file is missing. The linked files are every place opening the document looks for a link's
|
||||
file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS
|
||||
image's plate files beside each. Paths rejected by the document's path restrictions or the automation read roots are excluded before filesystem
|
||||
probes. The documents count whether they were open when the run started or were
|
||||
image's plate files beside each. Paths rejected by the document's path restrictions, and paths outside both the
|
||||
automation read and write roots, are left out of the comparison. Open documents and linked files that only
|
||||
a write root covers are still compared, and the error names only the requested path. The documents count whether they were open when the run started or were
|
||||
opened while it was paused. A name that differs from it only in letter case throws the same error in a
|
||||
folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or
|
||||
32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to
|
||||
@@ -11667,7 +11669,8 @@ With `ids`, `object.rasterize` rasterizes those objects instead of the selection
|
||||
without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id
|
||||
listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's
|
||||
clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or
|
||||
in a locked layer or group or on a locked artboard are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down)
|
||||
in a locked layer or group or on a locked artboard, and an object that is hidden or in a hidden layer or group, are
|
||||
refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down)
|
||||
keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused.
|
||||
Dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions
|
||||
round up. The result's
|
||||
|
||||
Reference in new issue
Block a user