mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 19:13:27 +00:00
Scripts: addDocument takes only a DocumentPreset and throws when its profile cannot be read
- new DocumentPreset() now makes an object of the DocumentPreset class whose settings the run keeps, so addDocument refuses a plain object, one with a typename of DocumentPreset included, with a TypeError naming presetSettings. - When file.new reports a profileError, addDocument throws an error that names the profile and the reason, and the document made with the defaults is put back. - A script's file.new reads the New Document profile file in the app's own profiles folder; the automation roots in force still apply. Before, the script's file gate refused the folder, so a scripted addDocument never used an edited profile. Docs: docs/mcp.md.
This commit is contained in:
@@ -984,13 +984,18 @@ impl Session {
|
||||
let file = path.to_string_lossy().to_string();
|
||||
// Checked before the file is looked for, so a request that may not read the folder learns
|
||||
// nothing of its files, nor where the folder is.
|
||||
// A script's gate does not apply to reads of the app's own folder; the automation roots in
|
||||
// force still do.
|
||||
let denied = |_| PROFILE_DENIED.to_string();
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) {
|
||||
return Ok(None);
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?;
|
||||
let read = crate::file_access::app_folder_read(|| {
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) {
|
||||
return Ok(None);
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some)
|
||||
})?;
|
||||
let Some(bytes) = read else { return Ok(None) };
|
||||
// The color profiles the file carries are installed where missing, as opening it installs
|
||||
// them, so the new document's assigned profiles draw and are saved with it.
|
||||
let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -206,9 +206,16 @@ pub fn unconfined<T>(f: impl FnOnce() -> T) -> T {
|
||||
with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f))
|
||||
}
|
||||
|
||||
/// Run `f`, a read of a file in one of the app's own folders, with reads exempt from the gate of
|
||||
/// the script command this thread runs. Unlike [`unconfined`], the roots in force still apply.
|
||||
pub(crate) fn app_folder_read<T>(f: impl FnOnce() -> T) -> T {
|
||||
with_gate_reads_exempt(true, f)
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Are reads on this thread exempt from the gate of the script command it runs? Only inside an
|
||||
/// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]).
|
||||
/// [`unconfined`] or an [`app_folder_read`] entered after the gate was put in force
|
||||
/// ([`with_script_gate`]).
|
||||
static GATE_READS_EXEMPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
|
||||
@@ -85,13 +85,14 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
|
||||
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
|
||||
/// What the object model keeps for one run: its coordinate system, the last list of a document's
|
||||
/// page items, kept while that document is unchanged, and whether a call's own savepoint
|
||||
/// ([`atomically`]) is open.
|
||||
/// page items, kept while that document is unchanged, whether a call's own savepoint
|
||||
/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
items: RefCell<Option<ItemList>>,
|
||||
saving: Cell<bool>,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
@@ -873,10 +874,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Range("the startup preset's name is too long".into()));
|
||||
}
|
||||
let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?;
|
||||
// Only an object `new DocumentPreset()` made: a plain object such as `{width: 500}` is refused.
|
||||
let settings = match given(arg(a, 2)) {
|
||||
None | Some(Data::Null) => Vec::new(),
|
||||
Some(Data::Object(o)) => o.clone(),
|
||||
Some(_) => return Err(HostError::Type("presetSettings must be a DocumentPreset".into())),
|
||||
Some(d) => {
|
||||
let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?;
|
||||
h.dom.presets.borrow()[i].clone()
|
||||
}
|
||||
};
|
||||
let field = |k: &str| settings.iter().find(|(n, _)| n == k).map(|(_, v)| v).and_then(given);
|
||||
for k in ["documentBleedLink", "documentBleedOffsetRect", "transparencyGrid"] {
|
||||
@@ -913,23 +917,101 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
if let Some(m) = mode {
|
||||
p.entry("colorMode").or_insert_with(|| json!(m));
|
||||
}
|
||||
new_document(h, p)
|
||||
// A profile whose file could not be read throws, and the document `file.new` made with the
|
||||
// defaults is put back, with the Recent sizes as they were.
|
||||
atomically(h, |h| {
|
||||
let (_, value) = command_value(h, "file.new", &Value::Object(p))?;
|
||||
if let Some(e) = value.get("profileError") {
|
||||
let profile = e["profile"].as_str().unwrap_or_default();
|
||||
let reason = e["reason"].as_str().unwrap_or_default();
|
||||
return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}")));
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
|
||||
Ok(doc_ref(h, st.uid))
|
||||
})
|
||||
}
|
||||
|
||||
/// `new DocumentPreset()`: a record of new-document settings with the defaults the help page
|
||||
/// <https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/> gives; the other settings are
|
||||
/// left out.
|
||||
fn new_preset(_: &[Data]) -> Answer {
|
||||
/// left out. The settings stay with the run, which hands the script an object of the
|
||||
/// `DocumentPreset` class.
|
||||
fn new_preset(h: &Host) -> Answer {
|
||||
let mut presets = h.dom.presets.borrow_mut();
|
||||
if presets.len() >= MAX_PRESETS {
|
||||
return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets")));
|
||||
}
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
Ok(Data::Object(vec![
|
||||
item("typename", text("DocumentPreset")),
|
||||
presets.push(vec![
|
||||
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
|
||||
item("artboardRowsOrCols", num(1.0)),
|
||||
item("artboardSpacing", num(20.0)),
|
||||
item("height", num(792.0)),
|
||||
item("numArtboards", num(1.0)),
|
||||
item("width", num(612.0)),
|
||||
]))
|
||||
]);
|
||||
Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)]))
|
||||
}
|
||||
|
||||
/// The most `DocumentPreset` objects one run can make.
|
||||
const MAX_PRESETS: usize = 10_000;
|
||||
|
||||
/// The settings a `DocumentPreset` has, each a property a script reads and assigns.
|
||||
const PRESET_FIELDS: &[&str] = &[
|
||||
"artboardLayout",
|
||||
"artboardRowsOrCols",
|
||||
"artboardSpacing",
|
||||
"colorMode",
|
||||
"documentBleedLink",
|
||||
"documentBleedOffsetRect",
|
||||
"height",
|
||||
"numArtboards",
|
||||
"previewMode",
|
||||
"rasterResolution",
|
||||
"title",
|
||||
"transparencyGrid",
|
||||
"units",
|
||||
"width",
|
||||
];
|
||||
|
||||
/// The index in the run's presets of the `DocumentPreset` `d` is, when it is one this run made.
|
||||
fn preset_of(h: &Host, d: &Data) -> Option<usize> {
|
||||
let handle = handle_of(d, "DocumentPreset")?;
|
||||
let [run, i] = handle.as_slice() else { return None };
|
||||
if whole(*run) != Some(h.run) {
|
||||
return None;
|
||||
}
|
||||
let i = usize::try_from(whole(*i)?).ok()?;
|
||||
(i < h.dom.presets.borrow().len()).then_some(i)
|
||||
}
|
||||
|
||||
/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and
|
||||
/// a value is checked when `addDocument` uses it.
|
||||
fn preset_field(link: &Link, key: &'static str) -> HostMember {
|
||||
let not_preset = || HostError::Type("this is not a DocumentPreset".into());
|
||||
let l = link.clone();
|
||||
let get: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?;
|
||||
let presets = h.dom.presets.borrow();
|
||||
Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone()))
|
||||
});
|
||||
let l = link.clone();
|
||||
let set: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
let value = arg(&a, 1).clone();
|
||||
h.charge_call(16 + data_size(&value))?;
|
||||
let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?;
|
||||
let mut presets = h.dom.presets.borrow_mut();
|
||||
let fields = &mut presets[i];
|
||||
match fields.iter_mut().find(|(k, _)| k == key) {
|
||||
Some((_, v)) => *v = value,
|
||||
None => fields.push((key.to_string(), value)),
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
});
|
||||
HostMember::Property { get, set }
|
||||
}
|
||||
|
||||
// ---- Document ----
|
||||
@@ -1723,11 +1805,14 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
application.push(later(l, "Application", "beep"));
|
||||
let preset = {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
current(&l)?.charge_call(64)?;
|
||||
new_preset(&a)
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(64)?;
|
||||
new_preset(&h)
|
||||
});
|
||||
HostClass { name: "DocumentPreset".into(), parent: None, members: Vec::new(), index: None, construct: Some(f) }
|
||||
let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))];
|
||||
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k))));
|
||||
HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) }
|
||||
};
|
||||
let mut classes = vec![
|
||||
class("Application", None, application, None),
|
||||
|
||||
@@ -835,6 +835,66 @@ fn headless_add_document_dialog_fails_without_creating() {
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_document_takes_only_a_document_preset() {
|
||||
let mut s = Session::new();
|
||||
for source in [
|
||||
"app.documents.addDocument('Print', {width: 500});",
|
||||
"app.documents.addDocument('Print', {});",
|
||||
"app.documents.addDocument('Print', {typename: 'DocumentPreset', width: 500});",
|
||||
"var p = new DocumentPreset(); var q = {}; for (var k in p) q[k] = p[k]; app.documents.addDocument('Print', q);",
|
||||
"app.documents.addDocument('Print', [612, 792]);",
|
||||
"app.documents.addDocument('Print', 'DocumentPreset');",
|
||||
] {
|
||||
let e = failure(&mut s, source);
|
||||
assert!(e.contains("TypeError") && e.contains("presetSettings must be a DocumentPreset"), "{source}: {e}");
|
||||
}
|
||||
assert!(s.documents().is_empty(), "a refused preset makes no document");
|
||||
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 500; vc.log(app.documents.addDocument('Print', p).width);");
|
||||
assert_eq!(out, vec![json!(500)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut s = Session::new();
|
||||
s.attach_new_doc_profiles(dir.clone());
|
||||
// A profile with no file gives the defaults.
|
||||
let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);");
|
||||
assert_eq!(out, vec![json!("Document")]);
|
||||
assert_eq!(s.doc().unwrap().links_from, None);
|
||||
// A script reads the profile's file in the app's own folder.
|
||||
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
|
||||
let file = dir.join("Print.vectorcraft").to_string_lossy().to_string();
|
||||
log(&mut s, "app.documents.addDocument('Print');");
|
||||
assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str()));
|
||||
while !s.documents().is_empty() {
|
||||
s.execute("file.close", &json!({})).unwrap();
|
||||
}
|
||||
std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap();
|
||||
// file.new itself makes the document with the defaults and reports the profile it could not read.
|
||||
let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap();
|
||||
assert_eq!(r["profileError"]["profile"], "Print", "{r}");
|
||||
s.execute("file.close", &json!({})).unwrap();
|
||||
let recent = s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap();
|
||||
let e = failure(&mut s, "app.documents.addDocument('Print');");
|
||||
assert!(e.contains("Error: the New Document profile Print could not be read"), "{e}");
|
||||
assert!(s.documents().is_empty(), "the document made with the defaults is put back");
|
||||
// A script that catches the error finds nothing changed.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = new DocumentPreset(); p.width = 333;\
|
||||
try { app.documents.addDocument('Print', p); } catch (e) { vc.log(e.name); } vc.log(app.documents.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Error"), json!(0)]);
|
||||
assert_eq!(s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(), recent, "the Recent sizes are as they were");
|
||||
// A startup preset with no profile reads no file.
|
||||
let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);");
|
||||
assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrappers_go_stale_after_delete_and_undo() {
|
||||
let (mut s, _, _) = doc();
|
||||
|
||||
@@ -73,7 +73,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
),
|
||||
(
|
||||
"",
|
||||
"app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \
|
||||
"app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||||
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \
|
||||
PageItems RulerUnits ZOrderMethod",
|
||||
),
|
||||
@@ -83,6 +83,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \
|
||||
selection typename",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
"DocumentPreset.prototype.",
|
||||
"artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \
|
||||
colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \
|
||||
height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \
|
||||
transparencyGrid transparencyGrid= typename units units= width width=",
|
||||
),
|
||||
("Documents.", "prototype"),
|
||||
("Documents.prototype.", "add addDocument constructor getByName index length parent typename"),
|
||||
("Document.", "prototype"),
|
||||
@@ -123,9 +131,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
];
|
||||
|
||||
/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset`
|
||||
/// and the page item types.
|
||||
const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \
|
||||
/// The classes the host adds with nothing but a prototype and its constructor: the page item types.
|
||||
const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \
|
||||
PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame";
|
||||
|
||||
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
|
||||
|
||||
+8
-2
@@ -2633,7 +2633,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset`
|
||||
starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and
|
||||
`transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when
|
||||
the preset it is given holds one of them with a value other than `null`, and makes no document.
|
||||
the preset it is given holds one of them with a value other than `null`, and makes no document. A
|
||||
`presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a
|
||||
`TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the
|
||||
automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the
|
||||
profile and the reason, and makes no document.
|
||||
`showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`,
|
||||
`width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source,
|
||||
destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/)
|
||||
@@ -9045,7 +9049,9 @@ The profile is read on every `file.new`, so a replayed journal or a recorded act
|
||||
runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read.
|
||||
When the file cannot be read, is too large or is not a native document, or the request's read roots leave out the
|
||||
folder (whether or not the file exists), the document starts with the defaults and
|
||||
`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar. The
|
||||
`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and
|
||||
a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's
|
||||
file. The
|
||||
reason given when the read roots leave out the folder does not name the folder's path. Color profiles the profile's
|
||||
file carries are installed when they are missing, as `document.open` installs them, and each one that can't be used
|
||||
adds a line to `file.new`'s `warnings`. The new document's links find their files through relative paths from the
|
||||
|
||||
Reference in New Issue
Block a user