mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Scripts: rasterize refuses art holding locked objects
Rasterize by id refuses a group that holds a locked object, as it refuses a locked object itself. A save that writes several files refuses an existing read-only destination before it writes any of them.
This commit is contained in:
1 parent
06eb0f252a
commit
b3dede0a25
5 files changed
+75
-10
No files matched your search
@@ -1078,8 +1078,13 @@ impl SaveJob {
|
||||
for (p, bytes) in &files {
|
||||
if super::may_write(p).is_err() {
|
||||
write(p, bytes)?;
|
||||
} else if std::path::Path::new(p).is_dir() {
|
||||
return Err(crate::EngineError::Other(format!("{p}: is a folder, not a file")));
|
||||
} else if let Ok(meta) = std::fs::metadata(p) {
|
||||
if meta.is_dir() {
|
||||
return Err(crate::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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1387,7 +1392,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written or is a directory, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when access to one of a save's files is refused, or it is a directory or an existing read-only file, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -28,6 +28,37 @@ fn readonly_error_is_typed_and_other_writers_keep_their_error() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_sidecar_leaves_every_save_destination_unchanged() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("save-readonly-sidecar");
|
||||
for format in ["vectorcraft", "eps"] {
|
||||
let mut session = Session::new();
|
||||
session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap();
|
||||
let path = dir.join(format!("Poster.{format}")).to_string_lossy().into_owned();
|
||||
let params = if format == "eps" { json!({"path": path, "useArtboards": true}) } else { json!({"path": path, "separateArtboards": true}) };
|
||||
let saved = session.execute("file.saveAs", ¶ms).unwrap();
|
||||
let files: Vec<_> = saved["files"].as_array().unwrap().iter().map(|p| p.as_str().unwrap()).collect();
|
||||
assert!(files.len() > 1);
|
||||
let before: Vec<_> = files.iter().map(std::fs::read).collect::<std::io::Result<_>>().unwrap();
|
||||
session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();
|
||||
let doc = session.doc().unwrap().doc.clone();
|
||||
let sidecar = files.last().unwrap();
|
||||
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 = session.execute("file.saveAs", ¶ms);
|
||||
std::fs::set_permissions(sidecar, original).unwrap();
|
||||
let error = result.unwrap_err();
|
||||
assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}");
|
||||
for (file, bytes) in files.iter().zip(before) {
|
||||
assert_eq!(std::fs::read(file).unwrap(), bytes, "{file}");
|
||||
}
|
||||
assert_eq!(*session.doc().unwrap().doc, *doc);
|
||||
assert!(session.doc().unwrap().is_dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[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 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, 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)}",
|
||||
has_selection,
|
||||
rasterize
|
||||
),
|
||||
@@ -969,8 +969,8 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec<Node>, p
|
||||
}
|
||||
|
||||
/// The objects `ids` names for Rasterize, in paint order: each an object of the active document,
|
||||
/// listed once, and neither it nor a layer or group it is in locked. An object inside another
|
||||
/// listed one is left out, as `edit::roots_of` leaves it out of a selection.
|
||||
/// listed once, with no locks on it, its descendants, or a layer or group it is in. An object
|
||||
/// inside another listed one is left out, as `edit::roots_of` leaves it out of a selection.
|
||||
fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = super::checked_ids_param(s, p, "ids", cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
@@ -1004,8 +1004,12 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
};
|
||||
return Err(bad(cmd, format!("id {} {message}", id.0)));
|
||||
}
|
||||
if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) {
|
||||
return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0)));
|
||||
let mut locked = false;
|
||||
if let Some(node) = d.node(*id) {
|
||||
node.walk(&mut |n| locked |= n.locked);
|
||||
}
|
||||
if locked || up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) {
|
||||
return Err(bad(cmd, format!("id {} is locked, in a locked layer or group, or contains locked art", id.0)));
|
||||
}
|
||||
if locks.holds_id(*id) {
|
||||
return Err(bad(cmd, format!("id {} is on a locked artboard", id.0)));
|
||||
|
||||
@@ -243,6 +243,30 @@ fn script_rasterize_rejects_locked_art() {
|
||||
refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_rasterize_rejects_groups_with_locked_descendants() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [inner, c.0]})).unwrap();
|
||||
let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.setProps", &json!({"id": a.0, "locked": true})).unwrap();
|
||||
for id in [inner, outer] {
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let selection = s.active().unwrap().selection.objects.clone();
|
||||
let undo = undo_steps(&s);
|
||||
let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string();
|
||||
assert!(e.contains("locked"), "{e}");
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
assert_eq!(s.active().unwrap().selection.objects, selection);
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
}
|
||||
refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked");
|
||||
s.execute("object.setProps", &json!({"id": a.0, "locked": false})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ids": [outer], "ppi": 72})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_rejects_explicit_art_on_a_locked_artboard() {
|
||||
let (mut s, a, b) = doc();
|
||||
|
||||
+3
-2
@@ -3326,7 +3326,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.
|
||||
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.
|
||||
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
|
||||
@@ -12095,7 +12096,7 @@ or in `options` (`file.formatOptions {format}` lists them with their values):
|
||||
- `separateArtboards: true` also writes each artboard of `range` (`"1-3, 5"`, default `"all"`) to
|
||||
`<name>-<artboard>.<ext>` beside the file: that artboard and the art touching it. The result's `files` lists every
|
||||
file written, the master file first (without a path: `files: [{name, dataBase64}]`). 3 artboards give 4 files.
|
||||
The save checks every destination before writing. If any destination is a directory or access is refused,
|
||||
The save checks every destination before writing. If any destination is a directory, an existing read-only file, or access is refused,
|
||||
it leaves every file unwritten. The same check applies to EPS saves that write multiple files.
|
||||
- `includeLinked: true` keeps linked images' own pixels in the file (they stay linked), not just the previews. Linked
|
||||
images in the art of the stored brushes count as those in the layers do, and an image key that the layers or a
|
||||
|
||||
Reference in new issue
Block a user