Merge pull request #9097 from dotCooCoo/feat/scripts-xmp-objects

Scripts: ExternalObject loads the XMP objects XMPMeta, XMPFile and XMPConst
This commit is contained in:
BFlat authored and GitHub committed 2026-11-27 11:55:06 +07:00
commit 5958a5e95c
19 files changed
+5720 -11

No files matched your search

Generated
+1
View File
@@ -8670,6 +8670,7 @@ name = "vectorcraft-js"
version = "0.24.1"
dependencies = [
"chrono",
"craft-xml",
"getrandom 0.4.3",
"proptest",
"unicode-properties",
+248 -3
View File
@@ -1684,8 +1684,12 @@ fn millis(t: Option<std::time::SystemTime>) -> Data {
/// One host function of `__vcFiles`, counted and charged as a host call of the run `link` holds.
fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem {
HostItem::Function(call_function(link, f))
}
fn call_function(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> vectorcraft_js::HostFunction {
let l = link.clone();
HostItem::Function(Rc::new(move |a| {
Rc::new(move |a| {
let h = super::current(&l)?;
bump(&h.counts.file_calls);
let r = f(&h, &a);
@@ -1693,7 +1697,7 @@ fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) ->
let r = r?;
h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?;
Ok(r)
}))
})
}
/// `Ok(true)`, or `{error}` for a failure.
@@ -1875,6 +1879,228 @@ fn copy(host: &Host, a: &[Data]) -> Result<Data, HostError> {
Ok(done(r.map_err(|_| WRITE_FAILED)))
}
/// Is `path` an XMP sidecar file, by its `.xmp` extension in any case?
fn is_sidecar(path: &str) -> bool {
Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp"))
}
/// The text of a sidecar's bytes and its character form as `XMPFile.getPacketInfo` gives it: 0 for
/// UTF-8, 2 for UTF-16 big-endian and 3 for UTF-16 little-endian, by its byte order mark.
fn sidecar_text(bytes: &[u8]) -> Option<(String, u32)> {
let utf16 = |rest: &[u8], big: bool| {
let units = rest.as_chunks::<2>().0.iter().map(|&pair| if big { u16::from_be_bytes(pair) } else { u16::from_le_bytes(pair) });
rest.len().is_multiple_of(2).then(|| char::decode_utf16(units).collect::<Result<String, _>>().ok()).flatten()
};
match bytes {
[0xEF, 0xBB, 0xBF, rest @ ..] => std::str::from_utf8(rest).ok().map(|t| (t.to_string(), 0)),
[0xFE, 0xFF, rest @ ..] => utf16(rest, true).map(|t| (t, 2)),
[0xFF, 0xFE, rest @ ..] => utf16(rest, false).map(|t| (t, 3)),
_ => std::str::from_utf8(bytes).ok().map(|t| (t.to_string(), 0)),
}
}
/// `xmpOpen(path, update, scan)`: the XMP packet of the file at `path` for `XMPFile`, read under
/// the rules for reading; with `update`, a file that can take a packet must also be one the run may write. A `.xmp` file
/// is read whole as its packet unless `scan`; any other file is scanned for its first UTF-8 packet.
/// → `{packet, offset, length, writeable, sidecar, charForm}`, with `packet` null when the file has
/// none.
fn xmp_open(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let path = arg_text(a, 0);
let (update, scan) = (matches!(a.get(1), Some(Data::Bool(true))), matches!(a.get(2), Some(Data::Bool(true))));
let mut disk = host.disk.borrow_mut();
match disk.stat(&path) {
Ok(Some(e)) if !e.file => return Ok(error(NOT_REGULAR)),
Ok(Some(e)) if e.len > MAX_FILE_BYTES as u64 => return Ok(error(TOO_LARGE)),
Ok(Some(_)) => {}
Ok(None) => return Ok(error(NOT_FOUND)),
Err(m) => return Ok(error(m)),
}
let (real, bytes) = match disk.scope.read(Path::new(&path), MAX_FILE_BYTES) {
Ok(read) => read,
Err(ScriptRead::TooLarge) => return Ok(error(TOO_LARGE)),
Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)),
Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)),
Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)),
};
disk.charge_read(&real, bytes.len())?;
let sidecar = is_sidecar(&path) && is_sidecar(&real.to_string_lossy()) && !scan;
// Only a file that can take a packet needs to be one the run may write.
if update
&& sidecar
&& let Err(m) = disk.target(&path, true)
{
return Ok(error(m));
}
let number = |n: usize| Data::Number(n as f64);
let (packet, offset, length, writeable, char_form) = if sidecar {
let Some((text, form)) = sidecar_text(&bytes) else { return Ok(error(UNDECODABLE)) };
(Data::String(text), 0, bytes.len(), true, form)
} else {
match vectorcraft_js::find_xmp_packet(&bytes) {
Some(span) => match bytes.get(span.start..span.end).map(std::str::from_utf8) {
Some(Ok(text)) => (Data::String(text.to_string()), span.start, span.end - span.start, span.writeable, 0),
_ => return Ok(error(UNDECODABLE)),
},
None => (Data::Null, 0, 0, false, 0),
}
};
Ok(Data::Object(vec![
("packet".into(), packet),
("offset".into(), number(offset)),
("length".into(), number(length)),
("writeable".into(), Data::Bool(writeable)),
("sidecar".into(), Data::Bool(sidecar)),
("charForm".into(), Data::Number(f64::from(char_form))),
]))
}
fn xmp_utf8_packet(text: &str) -> Result<Vec<u8>, &'static str> {
let body = text.strip_prefix('\u{feff}').unwrap_or(text);
if body.starts_with("<?xml") && body.as_bytes().get(5).is_some_and(|byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n')) {
let options = craft_xml::Options { pis: true, comments: true, drop_blank_text: false, ..craft_xml::Options::default() }.strict();
let mut events = options.events(body.as_bytes());
match events.next() {
Ok(Some(_)) => Ok(body.as_bytes()[events.span().start..].to_vec()),
_ => Err(UNDECODABLE),
}
} else {
Ok(text.as_bytes().to_vec())
}
}
/// `xmpWrite(path, packet, safely)`: the `.xmp` file at `path` replaced by `packet` in UTF-8, under
/// the rules for writing. The packet goes to a temporary file in the same folder that then takes the
/// file's name, when the run may write there; otherwise to the file itself, unless `safely`, which
/// fails and leaves the file as it is. Open objects of the file hold the new bytes.
/// The writer omits a leading XML declaration.
/// On Unix, the destination folder is flushed after writing. A folder flush failure returns an
/// error after the written path is recorded and open readers receive the replacement packet.
fn xmp_write(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let path = arg_text(a, 0);
let packet = match xmp_utf8_packet(&arg_text(a, 1)) {
Ok(packet) => packet,
Err(message) => return Ok(error(message)),
};
let safely = matches!(a.get(2), Some(Data::Bool(true)));
if !is_sidecar(&path) {
return Ok(error(ACCESS_DENIED));
}
if packet.len() > MAX_FILE_BYTES {
return Ok(error(TOO_LARGE));
}
let mut disk = host.disk.borrow_mut();
let target = match disk.target(&path, true) {
Ok(t) => t,
Err(m) => return Ok(error(m)),
};
// A `.xmp` link that leads to another kind of file does not make that file a sidecar.
if !is_sidecar(&target.to_string_lossy()) {
return Ok(error(ACCESS_DENIED));
}
if std::fs::metadata(&target).is_ok_and(|m| !m.is_file()) {
return Ok(error(NOT_REGULAR));
}
// An open object of the file with changes not yet written keeps them: the packet is not written
// over them.
if disk.open.values().any(|o| o.dirty && o.holds(&target)) {
return Ok(error(WRITE_FAILED));
}
let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let temp_name = |n: u32| target.with_file_name(format!(".{name}.{}.{n}.tmp", std::process::id()));
let first = temp_name(0);
let temp_allowed = disk.target(&first.to_string_lossy(), false).is_ok_and(|t| t == first);
// A safe update writes only through a temporary file.
if safely && !temp_allowed {
return Ok(error(WRITE_FAILED));
}
let holders = disk.open.values().filter(|o| o.holds(&target)).count();
disk.charge_write(packet.len().saturating_mul(holders.saturating_add(1)))?;
// `changed` is whether the file's bytes may differ from before: after a replacement, or once a
// direct write has opened (and so emptied) the file.
let (r, changed) = if temp_allowed {
// The temporary file takes a name no file or link has, so only the sidecar is replaced; when
// none of the names is free the sidecar is left as it is.
// Each name is checked against the places the run may write before it is made.
let allowed = |t: &Path| disk.target(&t.to_string_lossy(), false).is_ok_and(|r| r == t);
let new_file = |t: &Path| {
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
// On Unix the file starts readable and writable by its owner alone, until the packet is in
// it and the sidecar's permission bits are copied to it.
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
allowed(t).then(|| options.open(t).ok()).flatten()
};
let Some((temp, mut out)) = (0..16).map(temp_name).find_map(|t| new_file(&t).map(|f| (t, f))) else {
return Ok(error(WRITE_FAILED));
};
let mut write_temp = || {
#[cfg(test)]
if XMP_WRITE_FAILS.with(std::cell::Cell::get) {
return Err(std::io::Error::other("write failed"));
}
#[cfg(all(test, unix))]
{
let mode = std::os::unix::fs::PermissionsExt::mode(&out.metadata()?.permissions());
XMP_TEMP_MODE.with(|m| m.set(Some(mode)));
}
std::io::Write::write_all(&mut out, &packet)?;
// The packet is on the disk before it takes the sidecar's name, as a saved document's is.
#[cfg(not(target_arch = "wasm32"))]
vectorcraft_format::sync_file(&out)?;
Ok(())
};
let r = write_temp();
drop(out);
// The replacement keeps the sidecar's permission bits, group and (Linux) access ACL, or is
// readable by its owner alone, as a saved document is (`vectorcraft_format::keep_permissions`).
// On Windows the only permission is the read-only attribute, and a read-only temporary file
// could not be removed after a failed rename. The web build has no such files. Keeping them
// is best effort, as for a saved document: a volume without Unix permissions (SMB, FAT) refuses them, and the
// update still goes through.
#[cfg(not(target_arch = "wasm32"))]
if r.is_ok() {
let _ = vectorcraft_format::keep_permissions(&target, &temp);
}
let r = r.and_then(|()| std::fs::rename(&temp, &target)).inspect_err(|_| {
let _ = std::fs::remove_file(&temp);
});
let changed = r.is_ok();
(r, changed)
} else {
match std::fs::File::create(&target) {
Ok(mut f) => (std::io::Write::write_all(&mut f, &packet), true),
Err(e) => (Err(e), false),
}
};
if changed {
disk.wrote(&target);
}
if r.is_ok() {
for file in disk.open.values_mut().filter(|o| o.holds(&target)) {
let reset = file.bytes.starts_with(&[0xEF, 0xBB, 0xBF]) || matches!(file.encoding, Encoding::Utf16Le | Encoding::Utf16Be);
file.bytes.clone_from(&packet);
// `File` readers with a UTF-8 byte order mark or UTF-16 encoding restart in UTF-8.
if reset {
file.encoding = Encoding::Utf8;
file.name = Encoding::Utf8.name().to_string();
file.pos = 0;
}
file.pos = file.pos.min(packet.len());
file.dirty = false;
}
}
#[cfg(all(unix, not(target_arch = "wasm32")))]
let r = r.and_then(|()| {
#[cfg(test)]
if XMP_DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) {
return Err(std::io::Error::other("directory flush failed"));
}
vectorcraft_format::sync_parent(&target)
});
Ok(done(r.map_err(|_| WRITE_FAILED)))
}
/// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to.
fn remove(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let mut disk = host.disk.borrow_mut();
@@ -2480,8 +2706,20 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
("setHidden".into(), call(link, set_hidden)),
("createAlias".into(), call(link, create_alias)),
("pick".into(), call(link, pick)),
("xmpOpen".into(), call(link, xmp_open)),
(
"xmpWrite".into(),
HostItem::FunctionWithLimits {
limits: vectorcraft_js::DataLimits {
bytes: 3 * vectorcraft_js::XMP_MAX_BYTES + (128 << 10),
..vectorcraft_js::DataLimits::default()
},
function: call_function(link, xmp_write),
},
),
];
realm.define_file_classes(items)
realm.define_file_classes(items)?;
realm.define_external_object()
}
/// Tests: what the next `copy` does with its source's path, as given and as its real path, after
@@ -2501,6 +2739,13 @@ thread_local! {
pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell<Option<AliasHook>> = const { std::cell::RefCell::new(None) };
/// Tests: while set, the bytes `flush` writes fail after the file was opened for them.
pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: while set, `xmpWrite` fails after its checks and before it writes.
pub(crate) static XMP_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
#[cfg(unix)]
pub(crate) static XMP_DIRECTORY_SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: the permission bits of the last temporary file `xmpWrite` made, before it wrote to it.
#[cfg(unix)]
pub(crate) static XMP_TEMP_MODE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
+1
View File
@@ -184,6 +184,7 @@ mod script_include;
mod script_io;
mod script_run;
mod script_tags;
mod script_xmp;
mod scripts;
mod segment_nudge;
mod select_effects;
+815
View File
@@ -0,0 +1,815 @@
//! `XMPFile` in a script: reading and writing a sidecar packet through the script's file places,
//! scanning another file for its packet, and the paths and packets it refuses.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::*;
const LOAD: &str = "new ExternalObject('lib:AdobeXMPScript');\n";
const PACKET: &str = "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\
<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
<rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\
<dc:format>image/svg+xml</dc:format><dc:subject><rdf:Bag><rdf:li>a</rdf:li><rdf:li>b</rdf:li></rdf:Bag></dc:subject>\
</rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>";
#[test]
fn a_large_supported_packet_crosses_the_sidecar_write_transport() {
let base = folder("large-write-transport");
let payload = "x".repeat(6 << 20);
let packet = PACKET.replace("image/svg+xml", &payload);
let mut session = with_data(&base);
let setup = logged(&mut session, &base, "vc.log(Folder.userData.fsName + '/large.xmp');");
let path = PathBuf::from(setup[0].as_str().unwrap());
write(&path, packet.as_bytes());
let log = logged(
&mut session,
&base,
"var p = Folder.userData.fsName + '/large.xmp'; var x = new XMPFile(p, XMPConst.FILE_XML, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'title', 'changed-for-write'); x.putXMP(m); x.closeFile(); vc.log(true);",
);
assert_eq!(log, json!([true]));
let written = std::fs::read_to_string(path).unwrap();
assert!(written.contains(&payload));
assert!(written.contains("changed-for-write"));
}
struct Folder {
_guard: vectorcraft_testkit::TempDir,
path: PathBuf,
}
impl std::ops::Deref for Folder {
type Target = PathBuf;
fn deref(&self) -> &Self::Target {
&self.path
}
}
impl AsRef<Path> for Folder {
fn as_ref(&self) -> &Path {
&self.path
}
}
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path.
fn folder(name: &str) -> Folder {
let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}"));
let base = std::fs::canonicalize(&*guard).unwrap();
std::fs::create_dir_all(base.join("main")).unwrap();
Folder { _guard: guard, path: base }
}
fn write(path: &Path, bytes: &[u8]) {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).unwrap();
}
std::fs::write(path, bytes).unwrap();
}
/// A session whose scripts keep their data folders in `base/settings/Script Data`.
fn with_data(base: &Path) -> Session {
let mut s = Session::new();
s.attach_script_data(base.join("settings/Script Data"));
s
}
/// Runs `main/main.jsx` in `base` with the XMP library loaded and the text `text` in `s`.
fn run_in(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
let main = base.join("main/main.jsx");
write(&main, format!("{LOAD}{text}").as_bytes());
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
}
/// The values the run of `text` logged.
fn logged(s: &mut Session, base: &Path, text: &str) -> Value {
match run_in(s, base, text) {
Ok(r) => r["log"].clone(),
Err(e) => panic!("{text}\n{e}"),
}
}
/// A sidecar in the script's data folder reads, takes a changed packet and holds it after
/// `closeFile`; a new `XMPFile` reads it back.
#[test]
fn a_sidecar_packet_reads_and_writes() {
let base = folder("sidecar");
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!(
"var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.encoding = 'UTF-8'; f.open('w'); f.write({PACKET:?}); f.close();\n\
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = x.getXMP(); var info = x.getFileInfo();\n\
var out = [m.getProperty(XMPConst.NS_DC, 'format').value, m.countArrayItems(XMPConst.NS_DC, 'subject'), info.format == XMPConst.FILE_XML, x.canPutXMP(m)];\n\
m.setProperty(XMPConst.NS_DC, 'format', 'text/plain'); m.appendArrayItem(XMPConst.NS_DC, 'subject', 'c');\n\
x.putXMP(m); x.closeFile();\n\
var y = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var n = y.getXMP();\n\
out.push(n.getProperty(XMPConst.NS_DC, 'format').value, n.getArrayItem(XMPConst.NS_DC, 'subject', 3).value, y.getPacketInfo().offset, y.canPutXMP(n));\n\
y.closeFile(); vc.log(out); vc.log(p);"
),
);
assert_eq!(log[0], json!(["image/svg+xml", 2, true, true, "text/plain", "c", 0, false]));
let path = PathBuf::from(log[1].as_str().unwrap());
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("<dc:format>text/plain</dc:format>"), "{text}");
let leftovers: Vec<_> = std::fs::read_dir(path.parent().unwrap()).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name()).collect();
assert_eq!(leftovers.len(), 1, "no temporary file stays: {leftovers:?}");
let _ = std::fs::remove_dir_all(base);
}
/// A file that is not a sidecar is scanned for its packet, read only, and a file with none gives
/// `null`.
#[test]
fn another_file_is_scanned_for_its_packet() {
let base = folder("scan");
let mut bytes = b"\x89binary\x00head".to_vec();
bytes.extend_from_slice(PACKET.as_bytes());
bytes.extend_from_slice(b"\x00tail");
write(&base.join("main/art.bin"), &bytes);
write(&base.join("main/none.bin"), b"no packet here");
let mut s = Session::new();
let log = logged(
&mut s,
&base,
"var x = new XMPFile(File('art.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var i = x.getPacketInfo();\n\
var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, i.offset, i.length, i.writeable, x.canPutXMP(x.getXMP())];\n\
try { x.putXMP(x.getXMP()); out.push('put'); } catch (e) { out.push(e.message); }\n\
out.push(new XMPFile(File('none.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ).getXMP());\n\
x.closeFile(); try { x.getXMP(); } catch (e) { out.push(e.message); } vc.log(out);",
);
assert_eq!(
log[0],
json!([
"image/svg+xml",
12,
PACKET.len(),
true,
false,
"XMPFile.putXMP: the file cannot be updated",
null,
"XMPFile.getXMP: the file is closed"
])
);
let _ = std::fs::remove_dir_all(base);
}
/// `getPacketInfo().padSize` gives the bytes of whitespace before the packet's trailer: twice the
/// characters in a UTF-16 packet, and 0 in a packet with none.
#[test]
fn packet_info_gives_the_padding() {
let base = folder("pad");
let padded = PACKET.replace("<?xpacket end=", " \n\t \n<?xpacket end=");
write(&base.join("main/p.xmp"), padded.as_bytes());
let mut le = vec![0xFF, 0xFE];
le.extend(padded.encode_utf16().flat_map(u16::to_le_bytes));
write(&base.join("main/le.xmp"), &le);
write(&base.join("main/art.bin"), format!("\x00head{padded}\x00tail").as_bytes());
write(&base.join("main/none.xmp"), PACKET.as_bytes());
let mut s = Session::new();
let log = logged(
&mut s,
&base,
"vc.log(['p.xmp', 'le.xmp', 'art.bin', 'none.xmp'].map(function (n) {\n\
var x = new XMPFile(File(n).fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var p = x.getPacketInfo().padSize; x.closeFile(); return p;\n\
}));",
);
assert_eq!(log[0], json!([5, 10, 5, 0]));
let _ = std::fs::remove_dir_all(base);
}
/// A sidecar opened for update with packet scanning is read only, like any scanned file.
#[test]
fn a_scanned_sidecar_is_read_only() {
let base = folder("scansidecar");
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!(
"var p = Folder.userData.fsName + '/s.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE | XMPConst.OPEN_USE_PACKET_SCANNING); var m = x.getXMP();\n\
var out = [m.getProperty(XMPConst.NS_DC, 'format').value, x.canPutXMP(m)];\n\
try {{ x.putXMP(m); out.push('put'); }} catch (e) {{ out.push(e.message); }} x.closeFile(); vc.log(out);"
),
);
assert_eq!(log[0], json!(["image/svg+xml", false, "XMPFile.putXMP: the file cannot be updated"]));
let _ = std::fs::remove_dir_all(base);
}
/// The state an `XMPFile` keeps cannot be changed by the script: a sidecar opened for reading is
/// not written by `closeFile` after the script assigns, defines or deletes the properties that
/// name the packet, the path and the open flags, or calls `closeFile` on another object that holds
/// properties of the same names, plain or made from `XMPFile.prototype`.
#[test]
fn a_script_cannot_change_the_state_of_an_xmp_file() {
let base = folder("state");
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!(
"var p = Folder.userData.fsName + '/r.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var out = [];\n\
x.__vcXmpPending = 'not a packet'; x.__vcXmpFlags = XMPConst.OPEN_FOR_UPDATE; x.__vcXmpPath = p + '.other';\n\
try {{ Object.defineProperty(x, '__vcXmpPending', {{ value: 'not a packet' }}); out.push('defined'); }} catch (e) {{ out.push(e.name); }}\n\
out.push(typeof x.__vcXmpPending, x.getFileInfo().openFlags == XMPConst.OPEN_FOR_READ);\n\
[{{}}, Object.create(XMPFile.prototype)].forEach(function (fake) {{\n\
fake.__vcXmpPath = p; fake.__vcXmpRun = x.__vcXmpRun; fake.__vcXmpOpen = true; fake.__vcXmpPending = 'not a packet';\n\
try {{ XMPFile.prototype.closeFile.call(fake); out.push('closed'); }} catch (e) {{ out.push(e.name); }}\n\
}});\n\
x.closeFile(); out.push(delete x.__vcXmpPath); vc.log(out); vc.log(p);"
),
);
assert_eq!(log[0], json!(["defined", "string", true, "TypeError", "TypeError", true]));
let text = std::fs::read_to_string(log[1].as_str().unwrap()).unwrap();
assert_eq!(text, PACKET);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn xmp_file_buffers_are_not_script_properties() {
let base = folder("native-packet");
let mut session = with_data(&base);
let log = logged(
&mut session,
&base,
&format!(
"var p = Folder.userData.fsName + '/native.xmp', file = new File(p);\n\
file.open('w'); file.write({PACKET:?}); file.close();\n\
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE), m = x.getXMP();\n\
m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
vc.log([typeof x.__vcXmpPacket, typeof x.__vcXmpPending, typeof x.__vcXmpPath,\n\
Object.getOwnPropertyNames(x).filter(function (name) {{ return name.indexOf('__vcXmp') === 0; }}).length,\n\
x.getXMP().getProperty(XMPConst.NS_DC, 'format').value]); x.closeFile();"
),
);
assert_eq!(log[0], json!(["undefined", "undefined", "undefined", 0, "changed"]));
}
/// A path outside the script's places, a missing file and a file opened for update where the run
/// may not write are refused with the file access errors, and a malformed or huge packet with an
/// error, never a fault.
#[test]
fn refused_paths_and_bad_packets_throw() {
let base = folder("refused");
let outside = folder("refused-outside");
write(&outside.join("x.xmp"), PACKET.as_bytes());
write(&base.join("main/bad.xmp"), b"<x:xmpmeta><rdf:RDF");
write(&base.join("main/ok.xmp"), PACKET.as_bytes());
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!(
"function t(f) {{ try {{ f(); return 'no error'; }} catch (e) {{ return e.name + ': ' + e.message; }} }}\n\
vc.log([t(function () {{ new XMPFile({:?}, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); }}),\n\
t(function () {{ new XMPFile(File('missing.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); }}),\n\
t(function () {{ new XMPFile(File('ok.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); }}),\n\
t(function () {{ new XMPFile(File('bad.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ).getXMP(); }}),\n\
t(function () {{ new XMPFile(File('ok.xmp').fsName, XMPConst.FILE_UNKNOWN, 0x100); }}),\n\
t(function () {{ var u = new XMPFile(Folder.userData.fsName + '/n.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); }})]);",
outside.join("x.xmp").to_string_lossy()
),
);
assert_eq!(
log[0],
json!([
"Error: Script file access denied",
"Error: Script file does not exist",
"Error: Script file access denied",
"Error: XMPFile.getXMP: the XMP packet is not well-formed XMP",
"RangeError: XMPFile: the value 0x100 is not available yet",
"Error: Script file does not exist"
])
);
let _ = std::fs::remove_dir_all(base);
let _ = std::fs::remove_dir_all(outside);
}
/// A sidecar whose write fails is left as it was and is not named in `written`.
#[test]
fn a_failed_write_is_not_listed_as_written() {
let base = folder("unwritten");
let mut s = with_data(&base);
logged(&mut s, &base, &format!("var f = new File(Folder.userData.fsName + '/u.xmp'); f.open('w'); f.write({PACKET:?}); f.close();"));
crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(true));
let r = run_in(
&mut s,
&base,
"var x = new XMPFile(Folder.userData.fsName + '/u.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
try { x.closeFile(); } catch (e) { vc.log(e.message); }",
);
crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(false));
let r = r.unwrap();
assert_eq!(r["log"], json!(["Script file could not be written"]));
assert_eq!(r["written"], json!([]), "a file the run did not change is not listed");
let _ = std::fs::remove_dir_all(base);
}
/// A sidecar that an open `File` has changed and not yet written is not written over: the `File`
/// keeps its changes and writes them when it closes.
#[test]
fn unwritten_file_changes_are_not_written_over() {
let base = folder("pending");
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!(
"var p = Folder.userData.fsName + '/w.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
f.open('e'); f.seek(0, 2); f.write('<!-- kept -->');\n\
function text() {{ var g = new File(p); g.open('r'); var t = g.read(); g.close(); return t; }}\n\
var out = []; try {{ x.closeFile(); }} catch (e) {{ out.push(e.message); }} f.close(); out.push(text().indexOf('kept') > 0);\n\
x.closeFile(); out.push(text().indexOf('changed') > 0); vc.log(out);"
),
);
assert_eq!(log[0], json!(["Script file could not be written", true, true]), "the File's changes are written, then the packet");
let _ = std::fs::remove_dir_all(base);
}
/// A file with the name of the temporary file is left alone: the packet goes through another name
/// and replaces only the sidecar.
#[test]
fn a_file_in_the_temporary_name_is_left_alone() {
let base = folder("taken");
let mut s = with_data(&base);
let path = logged(
&mut s,
&base,
&format!("var f = new File(Folder.userData.fsName + '/t.xmp'); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(f.fsName);"),
);
let path = PathBuf::from(path[0].as_str().unwrap());
let taken = path.with_file_name(format!(".t.xmp.{}.0.tmp", std::process::id()));
write(&taken, b"someone else's");
let log = logged(
&mut s,
&base,
"var x = new XMPFile(Folder.userData.fsName + '/t.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile(); vc.log('closed');",
);
assert_eq!(log, json!(["closed"]));
assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's");
assert!(std::fs::read_to_string(&path).unwrap().contains("changed"));
let names: Vec<String> =
std::fs::read_dir(path.parent().unwrap()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
assert_eq!(names.iter().filter(|n| n.ends_with(".tmp")).count(), 1, "no temporary file is left behind: {names:?}");
let _ = std::fs::remove_dir_all(base);
}
/// Pumps the run until it waits for a file dialog (`None`) or ends.
fn pump_to_picker(s: &mut Session) -> Option<Result<Value>> {
for _ in 0..10_000 {
if s.script_picker().is_some() {
return None;
}
if let Some(r) = s.script_pump() {
return Some(r);
}
}
panic!("the run neither ended nor waited");
}
/// Starts `main/main.jsx` in `base` with the XMP library loaded and the text `text`, in the app.
fn start_framed(s: &mut Session, base: &Path, text: &str) {
s.script_frames = true;
let main = base.join("main/main.jsx");
write(&main, format!("{LOAD}{text}").as_bytes());
assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true);
}
/// With only the sidecar and the first temporary name granted, a taken first name does not make
/// the packet go to another name outside the grants: `closeFile()` throws and no file is made.
#[test]
fn temporary_names_outside_the_grants_are_not_made() {
let base = folder("tempgrant");
let (sidecar, taken) = (base.join("picked/t.xmp"), base.join(format!("picked/.t.xmp.{}.0.tmp", std::process::id())));
write(&sidecar, PACKET.as_bytes());
write(&taken, b"someone else's");
let mut s = with_data(&base);
start_framed(
&mut s,
&base,
"var a = File.saveDialog('a'), b = File.saveDialog('b');\n\
var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
try { x.closeFile(); vc.log('closed'); } catch (e) { vc.log(e.message); }",
);
for path in [&sidecar, &taken] {
assert!(pump_to_picker(&mut s).is_none());
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![path.to_string_lossy().into_owned()], always: false }));
}
let r = pump_to_picker(&mut s).unwrap().unwrap();
assert_eq!(r["log"], json!(["Script file could not be written"]));
assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET);
assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's");
let names: Vec<String> = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
assert_eq!(names.len(), 2, "no other file is made: {names:?}");
let _ = std::fs::remove_dir_all(base);
}
/// A `.xmp` link to another kind of file is scanned and takes no packet, and a link that leads to
/// another kind of file by the time of `closeFile()` is not written through.
#[cfg(unix)]
#[test]
fn a_link_to_another_kind_of_file_is_not_written() {
let base = folder("link");
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!(
"var d = Folder.userData.fsName, l = d + '/l.xmp';\n\
function put(n) {{ var f = new File(d + '/' + n); f.open('w'); f.write({PACKET:?}); f.close(); }}\n\
function link(n) {{ var f = new File(l); if (f.exists) f.remove(); return !!new File(l).createAlias(d + '/' + n); }}\n\
put('other.txt'); put('real.xmp'); var out = [link('other.txt')];\n\
var a = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); out.push(a.canPutXMP(a.getXMP())); a.closeFile();\n\
out.push(link('real.xmp'));\n\
var x = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\
m.setProperty(XMPConst.NS_DC, 'format', 'changed'); out.push(x.canPutXMP(m)); x.putXMP(m);\n\
out.push(link('other.txt'));\n\
try {{ x.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message); }}\n\
vc.log(out); vc.log(d);"
),
);
assert_eq!(log[0], json!([true, false, true, true, true, "Script file access denied"]));
let d = PathBuf::from(log[1].as_str().unwrap());
assert_eq!(std::fs::read_to_string(d.join("other.txt")).unwrap(), PACKET);
assert_eq!(std::fs::read_to_string(d.join("real.xmp")).unwrap(), PACKET);
let _ = std::fs::remove_dir_all(base);
}
/// A sidecar replaced through a temporary file keeps its permission bits.
#[cfg(unix)]
#[test]
fn a_replaced_sidecar_keeps_its_permissions() {
use std::os::unix::fs::PermissionsExt;
let base = folder("mode");
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"),
);
let path = PathBuf::from(log[0].as_str().unwrap());
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
logged(
&mut s,
&base,
"var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();",
);
assert!(std::fs::read_to_string(&path).unwrap().contains("changed"));
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let _ = std::fs::remove_dir_all(base);
}
/// A sidecar in UTF-16 is read by its byte order mark, and one that is not text is refused.
#[test]
fn a_utf16_sidecar_reads_by_its_byte_order_mark() {
let base = folder("utf16");
let mut le = vec![0xFF, 0xFE];
le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes));
write(&base.join("main/le.xmp"), &le);
write(&base.join("main/bad.xmp"), &[0xFF, 0xFE, 0x00]);
let mut s = Session::new();
let log = logged(
&mut s,
&base,
"var x = new XMPFile(File('le.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ);\n\
var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, x.getPacketInfo().charForm];\n\
try { new XMPFile(File('bad.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); } catch (e) { out.push(e.message); } vc.log(out);",
);
assert_eq!(log[0], json!(["image/svg+xml", 3, "Script file cannot be decoded"]));
let _ = std::fs::remove_dir_all(base);
}
/// A `File` open on a UTF-16 sidecar reads the UTF-8 packet `closeFile()` wrote, from the start.
#[test]
fn an_open_utf16_file_reads_the_written_packet() {
let base = folder("utf16open");
let mut s = with_data(&base);
let d = logged(&mut s, &base, "vc.log(Folder.userData.fsName);");
let d = PathBuf::from(d[0].as_str().unwrap());
let mut le = vec![0xFF, 0xFE];
le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes));
write(&d.join("u.xmp"), &le);
let log = logged(
&mut s,
&base,
"var p = Folder.userData.fsName + '/u.xmp'; var f = new File(p); f.open('r'); var out = [f.encoding, f.read(5)];\n\
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\
m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\
var t = f.read(), e = f.encoding; f.close(); out.push(e, t.slice(0, 9), t.indexOf('<dc:format>changed</dc:format>') > 0); vc.log(out);",
);
assert_eq!(log[0], json!(["UTF-16LE", "<?xpa", "UTF-8", "<?xpacket", true]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn writing_a_utf16_declared_packet_keeps_its_body_in_utf8() {
let base = folder("utf16declaredwrite");
let mut session = with_data(&base);
let data = logged(&mut session, &base, "vc.log(Folder.userData.fsName);");
let data = PathBuf::from(data[0].as_str().unwrap());
let body = format!("<!-- retained prolog -->\n{PACKET}\n<!-- retained epilog -->");
let packet = format!("<?xml version='1.0' encoding='UTF-16'?>{body}");
let mut bytes = vec![0xFF, 0xFE];
bytes.extend(packet.encode_utf16().flat_map(u16::to_le_bytes));
write(&data.join("declared.xmp"), &bytes);
logged(
&mut session,
&base,
"var x = new XMPFile(Folder.userData.fsName + '/declared.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var packet = x.getPacketInfo().packet; x.putXMP(packet); x.closeFile();",
);
let written = std::fs::read_to_string(data.join("declared.xmp")).unwrap();
assert_eq!(written, body);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn an_xmp_update_resets_bom_readers_and_keeps_unmarked_reader_positions() {
for bom in [true, false] {
let base = folder(if bom { "utf8bomopen" } else { "utf8open" });
let mut session = with_data(&base);
let data = logged(&mut session, &base, "vc.log(Folder.userData.fsName);");
let data = PathBuf::from(data[0].as_str().unwrap());
let mut bytes = if bom { vec![0xEF, 0xBB, 0xBF] } else { Vec::new() };
bytes.extend_from_slice(PACKET.as_bytes());
write(&data.join("u.xmp"), &bytes);
let log = logged(
&mut session,
&base,
&format!(
"var p = Folder.userData.fsName + '/u.xmp', f = new File(p); f.open('r');\n\
if (!{bom}) f.read(3); var before = f.tell();\n\
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE), m = x.getXMP();\n\
m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\
var after = f.tell(), text = f.read(); f.close(); vc.log([before, after, text.slice(0, 9)]);"
),
);
assert_eq!(log[0], if bom { json!([3, 0, "<?xpacket"]) } else { json!([3, 3, "packet be"]) });
let _ = std::fs::remove_dir_all(base);
}
}
/// Opens that cannot take a packet need no write grant, even with `OPEN_FOR_UPDATE`: a scanned
/// sidecar and another kind of file in the script's own folder open read only.
#[test]
fn read_only_opens_need_no_write_grant() {
let base = folder("readonly");
write(&base.join("main/ok.xmp"), PACKET.as_bytes());
write(&base.join("main/art.txt"), PACKET.as_bytes());
let mut s = Session::new();
let log = logged(
&mut s,
&base,
"var u = XMPConst.OPEN_FOR_UPDATE, out = [];\n\
[[File('ok.xmp').fsName, u | XMPConst.OPEN_USE_PACKET_SCANNING], [File('art.txt').fsName, u]].forEach(function (a) {\n\
var x = new XMPFile(a[0], XMPConst.FILE_UNKNOWN, a[1]); var m = x.getXMP();\n\
out.push(m.getProperty(XMPConst.NS_DC, 'format').value, x.canPutXMP(m)); x.closeFile();\n\
}); vc.log(out);",
);
assert_eq!(log[0], json!(["image/svg+xml", false, "image/svg+xml", false]));
let _ = std::fs::remove_dir_all(base);
}
/// A sidecar larger than a script may read is refused before it is read.
#[test]
fn a_huge_sidecar_is_refused_before_it_is_read() {
let base = folder("huge");
let file = std::fs::File::create(base.join("main/big.xmp")).unwrap();
file.set_len(9 << 20).unwrap();
drop(file);
let mut s = Session::new();
let log = logged(
&mut s,
&base,
"try { new XMPFile(File('big.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); vc.log('read'); } catch (e) { vc.log(e.message); }",
);
assert_eq!(log, json!(["Script file exceeds 8 MiB"]));
let _ = std::fs::remove_dir_all(base);
}
/// The file named `name` in `dir` or a folder inside it.
fn find_file(dir: &Path, name: &str) -> Option<PathBuf> {
for entry in std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok()) {
let path = entry.path();
if path.is_dir() {
if let Some(found) = find_file(&path, name) {
return Some(found);
}
} else if entry.file_name() == name {
return Some(path);
}
}
None
}
/// A write that fails leaves the sidecar as it was and the `XMPFile` open with its packet, so a
/// later `closeFile` of the same object writes it.
#[test]
fn a_failed_write_keeps_the_packet_for_a_later_close() {
let base = folder("fails");
let mut s = with_data(&base);
crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(true));
start_framed(
&mut s,
&base,
&format!(
"var p = Folder.userData.fsName + '/k.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = kept.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(m);\n\
var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\
File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out); vc.log(p);"
),
);
let paused = pump_to_picker(&mut s);
crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(false));
assert!(paused.is_none(), "the run waits at the dialog: {paused:?}");
let path = find_file(&base.join("settings"), "k.xmp").unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), PACKET, "the failed write leaves the file as it was");
assert!(s.script_pick(crate::script::files::PickAnswer::Deny));
let r = pump_to_picker(&mut s).unwrap().unwrap();
assert_eq!(r["log"][0], json!(["Script file could not be written", "changed", "closed"]));
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"), "the same XMPFile writes on its next close");
let _ = std::fs::remove_dir_all(base);
}
#[cfg(unix)]
#[test]
fn a_directory_flush_failure_keeps_the_written_packet_and_allows_retry() {
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
}
}
let _reset = Reset;
let base = folder("directory-flush");
let mut session = with_data(&base);
let dir = logged(&mut session, &base, "vc.log(Folder.userData.fsName);");
let path = PathBuf::from(dir[0].as_str().unwrap()).join("packet.xmp");
write(&path, format!("\u{FEFF}{PACKET}").as_bytes());
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
start_framed(
&mut session,
&base,
&format!(
"Folder.userData; var p = {:?}, reader = new File(p); reader.open('r'); reader.read(7);\n\
var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var meta = kept.getXMP(); meta.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(meta);\n\
var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\
out.push(reader.tell() === 0, reader.read().indexOf('changed') >= 0); reader.close();\n\
File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out);",
path.to_string_lossy()
),
);
let paused = pump_to_picker(&mut session);
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
assert!(paused.is_none(), "the run waits before retrying: {paused:?}");
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"), "the replacement already wrote the packet");
assert!(session.script_pick(crate::script::files::PickAnswer::Deny));
let report = pump_to_picker(&mut session).unwrap().unwrap();
assert_eq!(report["log"][0], json!(["Script file could not be written", "changed", true, true, "closed"]));
assert_eq!(report["written"], json!([path.to_string_lossy()]), "the written replacement is reported once");
}
/// An `XMPFile` from an earlier run of a named engine is closed.
#[test]
fn an_xmp_file_from_an_earlier_run_is_closed() {
let base = folder("earlier");
let mut s = with_data(&base);
let engine = |text: &str| format!("#targetengine xmp\n{LOAD}{text}");
let main = base.join("main/main.jsx");
write(&main, engine(&format!("var f = new File(Folder.userData.fsName + '/k2.xmp'); f.open('w'); f.write({PACKET:?}); f.close();")).as_bytes());
s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
write(
&main,
engine("$.global.kept = new XMPFile(Folder.userData.fsName + '/k2.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);").as_bytes(),
);
s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
write(&main, engine("try { kept.getXMP(); vc.log('open'); } catch (e) { vc.log(e.message); }").as_bytes());
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
assert_eq!(r["log"], json!(["XMPFile.getXMP: the file is closed"]), "an XMPFile from an earlier run is closed");
let _ = std::fs::remove_dir_all(base);
}
/// The temporary file a sidecar is replaced through is readable by its owner alone while the
/// packet is written to it, and the sidecar keeps its own permission bits.
#[cfg(unix)]
#[test]
fn a_temporary_file_starts_private() {
use std::os::unix::fs::PermissionsExt;
let base = folder("private");
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"),
);
let path = PathBuf::from(log[0].as_str().unwrap());
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
crate::script::files::XMP_TEMP_MODE.with(|m| m.set(None));
logged(
&mut s,
&base,
"var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();",
);
assert_eq!(crate::script::files::XMP_TEMP_MODE.with(std::cell::Cell::get).map(|m| m & 0o777), Some(0o600));
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644);
let _ = std::fs::remove_dir_all(base);
}
/// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named
/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.)
#[cfg(target_os = "linux")]
#[test]
fn a_replaced_sidecar_takes_no_inherited_acl() {
let base = folder("acl");
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"),
);
let path = PathBuf::from(log[0].as_str().unwrap());
let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status();
if !set.is_ok_and(|s| s.success()) {
let _ = std::fs::remove_dir_all(base);
return;
}
logged(
&mut s,
&base,
"var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();",
);
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"));
let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap();
let acl = String::from_utf8_lossy(&acl.stdout);
assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}");
let _ = std::fs::remove_dir_all(base);
}
/// A packet argument whose conversion closes the `XMPFile` leaves it closed: `canPutXMP` and
/// `putXMP` throw that the file is closed, and nothing is written.
#[test]
fn converting_the_packet_cannot_close_the_file() {
let base = folder("reentrant");
let mut s = with_data(&base);
let log = logged(
&mut s,
&base,
&format!(
"var p = Folder.userData.fsName + '/r.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
function closing(x) {{ var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); var s = m.serialize();\n\
return {{ toString: function () {{ x.closeFile(); return s; }} }}; }}\n\
var out = [], a = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
try {{ out.push(a.canPutXMP(closing(a))); }} catch (e) {{ out.push(e.message); }}\n\
var b = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
try {{ b.putXMP(closing(b)); out.push('put'); }} catch (e) {{ out.push(e.message); }}\n\
b.closeFile(); vc.log(out); vc.log(p);"
),
);
assert_eq!(log[0], json!(["XMPFile.canPutXMP: the file is closed", "XMPFile.putXMP: the file is closed"]));
assert_eq!(std::fs::read_to_string(log[1].as_str().unwrap()).unwrap(), PACKET);
let _ = std::fs::remove_dir_all(base);
}
/// With `CLOSE_UPDATE_SAFELY`, a sidecar whose folder takes no temporary file is left as it is and
/// the `XMPFile` keeps its packet; a later `closeFile()` without the flag writes the file itself.
#[test]
fn a_safe_close_writes_only_through_a_temporary_file() {
let base = folder("safely");
let sidecar = base.join("picked/s.xmp");
write(&sidecar, PACKET.as_bytes());
let mut s = with_data(&base);
start_framed(
&mut s,
&base,
"var a = File.saveDialog('a');\n\
var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
var out = []; try { x.closeFile(XMPConst.CLOSE_UPDATE_SAFELY); out.push('closed'); } catch (e) { out.push(e.message, x.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }\n\
File.saveDialog('pause'); x.closeFile(); out.push('written'); vc.log(out);",
);
assert!(pump_to_picker(&mut s).is_none());
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![sidecar.to_string_lossy().into_owned()], always: false }));
assert!(pump_to_picker(&mut s).is_none());
assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET, "the safe close leaves the file as it was");
assert!(s.script_pick(crate::script::files::PickAnswer::Deny));
let r = pump_to_picker(&mut s).unwrap().unwrap();
assert_eq!(r["log"], json!([["Script file could not be written", "changed", "written"]]));
assert!(std::fs::read_to_string(&sidecar).unwrap().contains("<dc:format>changed</dc:format>"));
let names: Vec<String> = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
assert_eq!(names, ["s.xmp"], "no other file is made");
let _ = std::fs::remove_dir_all(base);
}
@@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
];
/// The names the host adds that stay inside the document and the run, by the object that has them.
@@ -50,6 +51,8 @@ const INSIDE: &[(&str, &str)] = &[
("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="),
("localize.", "length"),
("toSource.", "length"),
("ExternalObject.", "length prototype search"),
("ExternalObject.prototype.", "constructor terminate"),
(
"$.",
"about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \
+5 -3
View File
@@ -347,9 +347,10 @@ fn temp_path(target: &Path) -> io::Result<PathBuf> {
/// mode bits mean other people when the group differs, and an ACL can narrow who reads the file.
/// When the group or the ACL can't be kept, the replacement is readable by its owner alone rather
/// than by people the old file didn't let in. (Unix; Windows files have none to keep beyond
/// read-only, which makes the save fail as writing in place would.)
/// read-only, which makes the save fail as writing in place would.) `tmp` is the file that is about
/// to replace `target`.
#[cfg(unix)]
fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> {
pub fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
// A new file: the default permissions.
let Ok(m) = std::fs::metadata(target) else { return Ok(()) };
@@ -385,8 +386,9 @@ fn keep_acl(_: &Path, _: &Path) -> bool {
true
}
/// Windows files have no permissions to keep beyond read-only (see the Unix version).
#[cfg(not(unix))]
fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> {
pub fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> {
Ok(())
}
+1 -1
View File
@@ -58,7 +58,7 @@ use vectorcraft_doc::{Document, ImageBlob};
#[cfg(all(unix, not(target_arch = "wasm32")))]
pub use atomic::sync_parent;
#[cfg(not(target_arch = "wasm32"))]
pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
use craft_gzip::Gz;
pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode};
use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json};
+2
View File
@@ -11,6 +11,8 @@ workspace = true
[dependencies]
chrono = { workspace = true }
# The XMP packets of XMPMeta and XMPFile (xmp.rs).
craft-xml = { workspace = true }
# Unicode 17.0 general categories for identifiers (chars.rs). 0.1.5 adds the Unicode-3.0 license,
# which is not on the license allowlist, so the version is exact.
unicode-properties = { version = "=0.1.4", default-features = false, features = ["general-category"] }
+49
View File
@@ -135,6 +135,29 @@ fn parse_text(i: &mut Interp, text: Value, platform: bool) -> JsResult<Value> {
host(i, "parse", &[text, current, Value::Bool(platform)])
}
/// The platform path `x` names, as `File(x).fsName` gives it: for `XMPFile`
/// ([`crate::xmp_classes`]).
pub(crate) fn platform_path(i: &mut Interp, x: &Value) -> JsResult<Value> {
let p = parse(i, x)?;
i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))
}
/// Calls the host function `name` with `args`, as `File` and `Folder` call theirs: for `XMPFile`.
pub(crate) fn call_host(i: &mut Interp, name: &str, args: &[Value]) -> JsResult<Value> {
host(i, name, args)
}
/// The field `name` of a record a host function gave ([`field`]): for `XMPFile`.
pub(crate) fn record_field(i: &mut Interp, v: &Value, name: &str) -> JsResult<Value> {
field(i, v, name)
}
/// The count of runs the realm has begun since `File` and `Folder` were added, or `None` without
/// them: an `XMPFile` is open only in the run that opened it.
pub(crate) fn run_count(i: &Interp) -> Option<f64> {
i.files.as_ref().map(|c| c.run)
}
fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult<Value> {
let (_, path) = this_path(i, this, what)?;
let p = parse_text(i, path, true)?;
@@ -1094,6 +1117,7 @@ fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> {
pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> {
let Some(c) = i.files.as_mut() else { return Ok(()) };
c.run += 1.0;
i.heap.reset_xmp_files();
let start = host(i, "current", &[])?;
if let Some(c) = i.files.as_mut() {
c.current = start;
@@ -1101,6 +1125,31 @@ pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> {
Ok(())
}
#[cfg(test)]
mod xmp_run_tests {
use super::*;
use crate::heap::PropMap;
#[test]
fn a_failed_folder_reset_releases_native_xmp_buffers() {
let mut interp = Interp::new(crate::Options::default(), crate::Limits::default());
let host = interp.heap.alloc_object(Object::new(Class::Ordinary, None));
interp.files = Some(Classes { file_proto: host, folder_proto: host, host, current: Value::str("start"), run: 0.0 });
let mut fields = PropMap::default();
fields.insert(key("__vcXmpPacket"), Value::str("packet"));
fields.insert(key("__vcXmpPending"), Value::str("pending"));
fields.insert(key("__vcXmpPath"), Value::str("kept.xmp"));
let file = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None));
let result = interp.rooted(&[Value::Object(file)], reset_current);
assert!(result.is_err(), "the host has no current function");
assert_eq!(run_count(&interp), Some(1.0));
let Class::XmpFile(fields) = &interp.heap.object(file).unwrap().class else { panic!("native file") };
assert!(matches!(fields.get(&key("__vcXmpPacket")), Some(Value::Null)));
assert!(matches!(fields.get(&key("__vcXmpPending")), Some(Value::Undefined)));
assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp"));
}
}
/// Adds `File` and `Folder` to the global object, their work done by the host functions in
/// `items` ([`crate::Realm::define_file_classes`]).
pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> {
+45 -1
View File
@@ -268,6 +268,10 @@ pub(crate) enum Class {
},
/// A `.( )` filter in progress.
XmlFilter(Box<XmlFilterState>),
/// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]).
Xmp(Box<crate::xmp::Meta>),
/// An object the `XMPFile` constructor made ([`crate::xmp_classes`]).
XmpFile(Box<PropMap<Value>>),
/// An object of a class a host defined ([`crate::host_classes`]).
Host(crate::host_classes::HostObj),
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
@@ -339,7 +343,7 @@ impl Class {
Class::XmlList(_) => "XMLList",
Class::Namespace(_) => "Namespace",
Class::QName { .. } => "QName",
Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object",
Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) => "Object",
Class::Promise(_) => "Promise",
Class::Math => "Math",
Class::Json => "JSON",
@@ -538,6 +542,16 @@ impl Heap {
ids.filter_map(|(i, _)| u32::try_from(i).ok().map(ObjId)).collect()
}
pub(crate) fn reset_xmp_files(&mut self) {
for cell in &mut self.cells {
if let Cell::Object(object) = cell
&& let Class::XmpFile(fields) = &mut object.class
{
crate::xmp_classes::reset_file_state(fields);
}
}
}
/// Live cells, for tests.
#[cfg(test)]
pub(crate) fn live_cells(&self) -> usize {
@@ -811,6 +825,14 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
work.extend(state.input.iter().chain(&state.kept).map(|o| o.0));
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
}
Class::Xmp(meta) => extra = meta.heap_bytes(),
Class::XmpFile(fields) => {
for (name, value) in fields.iter() {
strings.add_key(name);
mark_value(value, work, strings);
}
extra = std::mem::size_of::<PropMap<Value>>() + PROP_BYTES * fields.len();
}
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
Class::Promise(p) => {
for v in p.values() {
@@ -877,6 +899,28 @@ mod tests {
assert_eq!(heap.bytes, OBJECT_BYTES + 2 * PROP_BYTES + string_bytes(1000) + string_bytes(5));
}
#[test]
fn xmp_file_buffers_are_traced_and_released_at_the_file_run_boundary() {
let mut heap = Heap::default();
let pending = heap.alloc_object(Object::new(Class::Ordinary, None));
let mut fields = PropMap::default();
fields.insert(key("__vcXmpPacket"), Value::str(&"p".repeat(8192)));
fields.insert(key("__vcXmpPending"), Value::Object(pending));
fields.insert(key("__vcXmpPath"), Value::str("kept.xmp"));
let file = heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None));
let roots = Roots { objects: vec![file], ..Roots::default() };
heap.collect(&roots);
assert!(heap.object(pending).is_some(), "native values keep their objects reachable");
let before = heap.bytes;
assert!(before >= string_bytes(8192), "native packet strings count toward the heap limit");
heap.reset_xmp_files();
heap.collect(&roots);
assert!(heap.object(pending).is_none(), "the prior run's pending value is released");
assert!(before - heap.bytes >= string_bytes(8192), "the prior run's packet is released");
let Class::XmpFile(fields) = &heap.object(file).unwrap().class else { panic!("native file") };
assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp"));
}
#[test]
fn prop_maps_keep_insertion_order_through_removals_and_growth() {
let mut m = PropMap::default();
+43 -3
View File
@@ -106,6 +106,7 @@ pub enum Arg {
pub(crate) enum ArgRead {
/// Each as [`Data`].
Data,
DataWithin(DataLimits),
/// Each as [`Data`], with the result given frozen, as [`HostItem::Value`] gives its value.
Frozen,
/// Each as the string `String(value)` gives.
@@ -126,6 +127,12 @@ pub enum HostItem {
/// A read-only copy of a value.
Value(Data),
Function(HostFunction),
/// A function whose explicit arguments use `limits`. The realm's other crossings keep their
/// configured limits. The result uses the realm's limits.
FunctionWithLimits {
limits: DataLimits,
function: HostFunction,
},
/// A function whose arguments arrive as strings, each the string `String(value)` gives.
TextFunction(HostFunction),
/// A function whose arguments arrive converted one by one as the list says. Arguments past the
@@ -507,7 +514,10 @@ impl Interp {
/// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first.
fn read_args(&mut self, name: &Rc<str>, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
let mut reading = Reading {
limits: self.data_limits,
limits: match how {
ArgRead::DataWithin(limits) => *limits,
_ => self.data_limits,
},
bytes: 0,
entries: 0,
ancestors: Vec::new(),
@@ -529,14 +539,14 @@ impl Interp {
}
// A conversion can run the script's own `toString`, which may collect garbage.
let mark = self.temp_roots.len();
if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) {
if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Hosted) {
self.temp_roots.extend(args.iter().cloned());
}
let mut read = Ok(());
for (i, a) in args.iter().enumerate() {
reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX)));
let d = match how {
ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading),
ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading),
ArgRead::Text => self.read_text(a, &mut reading),
ArgRead::Each(list) => match list.get(i) {
Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined),
@@ -666,6 +676,9 @@ impl Interp {
},
HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE },
HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Data)), flags: ENUMERABLE },
HostItem::FunctionWithLimits { limits, function } => {
Prop::Data { value: Value::Object(self.host_function(function, &full, ArgRead::DataWithin(limits))), flags: ENUMERABLE }
}
HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Text)), flags: ENUMERABLE },
HostItem::Converted(list, f) => {
Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE }
@@ -720,3 +733,30 @@ fn read_site(data: &[Data]) -> CallSite {
};
CallSite { source: at(0, crate::UNKNOWN_SOURCE), line: at(1, 0), column: at(2, 0) }
}
#[cfg(test)]
mod argument_limit_tests {
use super::*;
#[test]
fn a_binding_argument_budget_does_not_change_other_crossings() {
let mut realm = crate::Realm::with_options(crate::Options::default(), crate::Limits::default());
let function: HostFunction = Rc::new(|_| Ok(Data::Bool(true)));
realm
.define_host_object(
"h",
vec![
("normal".into(), HostItem::Function(function.clone())),
("wide".into(), HostItem::FunctionWithLimits { limits: DataLimits { bytes: 64, ..DataLimits::default() }, function }),
],
)
.unwrap();
realm.set_data_limits(DataLimits { bytes: 16, ..DataLimits::default() });
assert_eq!(realm.run("h.wide('abcdefgh')").unwrap(), crate::JsValue::Bool(true));
assert_eq!(realm.run("try { h.normal('abcdefgh'); false } catch (e) { e instanceof RangeError }").unwrap(), crate::JsValue::Bool(true));
assert_eq!(
realm.run("try { h.wide('abcdefghijklmnopqrstuvwxyz'); false } catch (e) { e instanceof RangeError }").unwrap(),
crate::JsValue::Bool(true)
);
}
}
+6
View File
@@ -308,6 +308,9 @@ pub(crate) struct Interp {
pub(crate) install_error: Option<String>,
/// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]).
pub(crate) files: Option<crate::file_classes::Classes>,
/// `ExternalObject` and the XMP classes it loads, once a host has added them
/// ([`crate::Realm::define_external_object`]).
pub(crate) xmp: Option<crate::xmp_classes::Classes>,
/// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them.
pub(crate) host_classes: Vec<crate::host_classes::Entry>,
/// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`].
@@ -629,6 +632,7 @@ impl Interp {
held_bytes: 0,
install_error: None,
files: None,
xmp: None,
host_classes: Vec::new(),
write_hosted: false,
host_objects: crate::host_classes::Made::default(),
@@ -910,6 +914,7 @@ impl Interp {
roots.objects.push(self.global);
roots.objects.extend(self.intrinsics.all());
roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects));
roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects));
roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects));
roots.values.extend(self.symbols.root_values());
roots.objects.extend(self.symbols.root_objects());
@@ -938,6 +943,7 @@ impl Interp {
.saturating_add(self.held_bytes)
.saturating_add(self.held.now.get())
.saturating_add(self.symbols.registry_bytes())
.saturating_add(self.xmp.as_ref().map_or(0, crate::xmp_classes::Classes::bytes))
.saturating_add(queued);
}
+5
View File
@@ -126,6 +126,8 @@ mod unit_value;
mod value;
mod xml;
mod xml_builtins;
mod xmp;
mod xmp_classes;
mod xpath;
pub use ast::{
@@ -143,6 +145,7 @@ pub use realm::{
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
};
pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind};
pub use xmp::{MAX_BYTES as XMP_MAX_BYTES, PacketSpan, find_packet as find_xmp_packet};
/// How a script is read.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -300,3 +303,5 @@ mod text_tests;
mod unit_value_tests;
#[cfg(test)]
mod xml_tests;
#[cfg(test)]
mod xmp_tests;
+17
View File
@@ -617,6 +617,23 @@ impl Realm {
}
}
/// Adds the global `ExternalObject`. `new ExternalObject("lib:AdobeXMPScript")` defines the
/// globals `XMPMeta`, `XMPFile` and `XMPConst`; any other library name throws. `XMPFile` reads
/// and writes files through the host functions `xmpOpen` and `xmpWrite` of
/// [`Realm::define_file_classes`], which the host adds first; without `File` and `Folder`,
/// `XMPFile` throws. An `XMPFile` is open only in the run that opened it: each
/// [`Realm::reset_folder_current`] begins a new run for it, and [`Realm::run`] and
/// [`Realm::start`] do not. A successful close or a new file run releases its packet buffers.
/// Registered namespace storage counts toward the realm's heap limit.
/// After a successful installation, another call fails with an internal
/// error and preserves `ExternalObject` and registered namespaces. A failed installation can be retried.
pub fn define_external_object(&mut self) -> Result<(), RunError> {
match crate::xmp_classes::install(&mut self.interp) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose
/// prototype holds its members, and the global objects `instances`, each made from the
/// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be
+1436
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+79
View File
@@ -3396,6 +3396,85 @@ VectorCraft writes files by these rules of its own:
`Script file dialogs need a person to answer them`, and takes no kept grant. In the app, a file dialog inside a
built-in's callback, a getter, a conversion or a file `$.evalFile` runs throws an error.
`new ExternalObject("lib:AdobeXMPScript")` defines the globals `XMPMeta`, `XMPFile` and `XMPConst`
([the help page](https://extendscript.docsforadobe.dev/scripting-xmp/xmpscript-object-reference/)); any other library
name throws `ExternalObject: the library … is not available`, and no native library is loaded. VectorCraft's own
rules for these objects:
- `XMPMeta` reads a packet given as a string (`new XMPMeta(packet)`) and writes one with `serialize(options?)`, with
the packet wrapper unless `XMPConst.SERIALIZE_OMIT_PACKET_WRAPPER` is given. It has `getProperty`, `setProperty`,
`deleteProperty`, `doesPropertyExist`, `countArrayItems`, `getArrayItem`, `appendArrayItem`, `insertArrayItem`,
`setArrayItem`, `deleteArrayItem`, `doesArrayItemExist`, `getLocalizedText` and `setLocalizedText`, and the
functions `XMPMeta.registerNamespace`, `getNamespacePrefix` and `getNamespaceURI`. A path is a property name,
`prefix:name`, or either with `[n]` (from 1) or `[last()]` for an array item. `insertArrayItem` with
`XMPConst.ARRAY_LAST_ITEM` inserts before the last existing item and rejects an empty array. `insertArrayItem`
and `setArrayItem` store `null` as an empty item value. Arrays hold simple items; a structure
or a value with qualifiers that a packet holds is kept as it was written, and `getProperty` gives its options. An
array item with an `xml:lang` qualifier has the qualifier and language options in `getProperty` and `getArrayItem`.
`getLocalizedText` returns an `XMPProperty` with the selected text, locale and options; its `namespace` and `path` are empty strings.
VectorCraft returns `undefined` when the property is absent or its language alternative array is empty.
`appendArrayItem` keeps explicit item options, value and array options in their parameter slots, including `undefined` or `null` item options.
A string value can use the shorter call form; a null value with numeric array options can also use that form. A
value with qualifiers in the `rdf:value` form also gives the text of its `rdf:value`, and an empty property element
whose attributes are fields is a structure. The namespaces that a packet's property, element and attribute names use are registered with the prefix the packet
gives them, or `prefix_1_` when that prefix names another namespace; a namespace the packet declares but no name
uses is not registered. At most 4,096 namespaces, holding at most 1 MiB together, are registered. A namespace URI
over 1,024 bytes, a prefix over 128 bytes, and a namespace past either limit throw `… the XMP data is too large`,
both from `registerNamespace` and from a packet that uses the namespace. The prefix limit applies to a namespace
being registered, with any `_n_` suffix added to its prefix; a namespace already registered keeps its prefix, and
`registerNamespace` returns that prefix whatever prefix it is given. An `rdf:Alt` item with `xml:lang=""` has no
language, so its array is not a language alternative for `getLocalizedText` and `setLocalizedText`.
- `XMPFile(path, format, openFlags)` reads a file through the same places as `File`, so a path outside them, a
missing file and a file over 8 MiB throw the `File` messages (`Script file access denied`, `Script file does not
exist`, `Script file exceeds 8 MiB`). A `.xmp` file is read whole as its packet (a link counts by the file it leads to,
when it is opened and again when it is written); any other file, and any file with
`XMPConst.OPEN_USE_PACKET_SCANNING`, is scanned for its first UTF-8 packet and is read only. A packet starts at a
`<?xpacket begin=` whose header holds `id="W5M0MpCehiHzreSzNTczkc9d"` within 256 bytes; inside a packet, a start
or a trailer in a CDATA section or a comment is text, except that a section that does not close, or that holds a
trailer and then a start, is read as text around them. Only a `.xmp` file
opened with `XMPConst.OPEN_FOR_UPDATE`, without packet scanning, takes `putXMP`, and opening one that way where
the script may not write throws `Script file access denied`; other files open read only with that flag.
After `putXMP`, `closeFile()` writes the packet in
UTF-8 through a temporary file in the same folder when the script may write there, otherwise straight to the file;
when no temporary name is free, nothing is written. The written packet omits a leading XML declaration and retains
the following packet bytes. On Unix the replacement keeps the file's permission bits, group
and (on Linux) access ACL, as a saved document does, and is readable by its owner alone where the group or the ACL
cannot be kept; on a volume that refuses Unix permissions (SMB, FAT) the update still goes through. The packet is flushed to the disk before the temporary file takes the file's
name. With `XMPConst.CLOSE_UPDATE_SAFELY`, `closeFile()` writes only
through a temporary file, and where the script may not make one it throws `Script file could not be written` and
leaves the file as it is. A failed write throws and keeps the file open with its packet. While an open `File` of the same file holds changes it has not written, `closeFile()` throws
`Script file could not be written` and the `File` keeps its changes. `getXMP`, `getPacketInfo`, `getFileInfo` and `canPutXMP` are available. An `XMPFile` is open only in the
run that opened it. Its file state is native, and assigning script properties does not change that state.
A successful close or the next script file run releases its packet buffers.
After a successful update, an open `File` reader with a UTF-8 byte order mark or UTF-16 encoding
restarts in UTF-8 at the beginning of the replacement packet. A UTF-8 reader without a byte order mark keeps its position,
limited to the replacement packet's length.
- On Unix, `closeFile()` flushes the destination folder after writing the packet. If that flush fails,
it throws `Script file could not be written`, and the file already contains the replacement packet.
Open readers use that packet, `written` names the file, and the `XMPFile` keeps its pending packet for retry.
- Registered namespace storage and expanded XML values count toward the script's heap limit.
`canPutXMP` checks string packets without retaining their expanded XML values.
Pending packets count once toward that limit. Library installation checks its members before
publishing `ExternalObject`, in both ES5 and ES2015 realms. Serialization consumes fuel even
when its escaped output exceeds the packet limit. Packet-info scans and metadata size accounting during edits also consume fuel.
The sidecar-write host binding accepts packets up to VectorCraft's 8 MiB packet limit.
- A packet over 8 MiB, one that is not well-formed XML, one with a document type declaration or an undefined entity,
one with text beside its `rdf:Description` elements or their properties, and one nested more than 64 elements deep
throws. Only spaces, tabs, carriage returns and line feeds count as indentation. A qualified name's prefix
and local name must each be valid XML names without a colon. Explicit `rdf:about` values must agree, including empty values.
A nonempty `xml:lang` on an `rdf:Description` or inherited from its ancestors is not available yet and throws instead of discarding the language.
An empty `xml:lang` on that description clears an inherited language. Explicit property-level language qualifiers are retained.
A value is counted as deep as `serialize()` would write it, under `x:xmpmeta`, `rdf:RDF` and
`rdf:Description`. A packet that would be written with more than 1,024 attributes on one element, or more than
1,024 namespace declarations in scope at one element, throws
`… the XMP data is too large`, both from `serialize()` and when a packet with such a value is read. Members of the help page that are not built yet (iterators,
structure fields, qualifiers, aliases, sorting, byte-array packets and `XMPFile.getFormatInfo`) throw
`… is not available yet`, and so does a flag, format or path form that is not handled yet.
```json
{"name":"run_command","arguments":{"command":"script.run","params":{"source":"new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta(); m.setProperty(XMPConst.NS_DC, 'format', 'image/svg+xml'); vc.log(m.serialize());"}}}
```
`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file, error?}`, with `code`
the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's
grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later
+9
View File
@@ -36,6 +36,10 @@ Native saves on Unix flush the destination directory after writing or replacing
When startup scripts precede a chosen script, its source must compile before startup scripts run. Invalid chosen source is rejected before startup scripts execute in synchronous and sliced sessions, and a compilation failure clears the previous script report. The chosen script runs the source read before startup scripts, including when a startup script removes its installed file. Included files are read again when the chosen run starts. Each app queue pump processes at most one startup entry and preserves the remaining order after a failure. `crates/engine/tests/script_startup.rs` covers both modes.
XMP array insertion with `XMPConst.ARRAY_LAST_ITEM` precedes the last existing item and rejects an empty array. Array insertion and replacement store `null` as an empty item value. `crates/js/src/xmp_tests.rs` covers ordering, empty arrays, and null values.
XMP parsing rejects invalid qualified names, text other than XML whitespace beside descriptions or properties, and conflicting explicit `rdf:about` values, including empty values. Packet scanning skips other processing instructions inside a packet. Packet padding requires a real wrapper trailer and allows leading XML declarations, comments, and processing instructions. Array appends charge their added bytes without scanning existing items, and indexed property reads copy only the selected value. Pending packets count once toward the heap limit. ES5 and ES2015 library installation checks every published member against that limit. Failed serialization and packet-info scans consume fuel. Sidecar writes allow packets up to VectorCraft's 8 MiB packet limit through the host binding.
`vectorcraft-js` ends a paused or waiting run before `Realm::run` or `Realm::start` compiles new source. Its globals remain available. The earlier run's remaining code and queued jobs do not run. Regressions in `crates/js/src/host_tests.rs` cover paused scripts, Promise reactions, waiting host calls, invalid replacement source, and deferred language settings.
Scripts: `Promise.prototype[Symbol.toStringTag]` is `"Promise"` when Symbols are available, with a configurable, non-enumerable, non-writable descriptor. Promise instances report `[object Promise]` in engines without Symbols. Test: `promise_prototype_has_a_configurable_string_tag` in `crates/js/src/promise_tests.rs`.
@@ -91,6 +95,10 @@ The shared assessment status line and revision history are current upstream; thi
Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard option for ordinary resizing. Fit to Artwork Bounds and Fit to Selected Art explicitly leave artwork stationary. Dialog regression coverage checks preset/orientation/typed-size intent with scaling on and off, draft cancellation, one-step Undo/Redo, and fitting while Move Artwork and Scale Artwork are enabled. This is a narrow follow-up to #3277; no parity score or estimate is reassessed.
`XMPFile` updates restart open `File` readers with a UTF-8 byte order mark or UTF-16 encoding at the beginning of the new UTF-8 packet. Unmarked UTF-8 readers keep their position, limited to the new packet's length. Written packets omit a leading XML declaration and retain the following packet bytes. Nonempty language inherited by an `rdf:Description` is rejected as unavailable; explicit property-level language qualifiers are retained. Native file state is separate from script properties, and a successful close or the next script file run releases its packet buffers. Registered namespaces and expanded XML values count toward the script's heap limit. String-packet validation does not retain expanded XML values. On Unix, a folder flush failure after writing reports the written replacement and refreshes open readers while keeping the pending packet for retry. A failed `Realm::define_external_object` call can be retried; a call after a successful installation returns an internal error and preserves registered namespaces.
`XMPMeta.getLocalizedText` returns the selected `XMPProperty`, including its locale and option flags. VectorCraft returns `undefined` for an absent property or empty language alternative. `appendArrayItem` preserves explicit optional argument positions.
### Feature revisions
| Date | Change | Summary |
@@ -1092,6 +1100,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes, and a script or path outside the automation read roots in force when Preferences opens shows by its file name, as `script.grants` lists it, and Revoke still removes it; a grants file that `script.grants` cannot read shows that error in the section when Preferences opens, a grants file that is not well formed or is over 4 MiB makes Revoke show its error, and the file is left as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`).
- Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files as the links led at the run's first `vc.run` and as the person last opened or saved each document; a link does not let them write the file it names, and they write a linked file only where the previous line lets them write (the script's own write places and the open documents' own files); a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`.
- Scripts: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `crates/engine/src/tests/script_io.rs`.
- Scripts: `new ExternalObject("lib:AdobeXMPScript")` gives `XMPMeta`, `XMPFile` and `XMPConst` ([the help page](https://extendscript.docsforadobe.dev/scripting-xmp/xmpscript-object-reference/)): properties, arrays, language alternatives and namespaces read from a packet, changed and serialized, and a `.xmp` sidecar read and written with `getXMP`, `putXMP` and `closeFile`. VectorCraft's own rules: `XMPFile` reads and writes only where `File` may; other files are scanned for their packet and read only; a packet over 8 MiB or not well-formed throws; members not built yet (iterators, structure fields, qualifiers, aliases) throw that they are not available yet. `crates/js/src/xmp_tests.rs`, `crates/engine/src/tests/script_xmp.rs`.
- Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`).
- Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`.
- Startup scripts: with Preferences › General › Run Startup Scripts on, the `.jsx` files of the `Startup Scripts` folder next to the preferences run when VectorCraft starts and before each script chosen from File › Scripts ([the scripting guide](https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf), page 11). VectorCraft's own rules: the preference is off by default; only the folder's own `.jsx` files run, sorted by name without regard to case, each with the limits of any script and its own undo step; one that fails is named in the Script Console and the next one runs, then the chosen script; nothing runs in Safe Mode, the launch marker names the running startup script so a launch that stops there offers to disable it, and a startup script cannot start another round. `script.startup.run` runs the folder. `crates/engine/tests/script_startup.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`, `crates/ui-egui/tests/safe_mode.rs`.