From 8cc1bc85307c91d94d5ffcc76f8c90fd03fd0755 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:01:07 -0800 Subject: [PATCH 01/21] Scripts: ExternalObject loads the XMP objects XMPMeta, XMPFile and XMPConst new ExternalObject("lib:AdobeXMPScript") defines XMPMeta, XMPFile and XMPConst in the script engine; any other library name throws and no native library is loaded. - XMPMeta reads a packet string and serializes one, with or without the packet wrapper: simple properties, arrays of simple items, language alternatives and namespace registration and lookup. Structures and values with qualifiers are kept as they were written. - XMPFile reads and writes only where File may. A .xmp sidecar opened for update takes putXMP, and closeFile writes it through a temporary file in the same folder when the script may write there; other files are scanned for their packet and are read only. File's 8 MiB limit applies before reading. - Packets are parsed with craft-xml: a document type declaration, an undefined entity, nesting over 64 levels and a packet over 8 MiB are refused with an error. - Members not built yet (iterators, structure fields, qualifiers, aliases, sorting, byte-array packets, XMPFile.getFormatInfo) throw that they are not available yet. The XMPConst flag values follow the public XMP Toolkit SDK header XMP_Const.h. Tests: crates/js/src/xmp_tests.rs, with fuzz cases for the packet parser and scanner, and crates/engine/src/tests/script_xmp.rs. Docs: docs/mcp.md and docs/target-app-parity.md. --- Cargo.lock | 1 + crates/engine/src/script/files.rs | 169 +++- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_xmp.rs | 479 ++++++++++ crates/js/Cargo.toml | 2 + crates/js/src/file_classes.rs | 23 + crates/js/src/heap.rs | 5 +- crates/js/src/interp.rs | 5 + crates/js/src/lib.rs | 5 + crates/js/src/realm.rs | 12 + crates/js/src/xmp.rs | 762 +++++++++++++++ crates/js/src/xmp_classes.rs | 1224 +++++++++++++++++++++++++ crates/js/src/xmp_tests.rs | 322 +++++++ crates/ui-egui/src/i18n/ca.tsv | 15 + crates/ui-egui/src/i18n/cs.tsv | 15 + crates/ui-egui/src/i18n/da.tsv | 15 + crates/ui-egui/src/i18n/de.tsv | 15 + crates/ui-egui/src/i18n/el.tsv | 15 + crates/ui-egui/src/i18n/es.tsv | 15 + crates/ui-egui/src/i18n/fi.tsv | 15 + crates/ui-egui/src/i18n/fr.tsv | 15 + crates/ui-egui/src/i18n/hi.tsv | 15 + crates/ui-egui/src/i18n/hu.tsv | 15 + crates/ui-egui/src/i18n/id.tsv | 15 + crates/ui-egui/src/i18n/it.tsv | 15 + crates/ui-egui/src/i18n/ja.tsv | 15 + crates/ui-egui/src/i18n/ka.tsv | 15 + crates/ui-egui/src/i18n/ko.tsv | 15 + crates/ui-egui/src/i18n/nl.tsv | 15 + crates/ui-egui/src/i18n/pl.tsv | 15 + crates/ui-egui/src/i18n/pt-br.tsv | 15 + crates/ui-egui/src/i18n/ru.tsv | 15 + crates/ui-egui/src/i18n/sv.tsv | 15 + crates/ui-egui/src/i18n/tr.tsv | 15 + crates/ui-egui/src/i18n/uk.tsv | 15 + crates/ui-egui/src/i18n/vi.tsv | 15 + crates/ui-egui/src/i18n/zh-hans.tsv | 15 + crates/ui-egui/src/i18n/zh-hant.tsv | 15 + docs/mcp.md | 36 + docs/target-app-parity.md | 1 + 40 files changed, 3420 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/tests/script_xmp.rs create mode 100644 crates/js/src/xmp.rs create mode 100644 crates/js/src/xmp_classes.rs create mode 100644 crates/js/src/xmp_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 6a602ed891..69d5e6b6d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7031,6 +7031,7 @@ name = "vectorcraft-js" version = "0.24.1" dependencies = [ "chrono", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "getrandom 0.4.3", "proptest", "unicode-properties", diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 94ef3bdf9e..d22db3dc6a 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1850,6 +1850,168 @@ fn copy(host: &Host, a: &[Data]) -> Result { 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::>().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 { + 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))), + ])) +} + +/// `xmpWrite(path, packet)`: 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. Open objects of the +/// file hold the new bytes. +fn xmp_write(host: &Host, a: &[Data]) -> Result { + let path = arg_text(a, 0); + let packet = arg_text(a, 1).into_bytes(); + 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 holders = disk.open.values().filter(|o| o.holds(&target)).count(); + disk.charge_write(packet.len().saturating_mul(holders.saturating_add(1)))?; + 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); + // `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| allowed(t).then(|| std::fs::OpenOptions::new().write(true).create_new(true).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")); + } + std::io::Write::write_all(&mut out, &packet) + }; + let r = write_temp(); + drop(out); + 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)) { + file.bytes.clone_from(&packet); + // The packet is UTF-8 without a byte order mark, so an object reading UTF-16 reads it as + // UTF-8 from the start. + if matches!(file.encoding, Encoding::Utf16Le | Encoding::Utf16Be) { + file.encoding = Encoding::Utf8; + file.name = Encoding::Utf8.name().to_string(); + file.pos = 0; + } + file.pos = file.pos.min(packet.len()); + file.dirty = false; + } + } + 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 { let mut disk = host.disk.borrow_mut(); @@ -2455,8 +2617,11 @@ 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(), call(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 @@ -2476,6 +2641,8 @@ thread_local! { pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell> = 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 = 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 = const { std::cell::Cell::new(false) }; } #[cfg(test)] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..48cca170c6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -177,6 +177,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_xmp; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs new file mode 100644 index 0000000000..a89efbc14f --- /dev/null +++ b/crates/engine/src/tests/script_xmp.rs @@ -0,0 +1,479 @@ +//! `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 = "\ +\ +\ +image/svg+xmlab\ +"; + +/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-xmp-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +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 { + 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("text/plain"), "{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("');\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 = + 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> { + 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 = 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 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('changed') > 0); vc.log(out);", + ); + assert_eq!(log[0], json!(["UTF-16LE", " JsResult { 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 { + 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 { + 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 { + 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 { + i.files.as_ref().map(|c| c.run) +} + fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult { let (_, path) = this_path(i, this, what)?; let p = parse_text(i, path, true)?; diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..fc665342dc 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,8 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]). + Xmp(Box), } /// What an XML value is. @@ -309,7 +311,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) => "Object", + Class::XmlFilter(_) | Class::Xmp(_) => "Object", Class::Math => "Math", Class::Json => "JSON", Class::Ordinary | Class::ForIn(_) => "Object", @@ -680,6 +682,7 @@ fn trace_object(o: &Object, work: &mut Vec, 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(), _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..4ef92c0ffd 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -253,6 +253,9 @@ pub(crate) struct Interp { pub(crate) install_error: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, + /// `ExternalObject` and the XMP classes it loads, once a host has added them + /// ([`crate::Realm::define_external_object`]). + pub(crate) xmp: Option, /// The clock and time zone `Date` reads. pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. @@ -518,6 +521,7 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + xmp: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), flattened: std::cell::Cell::new(0), @@ -774,6 +778,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.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..e2d9bddd6c 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -72,6 +72,8 @@ mod token; mod value; mod xml; mod xml_builtins; +mod xmp; +mod xmp_classes; mod xpath; pub use ast::{ @@ -85,6 +87,7 @@ pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, 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)] @@ -214,3 +217,5 @@ mod tests; mod text_tests; #[cfg(test)] mod xml_tests; +#[cfg(test)] +mod xmp_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ee2cd364f8..a9826703ed 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -504,6 +504,18 @@ 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. + 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), + } + } + /// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has /// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its /// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs new file mode 100644 index 0000000000..e0a54bb30b --- /dev/null +++ b/crates/js/src/xmp.rs @@ -0,0 +1,762 @@ +//! XMP metadata for the scripts' `XMPMeta` and `XMPFile` ([`crate::xmp_classes`]): a packet read +//! into the list of its top-level properties and written back as RDF/XML, as the XMP Specification +//! Part 1 (ISO 16684-1, +//! ) +//! describes the serialization. +//! +//! A packet is read with `craft_xml`, which refuses a document type declaration and every entity +//! reference other than the predefined and numeric ones, and bounds the input, the nesting, the +//! nodes and the attributes. The `rdf:Description` elements under `rdf:RDF` give the properties: +//! a simple value (text, or a URI in `rdf:resource`), an array of simple items (`rdf:Bag`, +//! `rdf:Seq` or `rdf:Alt`, each item with an optional `xml:lang`), or any other value (a structure, +//! a value with qualifiers, an array of structures), which is kept as the XML it was written in and +//! written back with the namespace declarations it uses. Namespaces a packet declares are added to +//! the realm's [`Registry`] with the prefix the packet gives them, or a new prefix when that one is +//! taken. +//! +//! VectorCraft's own rules: a packet or a written packet holds at most [`MAX_BYTES`] bytes, +//! elements nest at most 64 deep, a child of `rdf:RDF` other than `rdf:Description` makes the +//! packet malformed, a property given twice keeps its first value, and [`find_packet`] finds only a +//! UTF-8 packet. + +use std::collections::{HashMap, HashSet}; + +use craft_xml::{Doctype, El, Limits, Names, Node, Options, UnknownEntity, XML_NS}; + +/// The RDF namespace. +pub(crate) const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; +/// The namespace of the `x:xmpmeta` element around a packet's `rdf:RDF`. +const X: &str = "adobe:ns:meta/"; // brand-ok: the XMP namespace the files use +/// The Dublin Core namespace. +pub(crate) const DC: &str = "http://purl.org/dc/elements/1.1/"; +/// The XMP basic namespace. +pub(crate) const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace the files use +/// The XMP rights namespace. +pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use +/// The PDF namespace. +pub(crate) const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use +/// The namespace of the image editor's properties. +pub(crate) const PHOTOSHOP: &str = "http://ns.adobe.com/photoshop/1.0/"; // brand-ok: the XMP namespace the files use +/// The XML namespace. +pub(crate) const XML: &str = XML_NS; +/// The namespace of the `xmlns` attributes, which no prefix may name. +const XMLNS: &str = "http://www.w3.org/2000/xmlns/"; + +/// The most bytes of a packet read or written. +pub const MAX_BYTES: usize = 8 << 20; +const MAX_DEPTH: usize = 64; +const MAX_NODES: usize = 1 << 20; +const MAX_ATTRS: usize = 1024; +/// The most namespaces a realm registers. +const MAX_NAMESPACES: usize = 4096; +/// The `id` of a packet wrapper (XMP Specification Part 1, 7.3.2). +const WRAPPER_ID: &str = "W5M0MpCehiHzreSzNTczkc9d"; + +/// The property is a URI (`rdf:resource`). +pub(crate) const PROP_VALUE_IS_URI: u32 = 0x2; +/// The property has qualifiers. +const PROP_HAS_QUALIFIERS: u32 = 0x10; +/// The property has an `xml:lang` qualifier. +const PROP_HAS_LANG: u32 = 0x40; +/// The property is a structure. +pub(crate) const PROP_IS_STRUCT: u32 = 0x100; +/// The property is an array. +pub(crate) const PROP_IS_ARRAY: u32 = 0x200; +/// The array's order matters (`rdf:Seq`). +pub(crate) const ARRAY_IS_ORDERED: u32 = 0x400; +/// The array's items are alternatives (`rdf:Alt`). +pub(crate) const ARRAY_IS_ALTERNATIVE: u32 = 0x800; +/// The array's items are text in several languages. +pub(crate) const ARRAY_IS_ALTTEXT: u32 = 0x1000; + +/// Why XMP could not be read, written or changed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum XmpError { + /// The packet is not well-formed XML, or not XMP. + Malformed, + /// The packet, or the packet written, is longer than [`MAX_BYTES`]. + TooLarge, + /// The realm already has [`MAX_NAMESPACES`] namespaces. + Namespaces, + /// A name that is not an XML name without a colon, or a prefix that names another namespace. + BadName, + /// Text with a character XML does not allow. + BadText, + /// A path form not read yet: a structure field, a qualifier or a selector. + NotYet, +} + +/// The kind of an array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Form { + Bag, + Seq, + Alt, +} + +impl Form { + fn element(self) -> &'static str { + match self { + Form::Bag => "rdf:Bag", + Form::Seq => "rdf:Seq", + Form::Alt => "rdf:Alt", + } + } + + /// The array's options, as `XMPProperty.options` gives them. + fn options(self) -> u32 { + match self { + Form::Bag => PROP_IS_ARRAY, + Form::Seq => PROP_IS_ARRAY | ARRAY_IS_ORDERED, + Form::Alt => PROP_IS_ARRAY | ARRAY_IS_ORDERED | ARRAY_IS_ALTERNATIVE, + } + } + + /// The form the options of a new array give: `Alt` with [`ARRAY_IS_ALTERNATIVE`] or + /// [`ARRAY_IS_ALTTEXT`], `Seq` with [`ARRAY_IS_ORDERED`], else `Bag`. + pub(crate) fn from_options(options: u32) -> Form { + if options & (ARRAY_IS_ALTERNATIVE | ARRAY_IS_ALTTEXT) != 0 { + Form::Alt + } else if options & ARRAY_IS_ORDERED != 0 { + Form::Seq + } else { + Form::Bag + } + } +} + +/// An item of an array of simple values. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Item { + pub(crate) text: String, + pub(crate) lang: Option, +} + +/// A property's value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Value { + Simple { + text: String, + uri: bool, + }, + Array { + form: Form, + items: Vec, + }, + /// A value kept as the XML element it was read as, with the namespace declarations it uses, its + /// options and its text when it has one. + Other { + xml: String, + options: u32, + text: Option, + }, +} + +impl Value { + /// The options `XMPProperty.options` gives. + pub(crate) fn options(&self) -> u32 { + match self { + Value::Simple { uri, .. } => { + if *uri { + PROP_VALUE_IS_URI + } else { + 0 + } + } + Value::Array { form, items } => { + let alt_text = *form == Form::Alt && !items.is_empty() && items.iter().all(|i| i.lang.is_some()); + form.options() | if alt_text { ARRAY_IS_ALTTEXT } else { 0 } + } + Value::Other { options, .. } => *options, + } + } + + /// The text `XMPProperty.value` gives; `None` for an array or a structure. + pub(crate) fn text(&self) -> Option<&str> { + match self { + Value::Simple { text, .. } => Some(text), + Value::Array { .. } => None, + Value::Other { text, .. } => text.as_deref(), + } + } +} + +/// A top-level property. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Prop { + pub(crate) ns: String, + pub(crate) name: String, + pub(crate) value: Value, +} + +impl Prop { + /// The estimated bytes the property holds. + pub(crate) fn heap_bytes(&self) -> usize { + let value = match &self.value { + Value::Simple { text, .. } => text.len(), + Value::Array { items, .. } => items.iter().map(|i| 48 + i.text.len() + i.lang.as_ref().map_or(0, String::len)).sum(), + Value::Other { xml, text, .. } => xml.len() + text.as_ref().map_or(0, String::len), + }; + 96 + self.ns.len() + self.name.len() + value + } +} + +/// The metadata of one `XMPMeta`: its `rdf:about` and its properties, in order. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct Meta { + pub(crate) about: String, + pub(crate) props: Vec, +} + +impl Meta { + /// The estimated bytes the metadata holds. + pub(crate) fn heap_bytes(&self) -> usize { + 32 + self.about.len() + self.props.iter().map(Prop::heap_bytes).sum::() + } + + /// The position of the property `name` in the namespace `ns`. + pub(crate) fn find(&self, ns: &str, name: &str) -> Option { + self.props.iter().position(|p| p.ns == ns && p.name == name) + } +} + +/// The namespaces a realm knows, each with its prefix (without the colon), in the order they were +/// registered. +#[derive(Clone, Debug)] +pub(crate) struct Registry { + /// Prefix by namespace, and namespace by prefix: each namespace has one prefix and each prefix + /// names one namespace. + prefixes: HashMap, + uris: HashMap, +} + +impl Default for Registry { + fn default() -> Self { + let standard = + [("rdf", RDF), ("x", X), ("xml", XML), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF), ("photoshop", PHOTOSHOP)]; // brand-ok: the XMP namespace prefix the files use + Self { + prefixes: standard.iter().map(|(p, u)| ((*u).to_string(), (*p).to_string())).collect(), + uris: standard.iter().map(|(p, u)| ((*p).to_string(), (*u).to_string())).collect(), + } + } +} + +impl Registry { + /// The prefix of the namespace `uri`. + pub(crate) fn prefix_of(&self, uri: &str) -> Option<&str> { + self.prefixes.get(uri).map(String::as_str) + } + + /// The namespace the prefix `prefix` names. + pub(crate) fn uri_of(&self, prefix: &str) -> Option<&str> { + self.uris.get(prefix).map(String::as_str) + } + + /// Registers the namespace `uri` with the prefix `suggested` (a trailing colon is left out), or + /// with `suggested_1_`, `suggested_2_` … when that one names another namespace. → the prefix + /// the namespace has, which is its earlier one when it was registered before. + pub(crate) fn register(&mut self, uri: &str, suggested: &str) -> Result { + if let Some(p) = self.prefix_of(uri) { + return Ok(p.to_string()); + } + let suggested = suggested.strip_suffix(':').unwrap_or(suggested); + // XML does not allow the prefix `xmlns` to be declared or a prefix to name its namespace. + if uri.is_empty() || !is_text(uri) || !is_ncname(suggested) || suggested == "xmlns" || uri == XMLNS { + return Err(XmpError::BadName); + } + if self.prefixes.len() >= MAX_NAMESPACES { + return Err(XmpError::Namespaces); + } + let mut prefix = suggested.to_string(); + let mut n = 1; + while self.uri_of(&prefix).is_some() { + prefix = format!("{suggested}_{n}_"); + n += 1; + } + self.prefixes.insert(uri.to_string(), prefix.clone()); + self.uris.insert(prefix.clone(), uri.to_string()); + Ok(prefix) + } +} + +/// Is `s` an XML name without a colon? +pub(crate) fn is_ncname(s: &str) -> bool { + craft_xml::is_name(s) && !s.contains(':') +} + +/// Does `s` hold only characters XML allows? +pub(crate) fn is_text(s: &str) -> bool { + s.chars().all(craft_xml::is_xml_char) +} + +/// Where a property path leads: the whole property, or one item of an array by its position from 1 +/// (-1 for the last). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Step { + Whole, + Item(i64), +} + +/// The property name and step of the path `path` in the namespace `ns`: `name`, `prefix:name`, +/// either with `[n]` or `[last()]` after it. A prefix must name `ns`. +pub(crate) fn parse_path(path: &str, ns: &str, registry: &Registry) -> Result<(String, Step), XmpError> { + if path.contains(['/', '?', '@']) { + return Err(XmpError::NotYet); + } + let (name, step) = match path.split_once('[') { + None => (path, Step::Whole), + Some((name, rest)) => { + let inner = rest.strip_suffix(']').ok_or(XmpError::BadName)?; + let step = match inner { + "last()" => Step::Item(-1), + n if !n.is_empty() && n.len() <= 9 && n.bytes().all(|b| b.is_ascii_digit()) => match n.parse::() { + Ok(i) if i >= 1 => Step::Item(i), + _ => return Err(XmpError::BadName), + }, + _ => return Err(XmpError::NotYet), + }; + (name, step) + } + }; + let local = match name.split_once(':') { + Some((prefix, local)) => { + if registry.uri_of(prefix) != Some(ns) { + return Err(XmpError::BadName); + } + local + } + None => name, + }; + if !is_ncname(local) { + return Err(XmpError::BadName); + } + Ok((local.to_string(), step)) +} + +/// The bindings of namespace prefixes in scope, innermost last; `""` is the default namespace. +type Scope = Vec<(String, String)>; + +fn push_decls(el: &El, scope: &mut Scope) { + for (prefix, uri) in el.ns_decls() { + scope.push((prefix.to_string(), uri.to_string())); + } +} + +/// Is `name` a namespace declaration? +fn is_decl(name: &str) -> bool { + name == "xmlns" || name.starts_with("xmlns:") +} + +/// The namespace and local name of the qualified name `name`: an unprefixed element is in the +/// default namespace, an unprefixed attribute (`element` false) in none. `None` for a prefix +/// nothing declares. +fn resolve<'n>(name: &'n str, scope: &Scope, element: bool) -> Option<(String, &'n str)> { + let (prefix, local) = match name.split_once(':') { + Some((p, l)) => (p, l), + None if element => ("", name), + None => return Some((String::new(), name)), + }; + if prefix == "xml" { + return Some((XML.to_string(), local)); + } + let uri = scope.iter().rev().find(|(p, _)| p == prefix).map(|(_, u)| u.clone()); + match uri { + Some(u) => Some((u, local)), + None if prefix.is_empty() => Some((String::new(), local)), + None => None, + } +} + +fn is_named(name: &str, scope: &Scope, element: bool, ns: &str, local: &str) -> bool { + resolve(name, scope, element).is_some_and(|(u, l)| u == ns && l == local) +} + +/// The text of `el`'s own text and CDATA children. +fn text_of(el: &El) -> String { + let mut s = String::new(); + for n in &el.children { + if let Node::Text(t) | Node::CData(t) = n { + s.push_str(t); + } + } + s +} + +/// The attributes of `el` that are not namespace declarations. +fn attrs(el: &El) -> Vec<(&str, &str)> { + el.attrs.iter().filter(|(k, _)| !is_decl(k)).map(|(k, v)| (k.as_str(), v.as_str())).collect() +} + +/// The `rdf:RDF` element at or below `el`, with `scope` holding the bindings in scope there. +fn find_rdf<'a>(el: &'a El, scope: &mut Scope) -> Option<&'a El> { + let mark = scope.len(); + push_decls(el, scope); + if is_named(&el.name, scope, true, RDF, "RDF") { + return Some(el); + } + for c in el.elements() { + if let Some(found) = find_rdf(c, scope) { + return Some(found); + } + } + scope.truncate(mark); + None +} + +/// Reads the packet `text`, registering the namespaces it uses in `registry`. A packet that fails +/// to read leaves `registry` unchanged. +pub(crate) fn parse(text: &str, registry: &mut Registry) -> Result { + let mut staged = registry.clone(); + let meta = parse_into(text, &mut staged)?; + *registry = staged; + Ok(meta) +} + +fn parse_into(text: &str, registry: &mut Registry) -> Result { + if text.len() > MAX_BYTES { + return Err(XmpError::TooLarge); + } + let text = text.strip_prefix('\u{FEFF}').unwrap_or(text); + let limits = Limits { max_input: MAX_BYTES, max_depth: MAX_DEPTH, max_nodes: MAX_NODES, max_attrs: MAX_ATTRS, ..Limits::DEFAULT }; + let opts = Options { + names: Names::AsWritten, + doctype: Doctype::Reject, + unknown_entity: UnknownEntity::Error, + drop_blank_text: true, + limits, + ..Options::default() + } + .strict(); + let root = opts.parse(text.as_bytes()).map_err(|e| if e.is_limit() { XmpError::TooLarge } else { XmpError::Malformed })?; + let mut scope = Scope::new(); + let rdf = find_rdf(&root, &mut scope).ok_or(XmpError::Malformed)?; + let mut meta = Meta::default(); + let mut seen = HashSet::new(); + for d in rdf.elements() { + let mark = scope.len(); + push_decls(d, &mut scope); + if !is_named(&d.name, &scope, true, RDF, "Description") { + return Err(XmpError::Malformed); + } + for (k, v) in attrs(d) { + let Some((ns, local)) = resolve(k, &scope, false) else { return Err(XmpError::Malformed) }; + if ns == RDF { + if local == "about" && meta.about.is_empty() { + meta.about = v.to_string(); + } + continue; + } + if ns.is_empty() || ns == XML { + continue; + } + let prefix = k.split_once(':').map_or("ns", |(p, _)| p); + registry.register(&ns, prefix)?; + add(&mut meta, &mut seen, Prop { ns, name: local.to_string(), value: Value::Simple { text: v.to_string(), uri: false } }); + } + for p in d.elements() { + let prop = read_property(p, &mut scope, registry)?; + add(&mut meta, &mut seen, prop); + } + scope.truncate(mark); + } + Ok(meta) +} + +/// Adds `prop` to `meta` unless it already has a property of that name; `seen` holds the names +/// `meta` has. +fn add(meta: &mut Meta, seen: &mut HashSet<(String, String)>, prop: Prop) { + if seen.insert((prop.ns.clone(), prop.name.clone())) { + meta.props.push(prop); + } +} + +fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result { + let mark = scope.len(); + push_decls(p, scope); + let (ns, local) = resolve(&p.name, scope, true).ok_or(XmpError::Malformed)?; + if ns.is_empty() || ns == RDF || ns == XML { + return Err(XmpError::Malformed); + } + let prefix = p.name.split_once(':').map_or("ns", |(p, _)| p); + registry.register(&ns, prefix)?; + let own = attrs(p); + let children: Vec<&El> = p.elements().collect(); + let value = if children.is_empty() && own.is_empty() { + Value::Simple { text: text_of(p), uri: false } + } else if let ([], [(k, v)]) = (children.as_slice(), own.as_slice()) + && is_named(k, scope, false, RDF, "resource") + && text_of(p).trim().is_empty() + { + Value::Simple { text: (*v).to_string(), uri: true } + } else if let (Some(array), true) = (array_of(&children, scope), own.is_empty()) { + array + } else { + other(p, &own, &children, scope, mark) + }; + scope.truncate(mark); + Ok(Prop { ns, name: local.to_string(), value }) +} + +/// The array of simple items the only child of a property element holds, when it is one. +fn array_of(children: &[&El], scope: &mut Scope) -> Option { + let [container] = children else { return None }; + let mark = scope.len(); + push_decls(container, scope); + let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&container.name, scope, true, RDF, &f.element()[4..])); + let mut items = Vec::new(); + let ok = form.is_some() && attrs(container).is_empty() && text_of(container).trim().is_empty() && { + container.elements().all(|li| { + let inner = scope.len(); + push_decls(li, scope); + let mut lang = None; + let mut simple = is_named(&li.name, scope, true, RDF, "li") && li.elements().next().is_none(); + for (k, v) in attrs(li) { + if is_named(k, scope, false, XML, "lang") { + lang = Some(v.to_string()); + } else { + simple = false; + } + } + scope.truncate(inner); + if simple { + items.push(Item { text: text_of(li), lang }); + } + simple + }) + }; + scope.truncate(mark); + match (ok, form) { + (true, Some(form)) => Some(Value::Array { form, items }), + _ => None, + } +} + +/// A value kept as the XML it was read as. +fn other(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope, mark: usize) -> Value { + // The first child's name is read with the prefixes it declares itself. + let form = children.first().and_then(|c| { + let inner = scope.len(); + push_decls(c, scope); + let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&c.name, scope, true, RDF, &f.element()[4..])); + scope.truncate(inner); + form + }); + let resource = own.iter().find(|(k, _)| is_named(k, scope, false, RDF, "resource")).map(|(_, v)| (*v).to_string()); + let lang = own.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")); + let (options, text) = match form { + Some(f) if children.len() == 1 => (f.options() | PROP_HAS_QUALIFIERS, None), + _ if !children.is_empty() || own.iter().any(|(k, _)| is_named(k, scope, false, RDF, "parseType")) => (PROP_IS_STRUCT, None), + _ => { + let uri = if resource.is_some() { PROP_VALUE_IS_URI } else { 0 }; + (PROP_HAS_QUALIFIERS | uri | if lang { PROP_HAS_LANG } else { 0 }, Some(resource.unwrap_or_else(|| text_of(p)))) + } + }; + let mut xml = String::new(); + write_fragment(p, scope.get(..mark).unwrap_or(&[]), &mut xml); + Value::Other { xml, options, text } +} + +/// Writes the element `p` as XML, declaring on it the prefixes from `outer` that it and the +/// elements inside it use and do not declare themselves. +fn write_fragment(p: &El, outer: &[(String, String)], out: &mut String) { + let mut used: Vec = Vec::new(); + collect_prefixes(p, &mut used); + let own: Vec<&str> = p.ns_decls().map(|(prefix, _)| prefix).collect(); + out.push('<'); + out.push_str(&p.name); + for prefix in used.iter().filter(|u| !own.contains(&u.as_str())) { + if let Some((_, uri)) = outer.iter().rev().find(|(q, _)| q == prefix) { + if prefix.is_empty() { + out.push_str(" xmlns=\""); + } else { + out.push_str(" xmlns:"); + out.push_str(prefix); + out.push_str("=\""); + } + craft_xml::push_esc_attr(out, uri); + out.push('"'); + } + } + write_rest(p, out); +} + +/// The prefixes the names of `el` and the elements inside it use, `""` for an unprefixed element. +fn collect_prefixes(el: &El, used: &mut Vec) { + let mut add = |prefix: &str| { + if prefix != "xml" && !used.iter().any(|u| u == prefix) { + used.push(prefix.to_string()); + } + }; + add(el.name.split_once(':').map_or("", |(p, _)| p)); + for (k, _) in &el.attrs { + if let Some((p, _)) = k.split_once(':') + && p != "xmlns" + { + add(p); + } + } + for c in el.elements() { + collect_prefixes(c, used); + } +} + +/// Writes the attributes, the children and the end tag of `el`, whose name is already written. +fn write_rest(el: &El, out: &mut String) { + for (k, v) in &el.attrs { + out.push(' '); + out.push_str(k); + out.push_str("=\""); + craft_xml::push_esc_attr(out, v); + out.push('"'); + } + if el.children.is_empty() { + out.push_str("/>"); + return; + } + out.push('>'); + for n in &el.children { + match n { + Node::El(c) => { + out.push('<'); + out.push_str(&c.name); + write_rest(c, out); + } + Node::Text(t) | Node::CData(t) => craft_xml::push_esc(out, t), + Node::Pi { .. } | Node::Comment(_) => {} + } + } + out.push_str("'); +} + +/// Text written while keeping to [`MAX_BYTES`]. +struct Out(String); + +impl Out { + fn push(&mut self, s: &str) -> Result<(), XmpError> { + if self.0.len().saturating_add(s.len()) > MAX_BYTES { + return Err(XmpError::TooLarge); + } + self.0.push_str(s); + Ok(()) + } + + fn text(&mut self, s: &str) -> Result<(), XmpError> { + self.push(&craft_xml::esc(s)) + } + + fn attr(&mut self, s: &str) -> Result<(), XmpError> { + self.push(&craft_xml::esc_attr(s)) + } +} + +/// `meta` as an XMP packet: the `x:xmpmeta` element inside a writable packet wrapper, or alone +/// without `wrapper`. +pub(crate) fn serialize(meta: &Meta, registry: &Registry, wrapper: bool) -> Result { + let mut namespaces: Vec<(&str, &str)> = Vec::new(); + let mut declared = HashSet::new(); + for p in &meta.props { + if matches!(p.value, Value::Other { .. }) || !declared.insert(p.ns.as_str()) { + continue; + } + let prefix = registry.prefix_of(&p.ns).ok_or(XmpError::BadName)?; + namespaces.push((prefix, &p.ns)); + } + let prefix = |ns: &str| registry.prefix_of(ns).ok_or(XmpError::BadName); + let mut out = Out(String::new()); + if wrapper { + out.push(&format!("\n"))?; + } + out.push(&format!("\n \n \n")?; + for p in &meta.props { + match &p.value { + Value::Simple { text, uri: false } => { + let name = format!("{}:{}", prefix(&p.ns)?, p.name); + out.push(&format!(" <{name}>"))?; + out.text(text)?; + out.push(&format!("\n"))?; + } + Value::Simple { text, uri: true } => { + out.push(&format!(" <{}:{} rdf:resource=\"", prefix(&p.ns)?, p.name))?; + out.attr(text)?; + out.push("\"/>\n")?; + } + Value::Array { form, items } => { + let name = format!("{}:{}", prefix(&p.ns)?, p.name); + out.push(&format!(" <{name}>\n <{}>\n", form.element()))?; + for item in items { + out.push(" ")?; + out.text(&item.text)?; + out.push("\n")?; + } + out.push(&format!(" \n \n", form.element()))?; + } + Value::Other { xml, .. } => { + out.push(" ")?; + out.push(xml)?; + out.push("\n")?; + } + } + } + out.push(" \n \n")?; + if wrapper { + out.push("\n")?; + } + Ok(out.0) +} + +/// Where a packet lies in a file's bytes: from the start of its ``, and whether its wrapper marks it writable (`end="w"`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PacketSpan { + pub start: usize, + pub end: usize, + pub writeable: bool, +} + +/// The characters of whitespace padding just before the ` usize { + packet.rfind(" Option { + const BEGIN: &[u8] = b"") { + Some(close) => return Some(PacketSpan { start, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }), + None => start = next?, + } + } +} diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs new file mode 100644 index 0000000000..ab6c2a6174 --- /dev/null +++ b/crates/js/src/xmp_classes.rs @@ -0,0 +1,1224 @@ +//! `ExternalObject` and the XMP classes it loads, as the help pages +//! , +//! and +//! describe them, +//! as built-ins ([`crate::Realm::define_external_object`]). The metadata itself is +//! [`crate::xmp`]. +//! +//! `new ExternalObject("lib:AdobeXMPScript")` defines the globals `XMPMeta`, `XMPFile` and +//! `XMPConst` and gives a handle whose `terminate()` releases it; the globals and the objects made +//! with them stay. Any other library name throws an `Error`, and no native code is loaded. +//! `ExternalObject.search(name)` is true for that name alone. +//! +//! `XMPMeta` holds its metadata in its object. Its namespace prefixes are the realm's: those a +//! packet declares are registered when it is read, and `XMPMeta.registerNamespace` adds others. +//! `getNamespacePrefix` and `registerNamespace` give a prefix with its colon. Property paths are a +//! name, `prefix:name`, and either with `[n]` (from 1) or `[last()]` for an array item. An array +//! property holds simple items; any other value a packet holds is kept as it was written and +//! `getProperty` gives its text, when it has one, and its options. +//! +//! `XMPFile` reads a file through the host functions `xmpOpen` and `xmpWrite` of `File` and +//! `Folder` ([`crate::Realm::define_file_classes`]), so it reads and writes only where they may. A +//! file named `.xmp` is read whole as a packet, and any other file, or any file with +//! `OPEN_USE_PACKET_SCANNING`, is scanned for its first packet ([`crate::xmp::find_packet`]). +//! `putXMP` keeps the packet and `closeFile` writes it. +//! +//! VectorCraft's own rules: only a `.xmp` file opened with `OPEN_FOR_UPDATE` takes `putXMP`; +//! `closeFile` always replaces the file through a temporary one when the folder may hold one; an +//! `XMPFile` is open only in the run that opened it, and a packet it kept and did not write is +//! dropped when the run ends. A member the reference lists that is not built yet, and a flag, +//! format or option not handled yet, throws an error that says so. + +use crate::builtins::{arg, data, method, native}; +use crate::heap::{Class, ENUMERABLE, HIDDEN, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; +use crate::xmp::{self, Form, Item, Meta, Registry, Step, XmpError}; + +/// The one library `ExternalObject` loads. +const LIBRARY: &str = "lib:AdobeXMPScript"; // brand-ok: the library name scripts load + +const FILE_UNKNOWN: u32 = 0x2020_2020; +const FILE_TEXT: u32 = 0x7465_7874; +const FILE_XML: u32 = 0x584D_4C20; +const OPEN_FOR_READ: u32 = 0x1; +const OPEN_FOR_UPDATE: u32 = 0x2; +const OPEN_ONLY_XMP: u32 = 0x4; +const OPEN_USE_PACKET_SCANNING: u32 = 0x40; +const CLOSE_UPDATE_SAFELY: u32 = 0x1; +const SERIALIZE_OMIT_PACKET_WRAPPER: u32 = 0x10; + +const LIBRARY_SLOT: &str = "__vcLibrary"; +const PATH: &str = "__vcXmpPath"; +const FORMAT: &str = "__vcXmpFormat"; +const FLAGS: &str = "__vcXmpFlags"; +const RUN: &str = "__vcXmpRun"; +const OPEN: &str = "__vcXmpOpen"; +const PACKET: &str = "__vcXmpPacket"; +const OFFSET: &str = "__vcXmpOffset"; +const LENGTH: &str = "__vcXmpLength"; +const WRITEABLE: &str = "__vcXmpWriteable"; +const SIDECAR: &str = "__vcXmpSidecar"; +const CHAR_FORM: &str = "__vcXmpCharForm"; +const PENDING: &str = "__vcXmpPending"; + +/// The objects of `ExternalObject` and the XMP classes, kept by the realm, and its namespaces. +#[derive(Debug)] +pub(crate) struct Classes { + ids: Ids, + registry: Registry, +} + +#[derive(Clone, Copy, Debug)] +struct Ids { + external_proto: ObjId, + meta: ObjId, + meta_proto: ObjId, + file: ObjId, + file_proto: ObjId, + constants: ObjId, + property_proto: ObjId, +} + +impl Classes { + /// The objects a collection keeps. + pub(crate) fn objects(&self) -> [ObjId; 7] { + let i = self.ids; + [i.external_proto, i.meta, i.meta_proto, i.file, i.file_proto, i.constants, i.property_proto] + } +} + +fn ids(i: &Interp) -> JsResult { + i.xmp.as_ref().map(|c| c.ids).ok_or_else(|| Abrupt::Internal("ExternalObject is not installed".into())) +} + +fn registry(i: &mut Interp) -> JsResult<&mut Registry> { + i.xmp.as_mut().map(|c| &mut c.registry).ok_or_else(|| Abrupt::Internal("ExternalObject is not installed".into())) +} + +// ---- errors ---- + +fn not_yet(i: &mut Interp, what: &str) -> Abrupt { + i.throw(ErrorType::Error, &format!("{what} is not available yet")) +} + +fn not_handled(i: &mut Interp, what: &str, value: &str) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: the value {value} is not available yet")) +} + +fn wrong_object(i: &mut Interp, what: &str, class: &str) -> Abrupt { + i.type_error(&format!("{what}: the object is not an {class} object")) +} + +/// The exception for `e`, which `what` met with the name or path `name`. +fn xmp_error(i: &mut Interp, what: &str, e: XmpError, name: &str) -> Abrupt { + match e { + XmpError::Malformed => i.throw(ErrorType::Error, &format!("{what}: the XMP packet is not well-formed XMP")), + XmpError::TooLarge | XmpError::Namespaces => i.throw(ErrorType::Range, &format!("{what}: the XMP data is too large")), + XmpError::BadName => i.throw(ErrorType::Error, &format!("{what}: {name} is not a valid property name")), + XmpError::BadText => i.throw(ErrorType::Error, &format!("{what}: the text holds a character XML does not allow")), + XmpError::NotYet => not_handled(i, what, name), + } +} + +fn not_array(i: &mut Interp, what: &str, name: &str) -> Abrupt { + i.throw(ErrorType::Error, &format!("{what}: {name} is not an array")) +} + +fn not_simple(i: &mut Interp, what: &str, name: &str) -> Abrupt { + i.throw(ErrorType::Error, &format!("{what}: {name} is not a simple property")) +} + +fn not_alt_text(i: &mut Interp, what: &str, name: &str) -> Abrupt { + i.throw(ErrorType::Error, &format!("{what}: {name} is not a language alternative array")) +} + +fn out_of_range(i: &mut Interp, what: &str, index: i64) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: the array index {index} is out of range")) +} + +fn unregistered(i: &mut Interp, what: &str, uri: &str) -> Abrupt { + i.throw(ErrorType::Error, &format!("{what}: the namespace {uri} is not registered")) +} + +// ---- small helpers ---- + +fn text(i: &mut Interp, v: &Value) -> JsResult { + Ok(i.to_str(v)?.to_rust_string()) +} + +/// A string argument's value as plain text, refused when it holds a character XML does not allow. +fn xml_text(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let s = text(i, v)?; + if !xmp::is_text(&s) { + return Err(xmp_error(i, what, XmpError::BadText, "")); + } + Ok(s) +} + +/// A flags argument: `undefined` and `null` are 0, any other value a whole number from 0 to +/// 2^32 - 1, refused with a `RangeError` otherwise. +fn flags(i: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Undefined | Value::Null) { + return Ok(0); + } + let n = i.to_number(v)?; + if n.fract() != 0.0 || !(0.0..=f64::from(u32::MAX)).contains(&n) { + let shown = crate::number::to_string(n); + return Err(not_handled(i, what, &shown)); + } + Ok(n as u32) +} + +/// Refuses the bits of `value` outside `allowed`, naming the first. +fn only(i: &mut Interp, value: u32, allowed: u32, what: &str) -> JsResult<()> { + let extra = value & !allowed; + if extra != 0 { + let bit = 1u32 << extra.trailing_zeros(); + return Err(not_handled(i, what, &format!("0x{bit:X}"))); + } + Ok(()) +} + +/// Takes fuel for reading or writing `bytes` bytes of XMP. +fn spend(i: &mut Interp, bytes: usize) -> JsResult<()> { + crate::regexp_vm::use_fuel_n(i, 1 + bytes as u64 / 256) +} + +fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match i.get_own_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) +} + +fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + if let Value::String(s) = &value { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; + } + i.define(o, key(name), Prop::Data { value, flags: HIDDEN }) +} + +/// A string value, charged to the heap. +fn string(i: &mut Interp, s: &str) -> JsResult { + let bytes = string_bytes(s.encode_utf16().count()); + i.reserve_heap(bytes)?; + i.heap.bytes = i.heap.bytes.saturating_add(bytes); + Ok(Value::str(s)) +} + +/// A new ordinary object with the prototype `proto` and the read-only data properties `fields`. +fn record(i: &mut Interp, proto: Option, fields: Vec<(&'static str, Value)>) -> JsResult { + i.rooted(&fields.iter().map(|(_, v)| v.clone()).collect::>(), |i| { + i.reserve_heap(OBJECT_BYTES + PROP_BYTES * fields.len())?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, proto.or(Some(i.intrinsics.object_proto)))); + for (name, value) in &fields { + i.define(o, key(name), Prop::Data { value: value.clone(), flags: ENUMERABLE })?; + } + Ok(Value::Object(o)) + }) +} + +// ---- ExternalObject ---- + +fn external_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let name = text(i, &arg(args, 0))?; + if name != LIBRARY { + let name: String = name.chars().take(200).collect(); + let what = "ExternalObject"; + return Err(i.throw(ErrorType::Error, &format!("{what}: the library {name} is not available"))); + } + let ids = ids(i)?; + let global = i.global; + data(i, global, "XMPMeta", Value::Object(ids.meta), HIDDEN)?; + data(i, global, "XMPFile", Value::Object(ids.file), HIDDEN)?; + data(i, global, "XMPConst", Value::Object(ids.constants), HIDDEN)?; + i.reserve_heap(OBJECT_BYTES + PROP_BYTES)?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(ids.external_proto))); + i.rooted(&[Value::Object(o)], |i| set_slot(i, o, LIBRARY_SLOT, Value::str(LIBRARY)))?; + Ok(Value::Object(o)) +} + +fn external_search(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + Ok(Value::Bool(text(i, &arg(args, 0))? == LIBRARY)) +} + +fn external_terminate(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let handle = this.as_object().filter(|&o| matches!(slot(i, o, LIBRARY_SLOT), Ok(Value::String(_)))); + let Some(o) = handle else { return Err(wrong_object(i, "ExternalObject.terminate", "ExternalObject")) }; + set_slot(i, o, LIBRARY_SLOT, Value::Bool(false))?; + Ok(Value::Undefined) +} + +// ---- XMPMeta ---- + +fn is_meta(i: &Interp, v: &Value) -> Option { + v.as_object().filter(|&o| matches!(i.heap.object(o).map(|ob| &ob.class), Some(Class::Xmp(_)))) +} + +fn this_meta(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match is_meta(i, this) { + Some(o) => Ok(o), + None => Err(wrong_object(i, what, "XMPMeta")), + } +} + +fn meta_of(i: &Interp, o: ObjId) -> JsResult<&Meta> { + match i.heap.object(o).map(|ob| &ob.class) { + Some(Class::Xmp(m)) => Ok(m), + _ => Err(Abrupt::Internal("an XMPMeta lost its metadata".into())), + } +} + +/// Changes the metadata of `o` with `f`, given `grow`, the most bytes the change adds, and charges +/// the heap for what it added or frees what it took out. +fn change(i: &mut Interp, o: ObjId, grow: usize, f: impl FnOnce(&mut Meta, &Registry) -> T) -> JsResult { + i.reserve_heap(grow)?; + let Some(c) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; + let Some(Class::Xmp(m)) = i.heap.object_mut(o).map(|ob| &mut ob.class) else { + return Err(Abrupt::Internal("an XMPMeta lost its metadata".into())); + }; + let before = m.heap_bytes(); + let r = f(m, &c.registry); + let after = m.heap_bytes(); + i.heap.bytes = if after >= before { i.heap.bytes.saturating_add(after - before) } else { i.heap.bytes.saturating_sub(before - after) }; + Ok(r) +} + +/// A new `XMPMeta` holding `meta`. +fn new_meta(i: &mut Interp, meta: Meta) -> JsResult { + let ids = ids(i)?; + let bytes = meta.heap_bytes(); + i.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let o = i.heap.alloc_object(Object::new(Class::Xmp(Box::new(meta)), Some(ids.meta_proto))); + i.heap.bytes = i.heap.bytes.saturating_add(bytes); + Ok(Value::Object(o)) +} + +/// The metadata of the packet `text`, read for `what`. +fn parse_packet(i: &mut Interp, what: &str, text: &str) -> JsResult { + spend(i, text.len())?; + let r = xmp::parse(text, registry(i)?); + r.map_err(|e| xmp_error(i, what, e, "")) +} + +fn meta_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let meta = match arg(args, 0) { + Value::Undefined => Meta::default(), + Value::Object(o) if matches!(i.heap.object(o).map(|ob| &ob.class), Some(Class::Array { .. })) => { + return Err(not_yet(i, "new XMPMeta(buffer)")); + } + v => { + let packet = text(i, &v)?; + parse_packet(i, "XMPMeta", &packet)? + } + }; + new_meta(i, meta) +} + +/// The namespace argument `v`, refused when it is not registered. +fn namespace(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let uri = text(i, v)?; + if registry(i)?.prefix_of(&uri).is_none() { + return Err(unregistered(i, what, &uri)); + } + Ok(uri) +} + +/// The namespace and path arguments at `at`: the namespace, the property name and its step. +fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult<(String, String, Step)> { + let ns = namespace(i, &arg(args, at), what)?; + let path = text(i, &arg(args, at + 1))?; + let r = xmp::parse_path(&path, &ns, registry(i)?); + match r { + Ok((name, step)) => Ok((ns, name, step)), + Err(e) => Err(xmp_error(i, what, e, &path)), + } +} + +/// The index an item position names in an array of `len` items: -1 is the last. +fn position(index: i64, len: usize) -> Option { + let i = if index == -1 { len } else { usize::try_from(index).ok()? }; + (1..=len).contains(&i).then(|| i - 1) +} + +/// An item position argument: a whole number from 1, or -1 for the last. +fn item_index(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let n = i.to_number(v)?; + if n.fract() != 0.0 || !(n == -1.0 || (1.0..=1e15).contains(&n)) { + return Err(out_of_range(i, what, if n.is_finite() { n as i64 } else { 0 })); + } + Ok(n as i64) +} + +/// An `XMPProperty` for `path` in `ns`. +fn property(i: &mut Interp, ns: &str, path: &str, value: Option<&str>, options: u32, locale: &str) -> JsResult { + let proto = ids(i)?.property_proto; + let ns = string(i, ns)?; + let path = i.rooted(std::slice::from_ref(&ns), |i| string(i, path))?; + let value = match value { + Some(v) => i.rooted(&[ns.clone(), path.clone()], |i| string(i, v))?, + None => Value::Undefined, + }; + let locale = i.rooted(&[ns.clone(), path.clone(), value.clone()], |i| string(i, locale))?; + let fields = vec![("namespace", ns), ("path", path), ("value", value), ("options", Value::Number(f64::from(options))), ("locale", locale)]; + record(i, Some(proto), fields) +} + +fn property_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let v = match this.as_object() { + Some(o) => slot(i, o, "value")?, + None => Value::Undefined, + }; + if matches!(v, Value::Undefined) { Ok(Value::str("")) } else { Ok(Value::String(i.to_str(&v)?)) } +} + +fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.getProperty"; + let o = this_meta(i, &this, what)?; + let (ns, name, step) = target(i, args, 0, what)?; + if !matches!(arg(args, 2), Value::Undefined) { + let v = text(i, &arg(args, 2))?; + return Err(not_handled(i, what, &v)); + } + let path = text(i, &arg(args, 1))?; + let found = { + let m = meta_of(i, o)?; + m.find(&ns, &name).map(|at| m.props[at].value.clone()) + }; + let Some(value) = found else { return Ok(Value::Undefined) }; + match step { + Step::Whole => property(i, &ns, &path, value.text(), value.options(), ""), + Step::Item(index) => match value { + xmp::Value::Array { items, .. } => match position(index, items.len()).and_then(|p| items.get(p)) { + Some(item) => property(i, &ns, &path, Some(&item.text), 0, item.lang.as_deref().unwrap_or("")), + None => Ok(Value::Undefined), + }, + _ => Err(not_array(i, what, &name)), + }, + } +} + +fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setProperty"; + let o = this_meta(i, &this, what)?; + let (ns, name, step) = target(i, args, 0, what)?; + let options = flags(i, &arg(args, 3), what)?; + only(i, options, xmp::PROP_IS_ARRAY | xmp::ARRAY_IS_ORDERED | xmp::ARRAY_IS_ALTERNATIVE, what)?; + if !matches!(arg(args, 4), Value::Undefined) { + let v = text(i, &arg(args, 4))?; + return Err(not_handled(i, what, &v)); + } + let value = arg(args, 2); + if let Step::Item(index) = step { + let v = xml_text(i, &value, what)?; + return set_item(i, o, &ns, &name, index, v, false, what); + } + if options != 0 { + // An array is made empty; one that exists is left as it is. + if !matches!(value, Value::Undefined | Value::Null) { + let v = text(i, &value)?; + return Err(not_handled(i, what, &v)); + } + let kind = { + let m = meta_of(i, o)?; + m.find(&ns, &name).map(|at| matches!(m.props[at].value, xmp::Value::Array { .. })) + }; + return match kind { + Some(true) => Ok(Value::Undefined), + Some(false) => Err(not_array(i, what, &name)), + None => { + let prop = xmp::Prop { ns, name, value: xmp::Value::Array { form: Form::from_options(options), items: Vec::new() } }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop)).map(|()| Value::Undefined) + } + }; + } + let v = xml_text(i, &value, what)?; + let simple = { + let m = meta_of(i, o)?; + m.find(&ns, &name).map(|at| (at, matches!(m.props[at].value, xmp::Value::Simple { .. }))) + }; + let new = xmp::Value::Simple { text: v, uri: false }; + match simple { + Some((_, false)) => Err(not_simple(i, what, &name)), + Some((at, true)) => { + let grow = 96 + new.text().map_or(0, str::len); + change(i, o, grow, |m, _| { + if let Some(p) = m.props.get_mut(at) { + p.value = new; + } + }) + } + None => { + let prop = xmp::Prop { ns, name, value: new }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop)) + } + } + .map(|()| Value::Undefined) +} + +fn delete_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.deleteProperty"; + let o = this_meta(i, &this, what)?; + let (ns, name, step) = target(i, args, 0, what)?; + match step { + Step::Whole => { + let at = meta_of(i, o)?.find(&ns, &name); + if let Some(at) = at { + change(i, o, 0, |m, _| m.props.remove(at))?; + } + Ok(Value::Undefined) + } + Step::Item(index) => delete_item(i, o, &ns, &name, index, what, true), + } +} + +fn does_property_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.doesPropertyExist"; + let o = this_meta(i, &this, what)?; + let (ns, name, step) = target(i, args, 0, what)?; + let m = meta_of(i, o)?; + let exists = match (m.find(&ns, &name).map(|at| &m.props[at].value), step) { + (None, _) => false, + (Some(_), Step::Whole) => true, + (Some(xmp::Value::Array { items, .. }), Step::Item(index)) => position(index, items.len()).is_some(), + (Some(_), Step::Item(_)) => false, + }; + Ok(Value::Bool(exists)) +} + +/// The items of the array `name` in `ns` of `o`, `None` when it has no such property, refused when +/// the property is not an array. +fn array_items(i: &mut Interp, o: ObjId, ns: &str, name: &str, what: &str) -> JsResult> { + let found = { + let m = meta_of(i, o)?; + m.find(ns, name).map(|at| match &m.props[at].value { + xmp::Value::Array { form, items } => Some((at, *form, items.len())), + _ => None, + }) + }; + match found { + None => Ok(None), + Some(Some(a)) => Ok(Some(a)), + Some(None) => Err(not_array(i, what, name)), + } +} + +/// The array name argument at `at` after the namespace: a whole property. +fn array_target(i: &mut Interp, args: &[Value], what: &str) -> JsResult<(String, String)> { + let (ns, name, step) = target(i, args, 0, what)?; + if step != Step::Whole { + let path = text(i, &arg(args, 1))?; + return Err(not_handled(i, what, &path)); + } + Ok((ns, name)) +} + +fn count_array_items(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.countArrayItems"; + let o = this_meta(i, &this, what)?; + let (ns, name) = array_target(i, args, what)?; + let n = array_items(i, o, &ns, &name, what)?.map_or(0, |(_, _, len)| len); + Ok(Value::Number(n as f64)) +} + +fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.getArrayItem"; + let o = this_meta(i, &this, what)?; + let (ns, name) = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let Some((at, _, len)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + let Some(p) = position(index, len) else { return Ok(Value::Undefined) }; + let item = match &meta_of(i, o)?.props[at].value { + xmp::Value::Array { items, .. } => items.get(p).cloned(), + _ => None, + }; + let Some(item) = item else { return Ok(Value::Undefined) }; + let path = format!("{}[{}]", text(i, &arg(args, 1))?, p + 1); + property(i, &ns, &path, Some(&item.text), 0, item.lang.as_deref().unwrap_or("")) +} + +fn does_array_item_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.doesArrayItemExist"; + let o = this_meta(i, &this, what)?; + let (ns, name) = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let len = array_items(i, o, &ns, &name, what)?.map_or(0, |(_, _, len)| len); + Ok(Value::Bool(position(index, len).is_some())) +} + +/// The item options argument: 0 alone, for a simple item. +fn item_options(i: &mut Interp, v: &Value, what: &str) -> JsResult<()> { + let options = flags(i, v, what)?; + only(i, options, 0, what) +} + +/// Adds `value` to the array `name` in `ns` of `o` at the position `index` (from 1; one past the +/// last appends), making the array in `form` when it has none. +#[allow(clippy::too_many_arguments)] +fn insert_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: Option, value: String, form: Option
, what: &str) -> JsResult { + let found = array_items(i, o, ns, name, what)?; + let len = found.map_or(0, |(_, _, len)| len); + let p = match index { + None => len, + Some(-1) => len, + Some(n) => match usize::try_from(n) { + Ok(n) if (1..=len + 1).contains(&n) => n - 1, + _ => return Err(out_of_range(i, what, n)), + }, + }; + let grow = 48 + value.len(); + match found { + Some((at, _, _)) => change(i, o, grow, |m, _| { + if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) { + items.insert(p.min(items.len()), Item { text: value, lang: None }); + } + })?, + None => { + let Some(form) = form else { return Err(not_array(i, what, name)) }; + let prop = xmp::Prop { + ns: ns.to_string(), + name: name.to_string(), + value: xmp::Value::Array { form, items: vec![Item { text: value, lang: None }] }, + }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop))?; + } + } + Ok(Value::Undefined) +} + +/// Replaces the item at `index` of the array `name` in `ns` of `o` with `value`, or appends it at +/// one past the last when `append` allows. +#[allow(clippy::too_many_arguments)] +fn set_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: i64, value: String, append: bool, what: &str) -> JsResult { + let Some((at, _, len)) = array_items(i, o, ns, name, what)? else { return Err(not_array(i, what, name)) }; + let p = match position(index, len) { + Some(p) => p, + None if append && usize::try_from(index).is_ok_and(|n| n == len + 1) => { + return insert_item(i, o, ns, name, Some(index), value, None, what); + } + None => return Err(out_of_range(i, what, index)), + }; + let grow = 48 + value.len(); + change(i, o, grow, |m, _| { + if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) + && let Some(item) = items.get_mut(p) + { + item.text = value; + } + })?; + Ok(Value::Undefined) +} + +/// Deletes the item at `index` of the array `name` in `ns` of `o`; a missing item or array is left +/// as it is when `quiet`. +fn delete_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: i64, what: &str, quiet: bool) -> JsResult { + let found = array_items(i, o, ns, name, what)?; + let target = found.and_then(|(at, _, len)| position(index, len).map(|p| (at, p))); + match target { + Some((at, p)) => { + change(i, o, 0, |m, _| { + if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) + && p < items.len() + { + items.remove(p); + } + })?; + Ok(Value::Undefined) + } + None if quiet => Ok(Value::Undefined), + None => Err(out_of_range(i, what, index)), + } +} + +fn append_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.appendArrayItem"; + let o = this_meta(i, &this, what)?; + let (ns, name) = array_target(i, args, what)?; + // `itemOptions` may be left out: a string or `null` third argument is the item's value. + let (value, array_options) = match arg(args, 2) { + Value::Number(_) => { + item_options(i, &arg(args, 2), what)?; + (arg(args, 3), arg(args, 4)) + } + v => (v, arg(args, 3)), + }; + let array_options = flags(i, &array_options, what)?; + only(i, array_options, xmp::PROP_IS_ARRAY | xmp::ARRAY_IS_ORDERED | xmp::ARRAY_IS_ALTERNATIVE, what)?; + let value = if matches!(value, Value::Null | Value::Undefined) { String::new() } else { xml_text(i, &value, what)? }; + let form = (array_options != 0).then(|| Form::from_options(array_options)); + insert_item(i, o, &ns, &name, None, value, form, what) +} + +fn insert_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.insertArrayItem"; + let o = this_meta(i, &this, what)?; + let (ns, name) = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let value = xml_text(i, &arg(args, 3), what)?; + item_options(i, &arg(args, 4), what)?; + insert_item(i, o, &ns, &name, Some(index), value, None, what) +} + +fn set_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setArrayItem"; + let o = this_meta(i, &this, what)?; + let (ns, name) = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let value = xml_text(i, &arg(args, 3), what)?; + item_options(i, &arg(args, 4), what)?; + set_item(i, o, &ns, &name, index, value, true, what) +} + +fn delete_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.deleteArrayItem"; + let o = this_meta(i, &this, what)?; + let (ns, name) = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + delete_item(i, o, &ns, &name, index, what, false) +} + +/// Does language tag `lang` match `want`, ignoring case? +fn same_lang(lang: Option<&str>, want: &str) -> bool { + lang.is_some_and(|l| l.eq_ignore_ascii_case(want)) +} + +/// The item of `items` for `specific`, else one whose language starts with `generic`, else the +/// `x-default` item, else the first. +fn pick_lang<'a>(items: &'a [Item], generic: &str, specific: &str) -> Option<&'a Item> { + let generic_match = |i: &&Item| { + !generic.is_empty() + && i.lang.as_deref().is_some_and(|l| { + l.eq_ignore_ascii_case(generic) + || l.len() > generic.len() + && l.get(..generic.len()).is_some_and(|p| p.eq_ignore_ascii_case(generic)) + && l.as_bytes().get(generic.len()) == Some(&b'-') + }) + }; + items + .iter() + .find(|i| same_lang(i.lang.as_deref(), specific)) + .or_else(|| items.iter().find(generic_match)) + .or_else(|| items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default"))) + .or_else(|| items.first()) +} + +/// A language argument: `null` and `undefined` are empty. +fn lang(i: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Null | Value::Undefined) { Ok(String::new()) } else { xml_text(i, v, what) } +} + +fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.getLocalizedText"; + let o = this_meta(i, &this, what)?; + let (ns, name) = array_target(i, args, what)?; + let generic = lang(i, &arg(args, 2), what)?; + let specific = lang(i, &arg(args, 3), what)?; + let Some((at, form, _)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + if form != Form::Alt { + return Err(not_alt_text(i, what, &name)); + } + let found = match &meta_of(i, o)?.props[at].value { + xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific).map(|i| i.text.clone()), + _ => None, + }; + match found { + Some(t) => string(i, &t), + None => Ok(Value::Undefined), + } +} + +fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setLocalizedText"; + let o = this_meta(i, &this, what)?; + let (ns, name) = array_target(i, args, what)?; + let specific = lang(i, &arg(args, 3), what)?; + if specific.is_empty() || specific.contains(char::is_whitespace) { + return Err(not_handled(i, what, &specific)); + } + let value = xml_text(i, &arg(args, 4), what)?; + let found = array_items(i, o, &ns, &name, what)?; + let at = match found { + Some((_, form, _)) if form != Form::Alt => return Err(not_alt_text(i, what, &name)), + Some((at, _, _)) => at, + None => { + let prop = xmp::Prop { ns: ns.clone(), name: name.clone(), value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop))?; + meta_of(i, o)?.find(&ns, &name).unwrap_or(0) + } + }; + let grow = 2 * (64 + value.len() + specific.len()); + change(i, o, grow, |m, _| { + let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|p| &mut p.value) else { return }; + set_lang(items, &specific, value); + })?; + Ok(Value::Undefined) +} + +/// Sets the item of `items` in `specific` to `value`. VectorCraft's own rule: the `x-default` item +/// is first; it is added with the value when there is none, and follows a change to an item that +/// had the same text. +fn set_lang(items: &mut Vec, specific: &str, value: String) { + let default = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")); + if specific.eq_ignore_ascii_case("x-default") { + match default { + Some(d) => { + if let Some(item) = items.get_mut(d) { + item.text = value; + } + } + None => items.insert(0, Item { text: value, lang: Some("x-default".into()) }), + } + return; + } + let old = items.iter().position(|i| same_lang(i.lang.as_deref(), specific)); + let follows = match (old, default) { + (Some(o), Some(d)) => items.get(o).map(|i| &i.text) == items.get(d).map(|i| &i.text), + (None, Some(_)) => false, + (_, None) => true, + }; + match old { + Some(o) => { + if let Some(item) = items.get_mut(o) { + item.text.clone_from(&value); + } + } + None => items.push(Item { text: value.clone(), lang: Some(specific.to_string()) }), + } + match default { + Some(d) if follows => { + if let Some(item) = items.get_mut(d) { + item.text = value; + } + } + None => items.insert(0, Item { text: value, lang: Some("x-default".into()) }), + Some(_) => {} + } +} + +/// The packet `o` serializes to with the serialize options argument `v`. +fn serialized(i: &mut Interp, o: ObjId, v: &Value, what: &str) -> JsResult { + let options = flags(i, v, what)?; + only(i, options, SERIALIZE_OMIT_PACKET_WRAPPER, what)?; + let r = { + let Some(c) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; + xmp::serialize(meta_of(i, o)?, &c.registry, options & SERIALIZE_OMIT_PACKET_WRAPPER == 0) + }; + let s = r.map_err(|e| xmp_error(i, what, e, ""))?; + spend(i, s.len())?; + Ok(s) +} + +fn serialize(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.serialize"; + let o = this_meta(i, &this, what)?; + // Padding, indent, newline and base indent are not handled yet. + for (n, a) in args.iter().enumerate().skip(1) { + if !matches!(a, Value::Undefined) { + let name = ["", "padding", "indent", "newline", "baseIndent"].get(n).copied().unwrap_or("argument"); + return Err(not_yet(i, &format!("XMPMeta.serialize {name}"))); + } + } + let s = serialized(i, o, &arg(args, 0), what)?; + string(i, &s) +} + +fn register_namespace(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.registerNamespace"; + let uri = text(i, &arg(args, 0))?; + let prefix = text(i, &arg(args, 1))?; + let r = registry(i)?.register(&uri, &prefix); + match r { + Ok(p) => string(i, &format!("{p}:")), + Err(e) => Err(xmp_error(i, what, e, &prefix)), + } +} + +fn get_namespace_prefix(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let uri = text(i, &arg(args, 0))?; + let found = registry(i)?.prefix_of(&uri).map(|p| format!("{p}:")); + match found { + Some(p) => string(i, &p), + None => Ok(Value::Undefined), + } +} + +fn get_namespace_uri(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let prefix = text(i, &arg(args, 0))?; + let prefix = prefix.strip_suffix(':').unwrap_or(&prefix).to_string(); + let found = registry(i)?.uri_of(&prefix).map(str::to_string); + match found { + Some(u) => string(i, &u), + None => Ok(Value::Undefined), + } +} + +/// Defines functions that throw that they are not available yet. +macro_rules! not_yet_fns { + ($($f:ident => $name:literal,)*) => { + $(fn $f(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(not_yet(i, $name)) + })* + }; +} + +not_yet_fns! { + meta_iterator => "XMPMeta.iterator", + meta_serialize_to_array => "XMPMeta.serializeToArray", + meta_dump_object => "XMPMeta.dumpObject", + meta_sort => "XMPMeta.sort", + meta_get_struct_field => "XMPMeta.getStructField", + meta_set_struct_field => "XMPMeta.setStructField", + meta_delete_struct_field => "XMPMeta.deleteStructField", + meta_does_struct_field_exist => "XMPMeta.doesStructFieldExist", + meta_get_qualifier => "XMPMeta.getQualifier", + meta_set_qualifier => "XMPMeta.setQualifier", + meta_delete_qualifier => "XMPMeta.deleteQualifier", + meta_does_qualifier_exist => "XMPMeta.doesQualifierExist", + meta_dump_namespaces => "XMPMeta.dumpNamespaces", + meta_register_alias => "XMPMeta.registerAlias", + meta_resolve_alias => "XMPMeta.resolveAlias", + meta_dump_aliases => "XMPMeta.dumpAliases", + meta_delete_alias => "XMPMeta.deleteAlias", + meta_delete_namespace => "XMPMeta.deleteNamespace", + file_get_format_info => "XMPFile.getFormatInfo", +} + +// ---- XMPFile ---- + +/// The `XMPFile` `this`, refused when it is not one. +fn this_file(i: &mut Interp, this: &Value, what: &str) -> JsResult { + if let Some(o) = this.as_object() + && matches!(slot(i, o, PATH)?, Value::String(_)) + { + return Ok(o); + } + Err(wrong_object(i, what, "XMPFile")) +} + +/// The `XMPFile` `this` while it is open in this run, refused when it is closed. +fn open_file(i: &mut Interp, this: &Value, what: &str) -> JsResult { + let o = this_file(i, this, what)?; + let this_run = matches!(slot(i, o, RUN)?, Value::Number(n) if Some(n) == crate::file_classes::run_count(i)); + if !this_run || !slot(i, o, OPEN)?.truthy() { + return Err(i.throw(ErrorType::Error, &format!("{what}: the file is closed"))); + } + Ok(o) +} + +fn file_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile"; + if i.files.is_none() { + return Err(not_yet(i, "XMPFile without File and Folder")); + } + let format = match arg(args, 1) { + Value::Undefined | Value::Null => FILE_UNKNOWN, + v => flags(i, &v, what)?, + }; + if ![FILE_UNKNOWN, FILE_TEXT, FILE_XML].contains(&format) { + return Err(not_handled(i, what, &format!("0x{format:08X}"))); + } + let open_flags = flags(i, &arg(args, 2), what)?; + only(i, open_flags, OPEN_FOR_READ | OPEN_FOR_UPDATE | OPEN_ONLY_XMP | OPEN_USE_PACKET_SCANNING, what)?; + let update = open_flags & OPEN_FOR_UPDATE != 0; + let scan = open_flags & OPEN_USE_PACKET_SCANNING != 0; + let path = crate::file_classes::platform_path(i, &arg(args, 0))?; + let r = i.rooted(std::slice::from_ref(&path), |i| { + crate::file_classes::call_host(i, "xmpOpen", &[path.clone(), Value::Bool(update), Value::Bool(scan)]) + })?; + let keep = [path.clone(), r.clone()]; + i.rooted(&keep, |i| { + let error = crate::file_classes::record_field(i, &r, "error")?; + if let Value::String(_) = error { + let m = text(i, &error)?; + return Err(i.throw(ErrorType::Error, &m)); + } + let field = |i: &mut Interp, name: &str| crate::file_classes::record_field(i, &r, name); + let sidecar = field(i, "sidecar")?.truthy(); + let reported = if format == FILE_UNKNOWN && sidecar { FILE_XML } else { format }; + let file_proto = ids(i)?.file_proto; + i.reserve_heap(OBJECT_BYTES + 12 * PROP_BYTES)?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(file_proto))); + i.rooted(&[Value::Object(o)], |i| { + let packet = field(i, "packet")?; + let fields = [ + (PATH, path.clone()), + (FORMAT, Value::Number(f64::from(reported))), + (FLAGS, Value::Number(f64::from(open_flags))), + (RUN, crate::file_classes::run_count(i).map_or(Value::Undefined, Value::Number)), + (OPEN, Value::Bool(true)), + (PACKET, if matches!(packet, Value::String(_)) { packet } else { Value::Null }), + (OFFSET, field(i, "offset")?), + (LENGTH, field(i, "length")?), + (WRITEABLE, Value::Bool(field(i, "writeable")?.truthy())), + (SIDECAR, Value::Bool(sidecar)), + (CHAR_FORM, field(i, "charForm")?), + ]; + for (name, value) in fields { + set_slot(i, o, name, value)?; + } + Ok(Value::Object(o)) + }) + }) +} + +fn get_xmp(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let what = "XMPFile.getXMP"; + let o = open_file(i, &this, what)?; + let pending = slot(i, o, PENDING)?; + let packet = if matches!(pending, Value::String(_)) { pending } else { slot(i, o, PACKET)? }; + if !matches!(packet, Value::String(_)) { + return Ok(Value::Null); + } + let text = text(i, &packet)?; + let meta = if text.trim().is_empty() { Meta::default() } else { parse_packet(i, what, &text)? }; + new_meta(i, meta) +} + +fn get_packet_info(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let what = "XMPFile.getPacketInfo"; + let o = open_file(i, &this, what)?; + let packet = slot(i, o, PACKET)?; + if !matches!(packet, Value::String(_)) { + return Ok(Value::Null); + } + let char_form = slot(i, o, CHAR_FORM)?; + // The padding is counted in bytes: two for each character of a UTF-16 packet. + let unit = if matches!(char_form, Value::Number(n) if n == 2.0 || n == 3.0) { 2 } else { 1 }; + let pad = crate::xmp::pad_size(&text(i, &packet)?) * unit; + let fields = vec![ + ("charForm", char_form), + ("length", slot(i, o, LENGTH)?), + ("offset", slot(i, o, OFFSET)?), + ("packet", packet), + ("padSize", Value::Number(pad as f64)), + ("writeable", slot(i, o, WRITEABLE)?), + ]; + record(i, None, fields) +} + +fn get_file_info(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let what = "XMPFile.getFileInfo"; + let o = open_file(i, &this, what)?; + let fields = vec![ + ("filePath", slot(i, o, PATH)?), + ("format", slot(i, o, FORMAT)?), + ("handlerFlags", Value::Number(0.0)), + ("openFlags", slot(i, o, FLAGS)?), + ]; + record(i, None, fields) +} + +/// Can `o` take a packet: opened for update, and a `.xmp` file? +fn can_update(i: &Interp, o: ObjId) -> JsResult { + let open_flags = match slot(i, o, FLAGS)? { + Value::Number(n) => n as u32, + _ => 0, + }; + Ok(open_flags & OPEN_FOR_UPDATE != 0 && slot(i, o, SIDECAR)?.truthy()) +} + +/// The packet the argument `v` of `putXMP` or `canPutXMP` gives: an `XMPMeta` serialized with its +/// wrapper, or a string, which must be a packet that can be read. +fn packet_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { + if let Some(m) = is_meta(i, v) { + return serialized(i, m, &Value::Undefined, what); + } + if let Value::Object(o) = v + && matches!(i.heap.object(*o).map(|ob| &ob.class), Some(Class::Array { .. })) + { + return Err(not_yet(i, &format!("{what}(buffer)"))); + } + let s = text(i, v)?; + if s.len() > xmp::MAX_BYTES { + return Err(xmp_error(i, what, XmpError::TooLarge, "")); + } + // A packet is checked by reading it into a copy of the realm's namespaces, so checking it + // registers nothing. + let mut scratch = registry(i)?.clone(); + spend(i, s.len())?; + xmp::parse(&s, &mut scratch).map_err(|e| xmp_error(i, what, e, ""))?; + Ok(s) +} + +fn can_put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile.canPutXMP"; + let o = open_file(i, &this, what)?; + if !can_update(i, o)? { + return Ok(Value::Bool(false)); + } + let packet = packet_arg(i, &arg(args, 0), what); + match packet { + Ok(_) => Ok(Value::Bool(true)), + Err(Abrupt::Throw(_)) => Ok(Value::Bool(false)), + Err(e) => Err(e), + } +} + +fn put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile.putXMP"; + let o = open_file(i, &this, what)?; + if !can_update(i, o)? { + return Err(i.throw(ErrorType::Error, &format!("{what}: the file cannot be updated"))); + } + let packet = packet_arg(i, &arg(args, 0), what)?; + let v = string(i, &packet)?; + i.rooted(std::slice::from_ref(&v), |i| set_slot(i, o, PENDING, v.clone()))?; + Ok(Value::Undefined) +} + +fn close_file(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile.closeFile"; + let o = this_file(i, &this, what)?; + let close_flags = flags(i, &arg(args, 0), what)?; + only(i, close_flags, CLOSE_UPDATE_SAFELY, what)?; + let this_run = matches!(slot(i, o, RUN)?, Value::Number(n) if Some(n) == crate::file_classes::run_count(i)); + let pending = slot(i, o, PENDING)?; + if this_run && slot(i, o, OPEN)?.truthy() && matches!(pending, Value::String(_)) { + let path = slot(i, o, PATH)?; + let r = i.rooted(&[path.clone(), pending.clone()], |i| crate::file_classes::call_host(i, "xmpWrite", &[path.clone(), pending.clone()]))?; + let error = i.rooted(std::slice::from_ref(&r), |i| crate::file_classes::record_field(i, &r, "error"))?; + if let Value::String(_) = error { + // The file stays open with its packet, so a later `closeFile` tries again. + let m = text(i, &error)?; + return Err(i.throw(ErrorType::Error, &m)); + } + } + set_slot(i, o, PENDING, Value::Undefined)?; + set_slot(i, o, OPEN, Value::Bool(false))?; + Ok(Value::Undefined) +} + +// ---- install ---- + +/// A data property of `XMPConst`: read-only, enumerable. +fn constant(i: &mut Interp, on: ObjId, name: &str, value: Value) -> JsResult<()> { + data(i, on, name, value, ENUMERABLE) +} + +fn constants(i: &mut Interp) -> JsResult { + let o = i.new_object(); + i.rooted(&[Value::Object(o)], |i| { + let namespaces = [ + ("NS_DC", xmp::DC), + ("NS_RDF", xmp::RDF), + ("NS_XML", xmp::XML), + ("NS_XMP", xmp::XMP), + ("NS_XMP_RIGHTS", xmp::XMP_RIGHTS), + ("NS_PDF", xmp::PDF), + ("NS_PHOTOSHOP", xmp::PHOTOSHOP), // brand-ok: the constant's name in the reference + ]; + for (name, uri) in namespaces { + constant(i, o, name, Value::str(uri))?; + } + let numbers: [(&str, f64); 14] = [ + ("FILE_UNKNOWN", f64::from(FILE_UNKNOWN)), + ("FILE_TEXT", f64::from(FILE_TEXT)), + ("FILE_XML", f64::from(FILE_XML)), + ("OPEN_FOR_READ", f64::from(OPEN_FOR_READ)), + ("OPEN_FOR_UPDATE", f64::from(OPEN_FOR_UPDATE)), + ("OPEN_ONLY_XMP", f64::from(OPEN_ONLY_XMP)), + ("OPEN_USE_PACKET_SCANNING", f64::from(OPEN_USE_PACKET_SCANNING)), + ("CLOSE_UPDATE_SAFELY", f64::from(CLOSE_UPDATE_SAFELY)), + ("SERIALIZE_OMIT_PACKET_WRAPPER", f64::from(SERIALIZE_OMIT_PACKET_WRAPPER)), + ("PROP_IS_ARRAY", f64::from(xmp::PROP_IS_ARRAY)), + ("PROP_IS_STRUCT", f64::from(xmp::PROP_IS_STRUCT)), + ("ARRAY_IS_ORDERED", f64::from(xmp::ARRAY_IS_ORDERED)), + ("ARRAY_IS_ALTERNATIVE", f64::from(xmp::ARRAY_IS_ALTERNATIVE)), + ("ARRAY_LAST_ITEM", -1.0), + ]; + for (name, n) in numbers { + constant(i, o, name, Value::Number(n))?; + } + i.object_mut(o)?.extensible = false; + Ok(o) + }) +} + +fn meta_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + method(i, proto, "getProperty", get_property, 2)?; + method(i, proto, "setProperty", set_property, 3)?; + method(i, proto, "deleteProperty", delete_property, 2)?; + method(i, proto, "doesPropertyExist", does_property_exist, 2)?; + method(i, proto, "countArrayItems", count_array_items, 2)?; + method(i, proto, "getArrayItem", get_array_item, 3)?; + method(i, proto, "appendArrayItem", append_array_item, 3)?; + method(i, proto, "insertArrayItem", insert_array_item, 4)?; + method(i, proto, "setArrayItem", set_array_item, 4)?; + method(i, proto, "deleteArrayItem", delete_array_item, 3)?; + method(i, proto, "doesArrayItemExist", does_array_item_exist, 3)?; + method(i, proto, "getLocalizedText", get_localized_text, 4)?; + method(i, proto, "setLocalizedText", set_localized_text, 5)?; + method(i, proto, "serialize", serialize, 0)?; + method(i, proto, "iterator", meta_iterator, 0)?; + method(i, proto, "serializeToArray", meta_serialize_to_array, 0)?; + method(i, proto, "dumpObject", meta_dump_object, 0)?; + method(i, proto, "sort", meta_sort, 0)?; + method(i, proto, "getStructField", meta_get_struct_field, 4)?; + method(i, proto, "setStructField", meta_set_struct_field, 5)?; + method(i, proto, "deleteStructField", meta_delete_struct_field, 4)?; + method(i, proto, "doesStructFieldExist", meta_does_struct_field_exist, 4)?; + method(i, proto, "getQualifier", meta_get_qualifier, 4)?; + method(i, proto, "setQualifier", meta_set_qualifier, 5)?; + method(i, proto, "deleteQualifier", meta_delete_qualifier, 4)?; + method(i, proto, "doesQualifierExist", meta_does_qualifier_exist, 4)?; + method(i, ctor, "registerNamespace", register_namespace, 2)?; + method(i, ctor, "getNamespacePrefix", get_namespace_prefix, 1)?; + method(i, ctor, "getNamespaceURI", get_namespace_uri, 1)?; + method(i, ctor, "dumpNamespaces", meta_dump_namespaces, 0)?; + method(i, ctor, "registerAlias", meta_register_alias, 5)?; + method(i, ctor, "resolveAlias", meta_resolve_alias, 2)?; + method(i, ctor, "dumpAliases", meta_dump_aliases, 0)?; + method(i, ctor, "deleteAlias", meta_delete_alias, 2)?; + method(i, ctor, "deleteNamespace", meta_delete_namespace, 1) +} + +fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + method(i, proto, "getXMP", get_xmp, 0)?; + method(i, proto, "putXMP", put_xmp, 1)?; + method(i, proto, "canPutXMP", can_put_xmp, 1)?; + method(i, proto, "getPacketInfo", get_packet_info, 0)?; + method(i, proto, "getFileInfo", get_file_info, 0)?; + method(i, proto, "closeFile", close_file, 1)?; + method(i, ctor, "getFormatInfo", file_get_format_info, 1) +} + +/// Links the constructor `ctor` and its prototype `proto`, without making it a global. +fn link(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + data(i, ctor, "prototype", Value::Object(proto), 0)?; + data(i, proto, "constructor", Value::Object(ctor), HIDDEN) +} + +/// Adds the global `ExternalObject`, which defines `XMPMeta`, `XMPFile` and `XMPConst` when a +/// script loads the XMP library ([`crate::Realm::define_external_object`]). +pub(crate) fn install(i: &mut Interp) -> JsResult<()> { + let object_proto = i.intrinsics.object_proto; + i.reserve_heap(4 * OBJECT_BYTES)?; + let external_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let meta_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let file_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let property_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let keep = [external_proto, meta_proto, file_proto, property_proto].map(Value::Object); + i.rooted(&keep, |i| { + let meta = native(i, "XMPMeta", meta_ctor, 1, NativeKind::Plain, true)?; + i.rooted(&[Value::Object(meta)], |i| { + let file = native(i, "XMPFile", file_ctor, 3, NativeKind::Plain, true)?; + i.rooted(&[Value::Object(file)], |i| { + let constants = constants(i)?; + i.xmp = Some(Classes { + ids: Ids { external_proto, meta, meta_proto, file, file_proto, constants, property_proto }, + registry: Registry::default(), + }); + link(i, meta, meta_proto)?; + link(i, file, file_proto)?; + meta_members(i, meta, meta_proto)?; + file_members(i, file, file_proto)?; + method(i, property_proto, "toString", property_to_string, 0)?; + let external = native(i, "ExternalObject", external_ctor, 1, NativeKind::Plain, true)?; + crate::builtins::constructor(i, "ExternalObject", external, external_proto)?; + method(i, external, "search", external_search, 1)?; + method(i, external_proto, "terminate", external_terminate, 0) + }) + }) + }) +} diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs new file mode 100644 index 0000000000..5641ff77d7 --- /dev/null +++ b/crates/js/src/xmp_tests.rs @@ -0,0 +1,322 @@ +use proptest::prelude::*; + +use crate::xmp::{self, Form, Registry, XmpError}; +use crate::{JsValue, Limits, Realm, RunErrorKind}; + +fn realm() -> Realm { + let mut r = Realm::with_options(crate::Options::default(), Limits::default()); + if let Err(e) = r.define_external_object() { + panic!("{e:?}"); + } + r +} + +fn run(src: &str) -> JsValue { + match realm().run(&format!("new ExternalObject('lib:AdobeXMPScript');\n{src}")) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +/// The name and message of what `src` throws. +fn thrown(src: &str) -> String { + string(&format!("try {{ {src}; 'no error' }} catch (e) {{ e.name + ': ' + e.message }}")) +} + +const PACKET: &str = r#" + + + + HelloBonjour + onetwo + image/svg+xml + 1 + + + +"#; + +fn with_packet(src: &str) -> String { + format!("var m = new XMPMeta({:?});\n{src}", PACKET) +} + +#[test] +fn only_the_xmp_library_loads() { + let r = realm().run("typeof XMPMeta + ' ' + ExternalObject.search('lib:AdobeXMPScript') + ' ' + ExternalObject.search('lib:other')"); + assert_eq!(r.ok(), Some(JsValue::String("undefined true false".into()))); + let r = realm().run("try { new ExternalObject('lib:other') ; 'loaded' } catch (e) { e.name + ': ' + e.message + ' ' + typeof XMPMeta }"); + assert_eq!(r.ok(), Some(JsValue::String("Error: ExternalObject: the library lib:other is not available undefined".into()))); + truth("typeof XMPMeta == 'function' && typeof XMPFile == 'function' && XMPConst.ARRAY_LAST_ITEM == -1"); + truth("var h = new ExternalObject('lib:AdobeXMPScript'); h.terminate(); typeof XMPMeta == 'function'"); +} + +#[test] +fn a_packet_reads_into_properties() { + assert_eq!(string(&with_packet("m.getProperty(XMPConst.NS_DC, 'format').value")), "image/svg+xml"); + assert_eq!(string(&with_packet("String(m.getProperty(XMPConst.NS_XMP, 'xmp:CreatorTool'))")), "Tool & Co"); + assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'fr-FR')")), "Bonjour"); + assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'de-DE')")), "Hello"); + assert_eq!(string(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM).value")), "two"); + assert_eq!(run(&with_packet("m.countArrayItems(XMPConst.NS_DC, 'subject')")), JsValue::Number(2.0)); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'title').options")), JsValue::Number(f64::from(0x200 | 0x400 | 0x800 | 0x1000))); + assert_eq!(run(&with_packet("m.getProperty('http://example.com/ns/', 'thing').options")), JsValue::Number(256.0)); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'creator')")), JsValue::Undefined); + assert_eq!(string("XMPMeta.getNamespacePrefix('http://example.com/ns/') + ''"), "undefined"); + assert_eq!(string(&with_packet("XMPMeta.getNamespacePrefix('http://example.com/ns/')")), "ex:"); +} + +#[test] +fn properties_arrays_and_namespaces_round_trip() { + let src = "var ns = 'http://example.com/rt/'; + var p = XMPMeta.registerNamespace(ns, 'rt'); + var m = new XMPMeta(); + m.setProperty(ns, 'name', 'a & \"c\"'); + m.appendArrayItem(ns, 'list', 0, 'x', XMPConst.ARRAY_IS_ORDERED); + m.appendArrayItem(ns, 'list', 'y'); + m.insertArrayItem(ns, 'list', 1, 'w'); + m.setArrayItem(ns, 'list', 3, 'z'); + m.setLocalizedText(ns, 'label', null, 'en-US', 'Hi'); + m.setLocalizedText(ns, 'label', null, 'de-DE', 'Hallo'); + var n = new XMPMeta(m.serialize()); + var o = new XMPMeta(n.serialize(XMPConst.SERIALIZE_OMIT_PACKET_WRAPPER)); + [p, o.getProperty(ns, 'rt:name').value, o.getProperty(ns, 'list').options, o.countArrayItems(ns, 'list'), + o.getArrayItem(ns, 'list', 1).value, o.getArrayItem(ns, 'list', 2).value, o.getArrayItem(ns, 'list', 3).value, + o.getLocalizedText(ns, 'label', null, 'x-default'), o.getLocalizedText(ns, 'label', 'de', 'de-AT'), + m.serialize() == n.serialize(), n.serialize().indexOf(' & \"c\"|1536|3|w|x|z|Hi|Hallo|true|true|-1"); + let src = with_packet( + "var n = new XMPMeta(m.serialize()); n.serialize() == m.serialize() && n.getProperty('http://example.com/ns/', 'thing').options == 256 && n.getProperty(XMPConst.NS_XMP, 'CreatorTool').value == 'Tool & Co'", + ); + truth(&src); + truth(&with_packet( + "m.deleteProperty(XMPConst.NS_DC, 'format'); !m.doesPropertyExist(XMPConst.NS_DC, 'format') && m.doesPropertyExist(XMPConst.NS_DC, 'subject')", + )); + truth(&with_packet("m.deleteArrayItem(XMPConst.NS_DC, 'subject', 1); m.getArrayItem(XMPConst.NS_DC, 'subject', 1).value == 'two'")); + assert_eq!(string("XMPMeta.registerNamespace('http://example.com/a/', 'dc')"), "dc_1_:"); + assert_eq!(string("XMPMeta.getNamespaceURI('dc:')"), "http://purl.org/dc/elements/1.1/"); +} + +/// The prefix `xmlns` and the namespace of `xmlns` attributes are refused, so no packet declares +/// them. +#[test] +fn the_xmlns_prefix_and_namespace_are_refused() { + assert_eq!( + thrown("XMPMeta.registerNamespace('http://example.com/x/', 'xmlns')"), + "Error: XMPMeta.registerNamespace: xmlns is not a valid property name" + ); + assert_eq!( + thrown("XMPMeta.registerNamespace('http://www.w3.org/2000/xmlns/', 'ok')"), + "Error: XMPMeta.registerNamespace: ok is not a valid property name" + ); + truth("XMPMeta.getNamespaceURI('xmlns') === undefined && XMPMeta.getNamespacePrefix('http://www.w3.org/2000/xmlns/') === undefined"); +} + +#[test] +fn bad_arguments_and_unbuilt_members_throw() { + assert_eq!(thrown("new XMPMeta().getProperty('http://none/', 'a')"), "Error: XMPMeta.getProperty: the namespace http://none/ is not registered"); + assert_eq!(thrown("new XMPMeta().setProperty(XMPConst.NS_DC, '1a', 'x')"), "Error: XMPMeta.setProperty: 1a is not a valid property name"); + assert_eq!( + thrown("new XMPMeta().setProperty(XMPConst.NS_DC, 'a', 'x\\u0001')"), + "Error: XMPMeta.setProperty: the text holds a character XML does not allow" + ); + assert_eq!(thrown(&with_packet("m.setProperty(XMPConst.NS_DC, 'subject', 'x')")), "Error: XMPMeta.setProperty: subject is not a simple property"); + assert_eq!(thrown(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'format', 1)")), "Error: XMPMeta.getArrayItem: format is not an array"); + assert_eq!( + thrown(&with_packet("m.insertArrayItem(XMPConst.NS_DC, 'subject', 9, 'x')")), + "RangeError: XMPMeta.insertArrayItem: the array index 9 is out of range" + ); + assert_eq!( + thrown(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'subject', null, 'en')")), + "Error: XMPMeta.getLocalizedText: subject is not a language alternative array" + ); + assert_eq!( + thrown("new XMPMeta().getStructField(XMPConst.NS_DC, 'a', XMPConst.NS_DC, 'b')"), + "Error: XMPMeta.getStructField is not available yet" + ); + assert_eq!(thrown("new XMPMeta().getProperty(XMPConst.NS_DC, 'a/b')"), "RangeError: XMPMeta.getProperty: the value a/b is not available yet"); + assert_eq!( + thrown("XMPMeta.prototype.getProperty.call({}, XMPConst.NS_DC, 'a')"), + "TypeError: XMPMeta.getProperty: the object is not an XMPMeta object" + ); + assert_eq!( + thrown("new XMPFile('a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ)"), + "Error: XMPFile without File and Folder is not available yet" + ); +} + +#[test] +fn malformed_and_huge_packets_are_refused() { + let malformed = [ + "", + "", + "]>", + "&e;", + "", + "1", + ]; + for p in malformed { + assert_eq!(thrown(&format!("new XMPMeta({p:?})")), "Error: XMPMeta: the XMP packet is not well-formed XMP", "{p}"); + } + let deep = format!( + "{}{}", + "".repeat(200), + "".repeat(200) + ); + assert_eq!(xmp::parse(&deep, &mut Registry::default()), Err(XmpError::TooLarge)); + let huge = "x".repeat(xmp::MAX_BYTES + 1); + assert_eq!(xmp::parse(&huge, &mut Registry::default()), Err(XmpError::TooLarge)); + let r = realm().run("new ExternalObject('lib:AdobeXMPScript'); var s = 'xxxxxxxx'; while (s.length < 9000000) s += s; try { new XMPMeta(s); 'read' } catch (e) { e.name + ': ' + e.message }"); + assert_eq!(r.ok(), Some(JsValue::String("RangeError: XMPMeta: the XMP data is too large".into()))); +} + +#[test] +fn packets_are_found_in_file_bytes() { + let bytes = format!("binary\0\u{1}{PACKET}trailer"); + let span = xmp::find_packet(bytes.as_bytes()).map(|s| (s.start, s.end, s.writeable)); + assert_eq!(span, Some((8, 8 + PACKET.len(), true))); + assert_eq!(xmp::find_packet(b" no end"), None); + let read_only = PACKET.replace("end=\"w\"", "end=\"r\""); + assert_eq!(xmp::find_packet(read_only.as_bytes()).map(|s| s.writeable), Some(false)); + let stray = format!(" junk {PACKET}"); + let span = xmp::find_packet(stray.as_bytes()).map(|s| (s.start, s.end)); + assert_eq!(span, Some((stray.len() - PACKET.len(), stray.len())), "a start with no end of its own is skipped"); + let open_end = format!(" junk ", + "1", + ); + let o = string(&format!("String(new XMPMeta({packet:?}).getProperty(XMPConst.NS_DC, 'creator').options)")); + let o: u32 = o.parse().unwrap(); + assert_eq!((o & xmp::PROP_IS_ARRAY, o & xmp::ARRAY_IS_ORDERED, o & xmp::PROP_IS_STRUCT), (xmp::PROP_IS_ARRAY, xmp::ARRAY_IS_ORDERED, 0)); +} + +#[test] +fn many_properties_and_namespaces_each_read_once() { + let mut body = String::new(); + for n in 0..3000 { + body.push_str(&format!("v{n}", n % 500, n % 500, n % 500, n % 500)); + } + body.push_str("second"); + let packet = format!("{body}"); + let mut registry = Registry::default(); + let meta = xmp::parse(&packet, &mut registry).unwrap(); + assert_eq!(meta.props.len(), 3000); + let first = meta.find("http://n/0/", "p0").and_then(|at| meta.props.get(at)).and_then(|p| p.value.text()); + assert_eq!(first, Some("v0"), "a property given twice keeps its first value"); + assert_eq!(registry.prefix_of("http://n/499/"), Some("n499")); + let again = xmp::parse(&xmp::serialize(&meta, ®istry, false).unwrap(), &mut registry).unwrap(); + assert_eq!(again, meta); +} + +#[test] +fn blank_values_and_failed_packets_keep_their_state() { + let rdf = "\ + \n "; + let src = format!( + "new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta({rdf:?}); var n = new XMPMeta(m.serialize());\n\ + [n.getProperty('http://a/', 'p').value, n.getArrayItem('http://a/', 'q', 1).value].join('|')" + ); + assert_eq!(string(&src), " | \n "); + let bad = "\ + x"; + let src = format!( + "new ExternalObject('lib:AdobeXMPScript'); try {{ new XMPMeta({bad:?}); }} catch (e) {{}}\n\ + String(XMPMeta.getNamespacePrefix('http://b/'))" + ); + assert_eq!(string(&src), "undefined", "a packet that fails to read registers no namespace"); +} + +#[test] +fn array_forms_follow_their_options() { + assert_eq!(Form::from_options(0x200), Form::Bag); + assert_eq!(Form::from_options(0x400), Form::Seq); + assert_eq!(Form::from_options(0x800), Form::Alt); +} + +const PIECES: &[&str] = &[ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "1", + "text & more", + "&bogus;", + "]]>", + "", + "", + "", + "", + "", + "", +]; + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + /// Any arrangement of packet pieces reads without a panic, and what reads serializes to a packet + /// that reads back the same. + #[test] + fn arbitrary_packets_never_panic_and_round_trip(pieces in proptest::collection::vec(0..PIECES.len(), 0..24)) { + let text: String = pieces.iter().map(|&i| PIECES[i]).collect(); + let mut registry = Registry::default(); + if let Ok(meta) = xmp::parse(&text, &mut registry) { + let out = xmp::serialize(&meta, ®istry, true); + prop_assert!(out.is_ok(), "{text}"); + let out = out.unwrap_or_default(); + let again = xmp::parse(&out, &mut registry); + prop_assert_eq!(again.as_ref().ok(), Some(&meta), "{}\n{}", text, out); + } + } + + /// Arbitrary bytes never make the packet parser or scanner panic. + #[test] + fn arbitrary_bytes_never_panic(bytes in proptest::collection::vec(any::(), 0..512)) { + let _ = xmp::find_packet(&bytes); + let text = String::from_utf8_lossy(&bytes); + let _ = xmp::parse(&text, &mut Registry::default()); + } + + /// Arbitrary text through the script surface ends in a value or a script error, never an + /// internal fault. + #[test] + fn arbitrary_script_values_never_fault(name in "[a-z:\\[\\]0-9/@?]{0,12}", value in "\\PC{0,16}") { + let src = format!( + "new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta(); try {{ m.setProperty(XMPConst.NS_DC, {name:?}, {value:?}); \ + m.appendArrayItem(XMPConst.NS_DC, 'z', 0, {value:?}, XMPConst.PROP_IS_ARRAY); new XMPMeta(m.serialize()).getProperty(XMPConst.NS_DC, {name:?}) }} catch (e) {{ e.message }}" + ); + if let Err(e) = realm().run(&src) { + prop_assert!(e.kind != RunErrorKind::Internal, "{src}: {e:?}"); + } + } +} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..a931d02068 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6573,6 +6573,21 @@ liquify-list-end {0}, {1} {0} i {1} @msg the script passed more data to and from commands than one run may pass l'script ha passat més dades a les ordres i des de les ordres de les que pot passar una execució @msg the script added more objects and data to the documents than one run may add l'script ha afegit als documents més objectes i dades dels que pot afegir una execució @msg {what}: the object is not a File or a Folder {what}: l'objecte no és un File ni un Folder +@msg {what}: the library {name} is not available {what}: la biblioteca {name} no està disponible +@msg {what} is not available yet {what} encara no està disponible +@msg {what}: the value {value} is not available yet {what}: el valor {value} encara no està disponible +@msg {what}: the object is not an {class} object {what}: l'objecte no és un objecte {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: el paquet XMP no és XMP ben format +@msg {what}: the XMP data is too large {what}: les dades XMP són massa grans +@msg {what}: {name} is not a valid property name {what}: {name} no és un nom de propietat vàlid +@msg {what}: the text holds a character XML does not allow {what}: el text conté un caràcter que XML no permet +@msg {what}: {name} is not an array {what}: {name} no és una matriu +@msg {what}: {name} is not a simple property {what}: {name} no és una propietat simple +@msg {what}: {name} is not a language alternative array {what}: {name} no és una matriu d'alternatives d'idioma +@msg {what}: the array index {index} is out of range {what}: l'índex de matriu {index} és fora de l'interval +@msg {what}: the namespace {uri} is not registered {what}: l'espai de noms {uri} no està registrat +@msg {what}: the file is closed {what}: el fitxer està tancat +@msg {what}: the file cannot be updated {what}: el fitxer no es pot actualitzar @msg {what}: the count must be a finite number, 0 or more {what}: el recompte ha de ser un nombre finit, 0 o més @msg File.seek: the position must be a finite number File.seek: la posició ha de ser un nombre finit @msg File.seek: the mode must be 0, 1 or 2 File.seek: el mode ha de ser 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..e4c6c614ad 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5368,6 +5368,21 @@ liquify-list-end {0}, {1} {0} a {1} @msg the script passed more data to and from commands than one run may pass skript předal příkazům a z příkazů více dat, než smí předat jeden běh @msg the script added more objects and data to the documents than one run may add skript přidal do dokumentů více objektů a dat, než smí přidat jeden běh @msg {what}: the object is not a File or a Folder {what}: objekt není File ani Folder +@msg {what}: the library {name} is not available {what}: knihovna {name} není k dispozici +@msg {what} is not available yet {what} zatím není k dispozici +@msg {what}: the value {value} is not available yet {what}: hodnota {value} zatím není k dispozici +@msg {what}: the object is not an {class} object {what}: objekt není objekt {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: paket XMP není správně utvořené XMP +@msg {what}: the XMP data is too large {what}: data XMP jsou příliš velká +@msg {what}: {name} is not a valid property name {what}: {name} není platný název vlastnosti +@msg {what}: the text holds a character XML does not allow {what}: text obsahuje znak, který XML nepovoluje +@msg {what}: {name} is not an array {what}: {name} není pole +@msg {what}: {name} is not a simple property {what}: {name} není jednoduchá vlastnost +@msg {what}: {name} is not a language alternative array {what}: {name} není pole jazykových alternativ +@msg {what}: the array index {index} is out of range {what}: index pole {index} je mimo rozsah +@msg {what}: the namespace {uri} is not registered {what}: obor názvů {uri} není registrován +@msg {what}: the file is closed {what}: soubor je zavřený +@msg {what}: the file cannot be updated {what}: soubor nelze aktualizovat @msg {what}: the count must be a finite number, 0 or more {what}: počet musí být konečné číslo, 0 nebo více @msg File.seek: the position must be a finite number File.seek: pozice musí být konečné číslo @msg File.seek: the mode must be 0, 1 or 2 File.seek: režim musí být 0, 1 nebo 2 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..7c2c34978b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -216,6 +216,21 @@ liquify-list-end {0}, {1} {0} og {1} @msg the script passed more data to and from commands than one run may pass scriptet sendte flere data til og fra kommandoer, end én kørsel må sende @msg the script added more objects and data to the documents than one run may add scriptet tilføjede flere objekter og data til dokumenterne, end én kørsel må tilføje @msg {what}: the object is not a File or a Folder {what}: objektet er ikke en File eller en Folder +@msg {what}: the library {name} is not available {what}: biblioteket {name} er ikke tilgængeligt +@msg {what} is not available yet {what} er endnu ikke tilgængelig +@msg {what}: the value {value} is not available yet {what}: værdien {value} er endnu ikke tilgængelig +@msg {what}: the object is not an {class} object {what}: objektet er ikke et {class}-objekt +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-pakken er ikke velformet XMP +@msg {what}: the XMP data is too large {what}: XMP-dataene er for store +@msg {what}: {name} is not a valid property name {what}: {name} er ikke et gyldigt egenskabsnavn +@msg {what}: the text holds a character XML does not allow {what}: teksten indeholder et tegn, som XML ikke tillader +@msg {what}: {name} is not an array {what}: {name} er ikke en matrix +@msg {what}: {name} is not a simple property {what}: {name} er ikke en simpel egenskab +@msg {what}: {name} is not a language alternative array {what}: {name} er ikke en matrix af sprogalternativer +@msg {what}: the array index {index} is out of range {what}: matrixindekset {index} er uden for området +@msg {what}: the namespace {uri} is not registered {what}: navnerummet {uri} er ikke registreret +@msg {what}: the file is closed {what}: filen er lukket +@msg {what}: the file cannot be updated {what}: filen kan ikke opdateres @msg {what}: the count must be a finite number, 0 or more {what}: antallet skal være et endeligt tal, 0 eller mere @msg File.seek: the position must be a finite number File.seek: positionen skal være et endeligt tal @msg File.seek: the mode must be 0, 1 or 2 File.seek: tilstanden skal være 0, 1 eller 2 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..d36b965b27 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4953,6 +4953,21 @@ liquify-list-end {0}, {1} {0} und {1} @msg the script passed more data to and from commands than one run may pass das Skript hat mehr Daten an Befehle und von Befehlen übergeben, als ein Lauf übergeben darf @msg the script added more objects and data to the documents than one run may add das Skript hat den Dokumenten mehr Objekte und Daten hinzugefügt, als ein Lauf hinzufügen darf @msg {what}: the object is not a File or a Folder {what}: Das Objekt ist weder ein File noch ein Folder +@msg {what}: the library {name} is not available {what}: Die Bibliothek {name} ist nicht verfügbar +@msg {what} is not available yet {what} ist noch nicht verfügbar +@msg {what}: the value {value} is not available yet {what}: Der Wert {value} ist noch nicht verfügbar +@msg {what}: the object is not an {class} object {what}: Das Objekt ist kein {class}-Objekt +@msg {what}: the XMP packet is not well-formed XMP {what}: Das XMP-Paket ist kein wohlgeformtes XMP +@msg {what}: the XMP data is too large {what}: Die XMP-Daten sind zu groß +@msg {what}: {name} is not a valid property name {what}: {name} ist kein gültiger Eigenschaftsname +@msg {what}: the text holds a character XML does not allow {what}: Der Text enthält ein Zeichen, das XML nicht zulässt +@msg {what}: {name} is not an array {what}: {name} ist kein Array +@msg {what}: {name} is not a simple property {what}: {name} ist keine einfache Eigenschaft +@msg {what}: {name} is not a language alternative array {what}: {name} ist kein Array mit Sprachalternativen +@msg {what}: the array index {index} is out of range {what}: Der Array-Index {index} liegt außerhalb des Bereichs +@msg {what}: the namespace {uri} is not registered {what}: Der Namensraum {uri} ist nicht registriert +@msg {what}: the file is closed {what}: Die Datei ist geschlossen +@msg {what}: the file cannot be updated {what}: Die Datei kann nicht aktualisiert werden @msg {what}: the count must be a finite number, 0 or more {what}: Die Anzahl muss eine endliche Zahl sein, 0 oder mehr @msg File.seek: the position must be a finite number File.seek: Die Position muss eine endliche Zahl sein @msg File.seek: the mode must be 0, 1 or 2 File.seek: Der Modus muss 0, 1 oder 2 sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..ac46fef527 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2770,6 +2770,21 @@ liquify-list-end {0}, {1} {0} και {1} @msg the script passed more data to and from commands than one run may pass το σενάριο μετέφερε περισσότερα δεδομένα προς και από εντολές από όσα επιτρέπονται σε μία εκτέλεση @msg the script added more objects and data to the documents than one run may add το σενάριο πρόσθεσε στα έγγραφα περισσότερα αντικείμενα και δεδομένα από όσα επιτρέπονται σε μία εκτέλεση @msg {what}: the object is not a File or a Folder {what}: το αντικείμενο δεν είναι File ούτε Folder +@msg {what}: the library {name} is not available {what}: η βιβλιοθήκη {name} δεν είναι διαθέσιμη +@msg {what} is not available yet {what} δεν είναι ακόμη διαθέσιμο +@msg {what}: the value {value} is not available yet {what}: η τιμή {value} δεν είναι ακόμη διαθέσιμη +@msg {what}: the object is not an {class} object {what}: το αντικείμενο δεν είναι αντικείμενο {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: το πακέτο XMP δεν είναι σωστά διαμορφωμένο XMP +@msg {what}: the XMP data is too large {what}: τα δεδομένα XMP είναι πολύ μεγάλα +@msg {what}: {name} is not a valid property name {what}: το {name} δεν είναι έγκυρο όνομα ιδιότητας +@msg {what}: the text holds a character XML does not allow {what}: το κείμενο περιέχει χαρακτήρα που η XML δεν επιτρέπει +@msg {what}: {name} is not an array {what}: το {name} δεν είναι πίνακας +@msg {what}: {name} is not a simple property {what}: το {name} δεν είναι απλή ιδιότητα +@msg {what}: {name} is not a language alternative array {what}: το {name} δεν είναι πίνακας γλωσσικών εναλλακτικών +@msg {what}: the array index {index} is out of range {what}: ο δείκτης πίνακα {index} είναι εκτός εύρους +@msg {what}: the namespace {uri} is not registered {what}: ο χώρος ονομάτων {uri} δεν είναι καταχωρισμένος +@msg {what}: the file is closed {what}: το αρχείο είναι κλειστό +@msg {what}: the file cannot be updated {what}: το αρχείο δεν μπορεί να ενημερωθεί @msg {what}: the count must be a finite number, 0 or more {what}: το πλήθος πρέπει να είναι πεπερασμένος αριθμός, 0 ή περισσότερο @msg File.seek: the position must be a finite number File.seek: η θέση πρέπει να είναι πεπερασμένος αριθμός @msg File.seek: the mode must be 0, 1 or 2 File.seek: ο τρόπος πρέπει να είναι 0, 1 ή 2 diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..415b46a8b0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5045,6 +5045,21 @@ liquify-list-end {0}, {1} {0}, {1} @msg the script passed more data to and from commands than one run may pass el script pasó más datos a los comandos y desde ellos de los que puede pasar una ejecución @msg the script added more objects and data to the documents than one run may add el script añadió a los documentos más objetos y datos de los que puede añadir una ejecución @msg {what}: the object is not a File or a Folder {what}: el objeto no es un File ni un Folder +@msg {what}: the library {name} is not available {what}: la biblioteca {name} no está disponible +@msg {what} is not available yet {what} aún no está disponible +@msg {what}: the value {value} is not available yet {what}: el valor {value} aún no está disponible +@msg {what}: the object is not an {class} object {what}: el objeto no es un objeto {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: el paquete XMP no es XMP bien formado +@msg {what}: the XMP data is too large {what}: los datos XMP son demasiado grandes +@msg {what}: {name} is not a valid property name {what}: {name} no es un nombre de propiedad válido +@msg {what}: the text holds a character XML does not allow {what}: el texto contiene un carácter que XML no permite +@msg {what}: {name} is not an array {what}: {name} no es una matriz +@msg {what}: {name} is not a simple property {what}: {name} no es una propiedad simple +@msg {what}: {name} is not a language alternative array {what}: {name} no es una matriz de alternativas de idioma +@msg {what}: the array index {index} is out of range {what}: el índice de matriz {index} está fuera de rango +@msg {what}: the namespace {uri} is not registered {what}: el espacio de nombres {uri} no está registrado +@msg {what}: the file is closed {what}: el archivo está cerrado +@msg {what}: the file cannot be updated {what}: el archivo no se puede actualizar @msg {what}: the count must be a finite number, 0 or more {what}: la cantidad debe ser un número finito, 0 o más @msg File.seek: the position must be a finite number File.seek: la posición debe ser un número finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: el modo debe ser 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..ad7e813fe5 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5286,6 +5286,21 @@ liquify-list-end {0}, {1} {0} ja {1} @msg the script passed more data to and from commands than one run may pass skripti välitti komennoille ja komennoilta enemmän tietoa kuin yksi ajo saa välittää @msg the script added more objects and data to the documents than one run may add skripti lisäsi asiakirjoihin enemmän objekteja ja tietoja kuin yksi ajo saa lisätä @msg {what}: the object is not a File or a Folder {what}: objekti ei ole File eikä Folder +@msg {what}: the library {name} is not available {what}: kirjasto {name} ei ole käytettävissä +@msg {what} is not available yet {what} ei ole vielä käytettävissä +@msg {what}: the value {value} is not available yet {what}: arvo {value} ei ole vielä käytettävissä +@msg {what}: the object is not an {class} object {what}: objekti ei ole {class}-objekti +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-paketti ei ole hyvin muodostettua XMP:tä +@msg {what}: the XMP data is too large {what}: XMP-tiedot ovat liian suuret +@msg {what}: {name} is not a valid property name {what}: {name} ei ole kelvollinen ominaisuuden nimi +@msg {what}: the text holds a character XML does not allow {what}: teksti sisältää merkin, jota XML ei salli +@msg {what}: {name} is not an array {what}: {name} ei ole taulukko +@msg {what}: {name} is not a simple property {what}: {name} ei ole yksinkertainen ominaisuus +@msg {what}: {name} is not a language alternative array {what}: {name} ei ole kielivaihtoehtojen taulukko +@msg {what}: the array index {index} is out of range {what}: taulukon indeksi {index} on alueen ulkopuolella +@msg {what}: the namespace {uri} is not registered {what}: nimiavaruutta {uri} ei ole rekisteröity +@msg {what}: the file is closed {what}: tiedosto on suljettu +@msg {what}: the file cannot be updated {what}: tiedostoa ei voi päivittää @msg {what}: the count must be a finite number, 0 or more {what}: määrän on oltava äärellinen luku, 0 tai enemmän @msg File.seek: the position must be a finite number File.seek: sijainnin on oltava äärellinen luku @msg File.seek: the mode must be 0, 1 or 2 File.seek: tilan on oltava 0, 1 tai 2 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..40cd203c0e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5013,6 +5013,21 @@ liquify-list-end {0}, {1} {0} et {1} @msg the script made more host calls than one run may make le script a fait plus d’appels à l’hôte qu’une exécution ne peut en faire @msg the script passed more data to and from commands than one run may pass le script a transmis plus de données vers et depuis les commandes qu’une exécution ne peut en transmettre @msg the script added more objects and data to the documents than one run may add le script a ajouté aux documents plus d’objets et de données qu’une exécution ne peut en ajouter +@msg {what}: the library {name} is not available {what} : la bibliothèque {name} n’est pas disponible +@msg {what} is not available yet {what} n’est pas encore disponible +@msg {what}: the value {value} is not available yet {what} : la valeur {value} n’est pas encore disponible +@msg {what}: the object is not an {class} object {what} : l’objet n’est pas un objet {class} +@msg {what}: the XMP packet is not well-formed XMP {what} : le paquet XMP n’est pas du XMP bien formé +@msg {what}: the XMP data is too large {what} : les données XMP sont trop volumineuses +@msg {what}: {name} is not a valid property name {what} : {name} n’est pas un nom de propriété valide +@msg {what}: the text holds a character XML does not allow {what} : le texte contient un caractère que XML n’autorise pas +@msg {what}: {name} is not an array {what} : {name} n’est pas un tableau +@msg {what}: {name} is not a simple property {what} : {name} n’est pas une propriété simple +@msg {what}: {name} is not a language alternative array {what} : {name} n’est pas un tableau d’alternatives linguistiques +@msg {what}: the array index {index} is out of range {what} : l’index de tableau {index} est hors limites +@msg {what}: the namespace {uri} is not registered {what} : l’espace de noms {uri} n’est pas enregistré +@msg {what}: the file is closed {what} : le fichier est fermé +@msg {what}: the file cannot be updated {what} : le fichier ne peut pas être mis à jour @msg {what}: the object is not a File or a Folder {what} : l’objet n’est ni un File ni un Folder @msg {what}: the count must be a finite number, 0 or more {what} : le nombre doit être un nombre fini, 0 ou plus @msg File.seek: the position must be a finite number File.seek : la position doit être un nombre fini diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..331aa30575 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7719,6 +7719,21 @@ liquify-list-end {0}, {1} {0} और {1} @msg the script passed more data to and from commands than one run may pass स्क्रिप्ट ने कमांड को और कमांड से एक रन में अनुमत से अधिक डेटा भेजा @msg the script added more objects and data to the documents than one run may add स्क्रिप्ट ने दस्तावेज़ों में एक रन में अनुमत से अधिक ऑब्जेक्ट और डेटा जोड़े @msg {what}: the object is not a File or a Folder {what}: ऑब्जेक्ट न File है न Folder +@msg {what}: the library {name} is not available {what}: लाइब्रेरी {name} उपलब्ध नहीं है +@msg {what} is not available yet {what} अभी उपलब्ध नहीं है +@msg {what}: the value {value} is not available yet {what}: मान {value} अभी उपलब्ध नहीं है +@msg {what}: the object is not an {class} object {what}: ऑब्जेक्ट {class} ऑब्जेक्ट नहीं है +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP पैकेट सही ढंग से बना XMP नहीं है +@msg {what}: the XMP data is too large {what}: XMP डेटा बहुत बड़ा है +@msg {what}: {name} is not a valid property name {what}: {name} मान्य प्रॉपर्टी नाम नहीं है +@msg {what}: the text holds a character XML does not allow {what}: टेक्स्ट में ऐसा वर्ण है जिसकी XML अनुमति नहीं देता +@msg {what}: {name} is not an array {what}: {name} ऐरे नहीं है +@msg {what}: {name} is not a simple property {what}: {name} सरल प्रॉपर्टी नहीं है +@msg {what}: {name} is not a language alternative array {what}: {name} भाषा विकल्पों का ऐरे नहीं है +@msg {what}: the array index {index} is out of range {what}: ऐरे इंडेक्स {index} सीमा से बाहर है +@msg {what}: the namespace {uri} is not registered {what}: नेमस्पेस {uri} पंजीकृत नहीं है +@msg {what}: the file is closed {what}: फ़ाइल बंद है +@msg {what}: the file cannot be updated {what}: फ़ाइल अपडेट नहीं की जा सकती @msg {what}: the count must be a finite number, 0 or more {what}: गिनती एक सीमित संख्या होनी चाहिए, 0 या अधिक @msg File.seek: the position must be a finite number File.seek: स्थिति एक सीमित संख्या होनी चाहिए @msg File.seek: the mode must be 0, 1 or 2 File.seek: मोड 0, 1 या 2 होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..8171b8d3f6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5885,6 +5885,21 @@ liquify-list-end {0}, {1} {0} és {1} @msg the script passed more data to and from commands than one run may pass a parancsfájl több adatot adott át a parancsoknak és a parancsoktól, mint amennyit egy futás átadhat @msg the script added more objects and data to the documents than one run may add a parancsfájl több objektumot és adatot adott a dokumentumokhoz, mint amennyit egy futás hozzáadhat @msg {what}: the object is not a File or a Folder {what}: az objektum nem File és nem Folder +@msg {what}: the library {name} is not available {what}: a(z) {name} könyvtár nem érhető el +@msg {what} is not available yet {what} még nem érhető el +@msg {what}: the value {value} is not available yet {what}: a(z) {value} érték még nem érhető el +@msg {what}: the object is not an {class} object {what}: az objektum nem {class} objektum +@msg {what}: the XMP packet is not well-formed XMP {what}: az XMP-csomag nem jól formázott XMP +@msg {what}: the XMP data is too large {what}: az XMP-adatok túl nagyok +@msg {what}: {name} is not a valid property name {what}: a(z) {name} nem érvényes tulajdonságnév +@msg {what}: the text holds a character XML does not allow {what}: a szöveg olyan karaktert tartalmaz, amelyet az XML nem enged meg +@msg {what}: {name} is not an array {what}: a(z) {name} nem tömb +@msg {what}: {name} is not a simple property {what}: a(z) {name} nem egyszerű tulajdonság +@msg {what}: {name} is not a language alternative array {what}: a(z) {name} nem nyelvi alternatívák tömbje +@msg {what}: the array index {index} is out of range {what}: a(z) {index} tömbindex a tartományon kívül esik +@msg {what}: the namespace {uri} is not registered {what}: a(z) {uri} névtér nincs regisztrálva +@msg {what}: the file is closed {what}: a fájl be van zárva +@msg {what}: the file cannot be updated {what}: a fájl nem frissíthető @msg {what}: the count must be a finite number, 0 or more {what}: a darabszámnak véges számnak kell lennie, 0 vagy több @msg File.seek: the position must be a finite number File.seek: a pozíciónak véges számnak kell lennie @msg File.seek: the mode must be 0, 1 or 2 File.seek: a mód csak 0, 1 vagy 2 lehet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..4e1170ad31 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -159,6 +159,21 @@ @msg the script passed more data to and from commands than one run may pass skrip mengirim lebih banyak data ke dan dari perintah daripada yang boleh dikirim satu proses @msg the script added more objects and data to the documents than one run may add skrip menambahkan lebih banyak objek dan data ke dokumen daripada yang boleh ditambahkan satu proses @msg {what}: the object is not a File or a Folder {what}: objek bukan File atau Folder +@msg {what}: the library {name} is not available {what}: pustaka {name} tidak tersedia +@msg {what} is not available yet {what} belum tersedia +@msg {what}: the value {value} is not available yet {what}: nilai {value} belum tersedia +@msg {what}: the object is not an {class} object {what}: objek bukan objek {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: paket XMP bukan XMP yang tersusun dengan benar +@msg {what}: the XMP data is too large {what}: data XMP terlalu besar +@msg {what}: {name} is not a valid property name {what}: {name} bukan nama properti yang valid +@msg {what}: the text holds a character XML does not allow {what}: teks berisi karakter yang tidak diizinkan XML +@msg {what}: {name} is not an array {what}: {name} bukan larik +@msg {what}: {name} is not a simple property {what}: {name} bukan properti sederhana +@msg {what}: {name} is not a language alternative array {what}: {name} bukan larik alternatif bahasa +@msg {what}: the array index {index} is out of range {what}: indeks larik {index} di luar rentang +@msg {what}: the namespace {uri} is not registered {what}: ruang nama {uri} tidak terdaftar +@msg {what}: the file is closed {what}: berkas tertutup +@msg {what}: the file cannot be updated {what}: berkas tidak dapat diperbarui @msg {what}: the count must be a finite number, 0 or more {what}: jumlah harus berupa angka berhingga, 0 atau lebih @msg File.seek: the position must be a finite number File.seek: posisi harus berupa angka berhingga @msg File.seek: the mode must be 0, 1 or 2 File.seek: mode harus 0, 1 atau 2 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..3638fab939 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5091,6 +5091,21 @@ liquify-list-end {0}, {1} {0} e {1} @msg the script passed more data to and from commands than one run may pass lo script ha passato ai comandi e dai comandi più dati di quanti ne possa passare un'esecuzione @msg the script added more objects and data to the documents than one run may add lo script ha aggiunto ai documenti più oggetti e dati di quanti ne possa aggiungere un'esecuzione @msg {what}: the object is not a File or a Folder {what}: l'oggetto non è un File né un Folder +@msg {what}: the library {name} is not available {what}: la libreria {name} non è disponibile +@msg {what} is not available yet {what} non è ancora disponibile +@msg {what}: the value {value} is not available yet {what}: il valore {value} non è ancora disponibile +@msg {what}: the object is not an {class} object {what}: l'oggetto non è un oggetto {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: il pacchetto XMP non è XMP ben formato +@msg {what}: the XMP data is too large {what}: i dati XMP sono troppo grandi +@msg {what}: {name} is not a valid property name {what}: {name} non è un nome di proprietà valido +@msg {what}: the text holds a character XML does not allow {what}: il testo contiene un carattere che XML non consente +@msg {what}: {name} is not an array {what}: {name} non è un array +@msg {what}: {name} is not a simple property {what}: {name} non è una proprietà semplice +@msg {what}: {name} is not a language alternative array {what}: {name} non è un array di alternative di lingua +@msg {what}: the array index {index} is out of range {what}: l'indice di array {index} è fuori intervallo +@msg {what}: the namespace {uri} is not registered {what}: lo spazio dei nomi {uri} non è registrato +@msg {what}: the file is closed {what}: il file è chiuso +@msg {what}: the file cannot be updated {what}: il file non può essere aggiornato @msg {what}: the count must be a finite number, 0 or more {what}: il conteggio deve essere un numero finito, 0 o più @msg File.seek: the position must be a finite number File.seek: la posizione deve essere un numero finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: la modalità deve essere 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..d40d4202d1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5917,6 +5917,21 @@ liquify-list-end {0}, {1} {0}、{1} @msg the script passed more data to and from commands than one run may pass スクリプトが 1 回の実行で許されるより多くのデータをコマンドとやり取りしました @msg the script added more objects and data to the documents than one run may add スクリプトが 1 回の実行で許されるより多くのオブジェクトとデータをドキュメントに追加しました @msg {what}: the object is not a File or a Folder {what}: オブジェクトは File でも Folder でもありません +@msg {what}: the library {name} is not available {what}: ライブラリ {name} は利用できません +@msg {what} is not available yet {what} はまだ利用できません +@msg {what}: the value {value} is not available yet {what}: 値 {value} はまだ利用できません +@msg {what}: the object is not an {class} object {what}: オブジェクトは {class} オブジェクトではありません +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP パケットが整形式の XMP ではありません +@msg {what}: the XMP data is too large {what}: XMP データが大きすぎます +@msg {what}: {name} is not a valid property name {what}: {name} は有効なプロパティ名ではありません +@msg {what}: the text holds a character XML does not allow {what}: テキストに XML で使えない文字が含まれています +@msg {what}: {name} is not an array {what}: {name} は配列ではありません +@msg {what}: {name} is not a simple property {what}: {name} は単純なプロパティではありません +@msg {what}: {name} is not a language alternative array {what}: {name} は言語の代替配列ではありません +@msg {what}: the array index {index} is out of range {what}: 配列のインデックス {index} が範囲外です +@msg {what}: the namespace {uri} is not registered {what}: 名前空間 {uri} は登録されていません +@msg {what}: the file is closed {what}: ファイルは閉じています +@msg {what}: the file cannot be updated {what}: ファイルを更新できません @msg {what}: the count must be a finite number, 0 or more {what}: 数は 0 以上の有限の数値にしてください @msg File.seek: the position must be a finite number File.seek: 位置は有限の数値にしてください @msg File.seek: the mode must be 0, 1 or 2 File.seek: モードは 0, 1 または 2 にしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..48372764c1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8586,6 +8586,21 @@ liquify-list-end {0}, {1} {0} და {1} @msg the script passed more data to and from commands than one run may pass სკრიპტმა ბრძანებებს და ბრძანებებიდან იმაზე მეტი მონაცემი გადასცა, ვიდრე ერთ გაშვებას შეუძლია @msg the script added more objects and data to the documents than one run may add სკრიპტმა დოკუმენტებს იმაზე მეტი ობიექტი და მონაცემი დაამატა, ვიდრე ერთ გაშვებას შეუძლია @msg {what}: the object is not a File or a Folder {what}: ობიექტი არც File-ია და არც Folder +@msg {what}: the library {name} is not available {what}: ბიბლიოთეკა {name} მიუწვდომელია +@msg {what} is not available yet {what} ჯერ მიუწვდომელია +@msg {what}: the value {value} is not available yet {what}: მნიშვნელობა {value} ჯერ მიუწვდომელია +@msg {what}: the object is not an {class} object {what}: ობიექტი არ არის {class} ობიექტი +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP პაკეტი არ არის სწორად აგებული XMP +@msg {what}: the XMP data is too large {what}: XMP მონაცემები ზედმეტად დიდია +@msg {what}: {name} is not a valid property name {what}: {name} არ არის თვისების სწორი სახელი +@msg {what}: the text holds a character XML does not allow {what}: ტექსტი შეიცავს სიმბოლოს, რომელსაც XML არ უშვებს +@msg {what}: {name} is not an array {what}: {name} არ არის მასივი +@msg {what}: {name} is not a simple property {what}: {name} არ არის მარტივი თვისება +@msg {what}: {name} is not a language alternative array {what}: {name} არ არის ენობრივი ალტერნატივების მასივი +@msg {what}: the array index {index} is out of range {what}: მასივის ინდექსი {index} დიაპაზონს გარეთაა +@msg {what}: the namespace {uri} is not registered {what}: სახელთა სივრცე {uri} არ არის რეგისტრირებული +@msg {what}: the file is closed {what}: ფაილი დახურულია +@msg {what}: the file cannot be updated {what}: ფაილის განახლება შეუძლებელია @msg {what}: the count must be a finite number, 0 or more {what}: რაოდენობა უნდა იყოს სასრული რიცხვი, 0 ან მეტი @msg File.seek: the position must be a finite number File.seek: პოზიცია უნდა იყოს სასრული რიცხვი @msg File.seek: the mode must be 0, 1 or 2 File.seek: რეჟიმი უნდა იყოს 0, 1 ან 2 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..3e85928817 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5846,6 +5846,21 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg the script passed more data to and from commands than one run may pass 스크립트가 한 번의 실행에 허용된 것보다 많은 데이터를 명령과 주고받았습니다 @msg the script added more objects and data to the documents than one run may add 스크립트가 한 번의 실행에 허용된 것보다 많은 객체와 데이터를 문서에 추가했습니다 @msg {what}: the object is not a File or a Folder {what}: 객체가 File도 Folder도 아닙니다 +@msg {what}: the library {name} is not available {what}: 라이브러리 {name}을(를) 사용할 수 없습니다 +@msg {what} is not available yet {what}은(는) 아직 사용할 수 없습니다 +@msg {what}: the value {value} is not available yet {what}: 값 {value}은(는) 아직 사용할 수 없습니다 +@msg {what}: the object is not an {class} object {what}: 객체가 {class} 객체가 아닙니다 +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP 패킷이 올바른 형식의 XMP가 아닙니다 +@msg {what}: the XMP data is too large {what}: XMP 데이터가 너무 큽니다 +@msg {what}: {name} is not a valid property name {what}: {name}은(는) 올바른 속성 이름이 아닙니다 +@msg {what}: the text holds a character XML does not allow {what}: 텍스트에 XML이 허용하지 않는 문자가 있습니다 +@msg {what}: {name} is not an array {what}: {name}은(는) 배열이 아닙니다 +@msg {what}: {name} is not a simple property {what}: {name}은(는) 단순 속성이 아닙니다 +@msg {what}: {name} is not a language alternative array {what}: {name}은(는) 언어 대체 배열이 아닙니다 +@msg {what}: the array index {index} is out of range {what}: 배열 인덱스 {index}이(가) 범위를 벗어났습니다 +@msg {what}: the namespace {uri} is not registered {what}: 네임스페이스 {uri}이(가) 등록되지 않았습니다 +@msg {what}: the file is closed {what}: 파일이 닫혀 있습니다 +@msg {what}: the file cannot be updated {what}: 파일을 업데이트할 수 없습니다 @msg {what}: the count must be a finite number, 0 or more {what}: 개수는 0 이상의 유한한 숫자여야 합니다 @msg File.seek: the position must be a finite number File.seek: 위치는 유한한 숫자여야 합니다 @msg File.seek: the mode must be 0, 1 or 2 File.seek: 모드는 0, 1 또는 2여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..b23412f1ec 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -205,6 +205,21 @@ liquify-list-end {0}, {1} {0} en {1} @msg the script passed more data to and from commands than one run may pass het script heeft meer gegevens van en naar opdrachten doorgegeven dan één uitvoering mag doorgeven @msg the script added more objects and data to the documents than one run may add het script heeft meer objecten en gegevens aan de documenten toegevoegd dan één uitvoering mag toevoegen @msg {what}: the object is not a File or a Folder {what}: het object is geen File of Folder +@msg {what}: the library {name} is not available {what}: de bibliotheek {name} is niet beschikbaar +@msg {what} is not available yet {what} is nog niet beschikbaar +@msg {what}: the value {value} is not available yet {what}: de waarde {value} is nog niet beschikbaar +@msg {what}: the object is not an {class} object {what}: het object is geen {class}-object +@msg {what}: the XMP packet is not well-formed XMP {what}: het XMP-pakket is geen goed gevormde XMP +@msg {what}: the XMP data is too large {what}: de XMP-gegevens zijn te groot +@msg {what}: {name} is not a valid property name {what}: {name} is geen geldige eigenschapsnaam +@msg {what}: the text holds a character XML does not allow {what}: de tekst bevat een teken dat XML niet toestaat +@msg {what}: {name} is not an array {what}: {name} is geen array +@msg {what}: {name} is not a simple property {what}: {name} is geen eenvoudige eigenschap +@msg {what}: {name} is not a language alternative array {what}: {name} is geen array van taalalternatieven +@msg {what}: the array index {index} is out of range {what}: de array-index {index} valt buiten het bereik +@msg {what}: the namespace {uri} is not registered {what}: de naamruimte {uri} is niet geregistreerd +@msg {what}: the file is closed {what}: het bestand is gesloten +@msg {what}: the file cannot be updated {what}: het bestand kan niet worden bijgewerkt @msg {what}: the count must be a finite number, 0 or more {what}: het aantal moet een eindig getal zijn, 0 of meer @msg File.seek: the position must be a finite number File.seek: de positie moet een eindig getal zijn @msg File.seek: the mode must be 0, 1 or 2 File.seek: de modus moet 0, 1 of 2 zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..d12a0430d9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5196,6 +5196,21 @@ liquify-list-end {0}, {1} {0} i {1} @msg the script passed more data to and from commands than one run may pass skrypt przekazał do poleceń i z poleceń więcej danych, niż może przekazać jedno uruchomienie @msg the script added more objects and data to the documents than one run may add skrypt dodał do dokumentów więcej obiektów i danych, niż może dodać jedno uruchomienie @msg {what}: the object is not a File or a Folder {what}: obiekt nie jest ani File, ani Folder +@msg {what}: the library {name} is not available {what}: biblioteka {name} jest niedostępna +@msg {what} is not available yet {what} nie jest jeszcze dostępne +@msg {what}: the value {value} is not available yet {what}: wartość {value} nie jest jeszcze dostępna +@msg {what}: the object is not an {class} object {what}: obiekt nie jest obiektem {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: pakiet XMP nie jest poprawnie zbudowanym XMP +@msg {what}: the XMP data is too large {what}: dane XMP są za duże +@msg {what}: {name} is not a valid property name {what}: {name} nie jest prawidłową nazwą właściwości +@msg {what}: the text holds a character XML does not allow {what}: tekst zawiera znak niedozwolony w XML +@msg {what}: {name} is not an array {what}: {name} nie jest tablicą +@msg {what}: {name} is not a simple property {what}: {name} nie jest prostą właściwością +@msg {what}: {name} is not a language alternative array {what}: {name} nie jest tablicą alternatyw językowych +@msg {what}: the array index {index} is out of range {what}: indeks tablicy {index} jest poza zakresem +@msg {what}: the namespace {uri} is not registered {what}: przestrzeń nazw {uri} nie jest zarejestrowana +@msg {what}: the file is closed {what}: plik jest zamknięty +@msg {what}: the file cannot be updated {what}: nie można zaktualizować pliku @msg {what}: the count must be a finite number, 0 or more {what}: liczba musi być liczbą skończoną, 0 lub większą @msg File.seek: the position must be a finite number File.seek: pozycja musi być liczbą skończoną @msg File.seek: the mode must be 0, 1 or 2 File.seek: tryb musi wynosić 0, 1 lub 2 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..868a243cef 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6235,6 +6235,21 @@ liquify-list-end {0}, {1} {0} e {1} @msg the script passed more data to and from commands than one run may pass o script passou mais dados para os comandos e a partir deles do que uma execução pode passar @msg the script added more objects and data to the documents than one run may add o script adicionou aos documentos mais objetos e dados do que uma execução pode adicionar @msg {what}: the object is not a File or a Folder {what}: o objeto não é um File nem um Folder +@msg {what}: the library {name} is not available {what}: a biblioteca {name} não está disponível +@msg {what} is not available yet {what} ainda não está disponível +@msg {what}: the value {value} is not available yet {what}: o valor {value} ainda não está disponível +@msg {what}: the object is not an {class} object {what}: o objeto não é um objeto {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: o pacote XMP não é um XMP bem formado +@msg {what}: the XMP data is too large {what}: os dados XMP são grandes demais +@msg {what}: {name} is not a valid property name {what}: {name} não é um nome de propriedade válido +@msg {what}: the text holds a character XML does not allow {what}: o texto contém um caractere que o XML não permite +@msg {what}: {name} is not an array {what}: {name} não é uma matriz +@msg {what}: {name} is not a simple property {what}: {name} não é uma propriedade simples +@msg {what}: {name} is not a language alternative array {what}: {name} não é uma matriz de alternativas de idioma +@msg {what}: the array index {index} is out of range {what}: o índice de matriz {index} está fora do intervalo +@msg {what}: the namespace {uri} is not registered {what}: o namespace {uri} não está registrado +@msg {what}: the file is closed {what}: o arquivo está fechado +@msg {what}: the file cannot be updated {what}: o arquivo não pode ser atualizado @msg {what}: the count must be a finite number, 0 or more {what}: a contagem deve ser um número finito, 0 ou mais @msg File.seek: the position must be a finite number File.seek: a posição deve ser um número finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: o modo deve ser 0, 1 ou 2 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..9af201db91 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5067,6 +5067,21 @@ liquify-list-end {0}, {1} {0} и {1} @msg the script passed more data to and from commands than one run may pass скрипт передал командам и получил от них больше данных, чем разрешено одному запуску @msg the script added more objects and data to the documents than one run may add скрипт добавил в документы больше объектов и данных, чем разрешено одному запуску @msg {what}: the object is not a File or a Folder {what}: объект не является ни File, ни Folder +@msg {what}: the library {name} is not available {what}: библиотека {name} недоступна +@msg {what} is not available yet {what} пока недоступно +@msg {what}: the value {value} is not available yet {what}: значение {value} пока недоступно +@msg {what}: the object is not an {class} object {what}: объект не является объектом {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: пакет XMP не является правильно построенным XMP +@msg {what}: the XMP data is too large {what}: данные XMP слишком велики +@msg {what}: {name} is not a valid property name {what}: {name} не является допустимым именем свойства +@msg {what}: the text holds a character XML does not allow {what}: текст содержит символ, недопустимый в XML +@msg {what}: {name} is not an array {what}: {name} не является массивом +@msg {what}: {name} is not a simple property {what}: {name} не является простым свойством +@msg {what}: {name} is not a language alternative array {what}: {name} не является массивом языковых вариантов +@msg {what}: the array index {index} is out of range {what}: индекс массива {index} вне диапазона +@msg {what}: the namespace {uri} is not registered {what}: пространство имен {uri} не зарегистрировано +@msg {what}: the file is closed {what}: файл закрыт +@msg {what}: the file cannot be updated {what}: файл нельзя обновить @msg {what}: the count must be a finite number, 0 or more {what}: количество должно быть конечным числом, 0 или больше @msg File.seek: the position must be a finite number File.seek: позиция должна быть конечным числом @msg File.seek: the mode must be 0, 1 or 2 File.seek: режим должен быть 0, 1 или 2 diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..c69017b569 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4942,6 +4942,21 @@ liquify-list-end {0}, {1} {0} och {1} @msg the script passed more data to and from commands than one run may pass skriptet skickade mer data till och från kommandon än en körning får skicka @msg the script added more objects and data to the documents than one run may add skriptet lade till fler objekt och mer data i dokumenten än en körning får lägga till @msg {what}: the object is not a File or a Folder {what}: objektet är varken en File eller en Folder +@msg {what}: the library {name} is not available {what}: biblioteket {name} är inte tillgängligt +@msg {what} is not available yet {what} är inte tillgängligt än +@msg {what}: the value {value} is not available yet {what}: värdet {value} är inte tillgängligt än +@msg {what}: the object is not an {class} object {what}: objektet är inte ett {class}-objekt +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-paketet är inte välformad XMP +@msg {what}: the XMP data is too large {what}: XMP-data är för stora +@msg {what}: {name} is not a valid property name {what}: {name} är inte ett giltigt egenskapsnamn +@msg {what}: the text holds a character XML does not allow {what}: texten innehåller ett tecken som XML inte tillåter +@msg {what}: {name} is not an array {what}: {name} är inte en matris +@msg {what}: {name} is not a simple property {what}: {name} är inte en enkel egenskap +@msg {what}: {name} is not a language alternative array {what}: {name} är inte en matris med språkalternativ +@msg {what}: the array index {index} is out of range {what}: matrisindexet {index} ligger utanför intervallet +@msg {what}: the namespace {uri} is not registered {what}: namnrymden {uri} är inte registrerad +@msg {what}: the file is closed {what}: filen är stängd +@msg {what}: the file cannot be updated {what}: filen kan inte uppdateras @msg {what}: the count must be a finite number, 0 or more {what}: antalet måste vara ett ändligt tal, 0 eller mer @msg File.seek: the position must be a finite number File.seek: positionen måste vara ett ändligt tal @msg File.seek: the mode must be 0, 1 or 2 File.seek: läget måste vara 0, 1 eller 2 diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..59fa066b58 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4789,6 +4789,21 @@ liquify-list-end {0}, {1} {0} ve {1} @msg the script passed more data to and from commands than one run may pass betik, komutlara ve komutlardan bir çalıştırmanın aktarabileceğinden daha fazla veri aktardı @msg the script added more objects and data to the documents than one run may add betik, belgelere bir çalıştırmanın ekleyebileceğinden daha fazla nesne ve veri ekledi @msg {what}: the object is not a File or a Folder {what}: nesne ne File ne de Folder +@msg {what}: the library {name} is not available {what}: {name} kitaplığı kullanılamıyor +@msg {what} is not available yet {what} henüz kullanılamıyor +@msg {what}: the value {value} is not available yet {what}: {value} değeri henüz kullanılamıyor +@msg {what}: the object is not an {class} object {what}: nesne bir {class} nesnesi değil +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP paketi düzgün biçimli XMP değil +@msg {what}: the XMP data is too large {what}: XMP verileri çok büyük +@msg {what}: {name} is not a valid property name {what}: {name} geçerli bir özellik adı değil +@msg {what}: the text holds a character XML does not allow {what}: metin XML'in izin vermediği bir karakter içeriyor +@msg {what}: {name} is not an array {what}: {name} bir dizi değil +@msg {what}: {name} is not a simple property {what}: {name} basit bir özellik değil +@msg {what}: {name} is not a language alternative array {what}: {name} bir dil alternatifleri dizisi değil +@msg {what}: the array index {index} is out of range {what}: {index} dizi dizini aralık dışında +@msg {what}: the namespace {uri} is not registered {what}: {uri} ad alanı kayıtlı değil +@msg {what}: the file is closed {what}: dosya kapalı +@msg {what}: the file cannot be updated {what}: dosya güncellenemiyor @msg {what}: the count must be a finite number, 0 or more {what}: sayı 0 veya daha büyük, sonlu bir sayı olmalıdır @msg File.seek: the position must be a finite number File.seek: konum sonlu bir sayı olmalıdır @msg File.seek: the mode must be 0, 1 or 2 File.seek: mod 0, 1 veya 2 olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..dcde17615c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5075,6 +5075,21 @@ liquify-list-end {0}, {1} {0} і {1} @msg the script passed more data to and from commands than one run may pass скрипт передав командам і отримав від них більше даних, ніж дозволено одному запуску @msg the script added more objects and data to the documents than one run may add скрипт додав до документів більше об'єктів і даних, ніж дозволено одному запуску @msg {what}: the object is not a File or a Folder {what}: об'єкт не є ні File, ні Folder +@msg {what}: the library {name} is not available {what}: бібліотека {name} недоступна +@msg {what} is not available yet {what} поки що недоступне +@msg {what}: the value {value} is not available yet {what}: значення {value} поки що недоступне +@msg {what}: the object is not an {class} object {what}: об'єкт не є об'єктом {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: пакет XMP не є правильно побудованим XMP +@msg {what}: the XMP data is too large {what}: дані XMP завеликі +@msg {what}: {name} is not a valid property name {what}: {name} не є допустимою назвою властивості +@msg {what}: the text holds a character XML does not allow {what}: текст містить символ, який XML не дозволяє +@msg {what}: {name} is not an array {what}: {name} не є масивом +@msg {what}: {name} is not a simple property {what}: {name} не є простою властивістю +@msg {what}: {name} is not a language alternative array {what}: {name} не є масивом мовних варіантів +@msg {what}: the array index {index} is out of range {what}: індекс масиву {index} поза діапазоном +@msg {what}: the namespace {uri} is not registered {what}: простір імен {uri} не зареєстровано +@msg {what}: the file is closed {what}: файл закрито +@msg {what}: the file cannot be updated {what}: файл неможливо оновити @msg {what}: the count must be a finite number, 0 or more {what}: кількість має бути скінченним числом, 0 або більше @msg File.seek: the position must be a finite number File.seek: позиція має бути скінченним числом @msg File.seek: the mode must be 0, 1 or 2 File.seek: режим має бути 0, 1 або 2 diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..02d2aa1ff4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5566,6 +5566,21 @@ liquify-list-end {0}, {1} {0} và {1} @msg the script passed more data to and from commands than one run may pass tập lệnh đã truyền đến và từ các lệnh nhiều dữ liệu hơn mức một lần chạy được phép @msg the script added more objects and data to the documents than one run may add tập lệnh đã thêm vào tài liệu nhiều đối tượng và dữ liệu hơn mức một lần chạy được phép @msg {what}: the object is not a File or a Folder {what}: đối tượng không phải File cũng không phải Folder +@msg {what}: the library {name} is not available {what}: thư viện {name} không khả dụng +@msg {what} is not available yet {what} chưa khả dụng +@msg {what}: the value {value} is not available yet {what}: giá trị {value} chưa khả dụng +@msg {what}: the object is not an {class} object {what}: đối tượng không phải đối tượng {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: gói XMP không phải XMP đúng định dạng +@msg {what}: the XMP data is too large {what}: dữ liệu XMP quá lớn +@msg {what}: {name} is not a valid property name {what}: {name} không phải tên thuộc tính hợp lệ +@msg {what}: the text holds a character XML does not allow {what}: văn bản chứa ký tự mà XML không cho phép +@msg {what}: {name} is not an array {what}: {name} không phải mảng +@msg {what}: {name} is not a simple property {what}: {name} không phải thuộc tính đơn +@msg {what}: {name} is not a language alternative array {what}: {name} không phải mảng phương án ngôn ngữ +@msg {what}: the array index {index} is out of range {what}: chỉ số mảng {index} nằm ngoài phạm vi +@msg {what}: the namespace {uri} is not registered {what}: không gian tên {uri} chưa được đăng ký +@msg {what}: the file is closed {what}: tệp đã đóng +@msg {what}: the file cannot be updated {what}: không thể cập nhật tệp @msg {what}: the count must be a finite number, 0 or more {what}: số lượng phải là một số hữu hạn, 0 trở lên @msg File.seek: the position must be a finite number File.seek: vị trí phải là một số hữu hạn @msg File.seek: the mode must be 0, 1 or 2 File.seek: chế độ phải là 0, 1 hoặc 2 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..e20c89b2f1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5582,6 +5582,21 @@ liquify-list-end {0}, {1} {0}和{1} @msg the script passed more data to and from commands than one run may pass 脚本与命令之间传递的数据超过了一次运行允许的数量 @msg the script added more objects and data to the documents than one run may add 脚本向文档添加的对象和数据超过了一次运行允许的数量 @msg {what}: the object is not a File or a Folder {what}:该对象既不是 File 也不是 Folder +@msg {what}: the library {name} is not available {what}:库 {name} 不可用 +@msg {what} is not available yet {what} 尚不可用 +@msg {what}: the value {value} is not available yet {what}:值 {value} 尚不可用 +@msg {what}: the object is not an {class} object {what}:该对象不是 {class} 对象 +@msg {what}: the XMP packet is not well-formed XMP {what}:XMP 数据包不是格式正确的 XMP +@msg {what}: the XMP data is too large {what}:XMP 数据过大 +@msg {what}: {name} is not a valid property name {what}:{name} 不是有效的属性名称 +@msg {what}: the text holds a character XML does not allow {what}:文本包含 XML 不允许的字符 +@msg {what}: {name} is not an array {what}:{name} 不是数组 +@msg {what}: {name} is not a simple property {what}:{name} 不是简单属性 +@msg {what}: {name} is not a language alternative array {what}:{name} 不是语言替代数组 +@msg {what}: the array index {index} is out of range {what}:数组索引 {index} 超出范围 +@msg {what}: the namespace {uri} is not registered {what}:命名空间 {uri} 未注册 +@msg {what}: the file is closed {what}:文件已关闭 +@msg {what}: the file cannot be updated {what}:文件无法更新 @msg {what}: the count must be a finite number, 0 or more {what}:数量必须是 0 或更大的有限数 @msg File.seek: the position must be a finite number File.seek:位置必须是有限数 @msg File.seek: the mode must be 0, 1 or 2 File.seek:模式必须是 0, 1 或 2 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..c18488af0e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2928,6 +2928,21 @@ liquify-list-end {0}, {1} {0}和{1} @msg the script passed more data to and from commands than one run may pass 指令碼與命令之間傳遞的資料超過一次執行允許的數量 @msg the script added more objects and data to the documents than one run may add 指令碼加入文件的物件和資料超過一次執行允許的數量 @msg {what}: the object is not a File or a Folder {what}:此物件既不是 File 也不是 Folder +@msg {what}: the library {name} is not available {what}:程式庫 {name} 無法使用 +@msg {what} is not available yet {what} 尚無法使用 +@msg {what}: the value {value} is not available yet {what}:值 {value} 尚無法使用 +@msg {what}: the object is not an {class} object {what}:此物件不是 {class} 物件 +@msg {what}: the XMP packet is not well-formed XMP {what}:XMP 封包不是格式正確的 XMP +@msg {what}: the XMP data is too large {what}:XMP 資料過大 +@msg {what}: {name} is not a valid property name {what}:{name} 不是有效的屬性名稱 +@msg {what}: the text holds a character XML does not allow {what}:文字含有 XML 不允許的字元 +@msg {what}: {name} is not an array {what}:{name} 不是陣列 +@msg {what}: {name} is not a simple property {what}:{name} 不是簡單屬性 +@msg {what}: {name} is not a language alternative array {what}:{name} 不是語言替代陣列 +@msg {what}: the array index {index} is out of range {what}:陣列索引 {index} 超出範圍 +@msg {what}: the namespace {uri} is not registered {what}:命名空間 {uri} 未註冊 +@msg {what}: the file is closed {what}:檔案已關閉 +@msg {what}: the file cannot be updated {what}:檔案無法更新 @msg {what}: the count must be a finite number, 0 or more {what}:數量必須是 0 或更大的有限數 @msg File.seek: the position must be a finite number File.seek:位置必須是有限數 @msg File.seek: the mode must be 0, 1 or 2 File.seek:模式必須是 0, 1 或 2 diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..c4a5f73998 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3051,6 +3051,42 @@ 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. 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. + Namespaces a packet declares are registered with the prefix it gives them, or `prefix_1_` when that prefix names + another namespace. +- `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. 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. 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. +- A packet over 8 MiB, one that is not well-formed XML, one with a document type declaration or an undefined entity, + and one nested more than 64 elements deep throws. 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}`, 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..60fb057207 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1044,6 +1044,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - 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`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 7fb823a4622f5a84b71e5ed392c23f5085baf761 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:40:13 -0800 Subject: [PATCH 02/21] Scripts: XMP namespaces have length limits and a byte budget XMPMeta.registerNamespace and packets that declare namespaces could add up to 4,096 namespaces of any length, held outside the script heap. - A namespace URI over 1,024 bytes and a prefix over 128 bytes, the `_n_` suffix included, throw "the XMP data is too large". - The registered namespaces hold at most 1 MiB together; a namespace past that throws the same error and is not registered. - Reading a packet takes fuel for the namespaces it copies. - Error messages hold at most the first 200 characters of a name, path, value or namespace the script gave. Tests: namespace_lengths_and_the_registry_budget_are_bounded, long_namespaces_from_scripts_and_packets_are_refused and error_messages_hold_a_bounded_part_of_the_script_text in crates/js/src/xmp_tests.rs. Docs: docs/mcp.md. --- crates/js/src/xmp.rs | 46 +++++++++++++++++++++--- crates/js/src/xmp_classes.rs | 21 ++++++++--- crates/js/src/xmp_tests.rs | 68 ++++++++++++++++++++++++++++++++++++ docs/mcp.md | 4 ++- 4 files changed, 130 insertions(+), 9 deletions(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index e0a54bb30b..60d07d4cce 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -17,7 +17,9 @@ //! VectorCraft's own rules: a packet or a written packet holds at most [`MAX_BYTES`] bytes, //! elements nest at most 64 deep, a child of `rdf:RDF` other than `rdf:Description` makes the //! packet malformed, a property given twice keeps its first value, and [`find_packet`] finds only a -//! UTF-8 packet. +//! UTF-8 packet. A realm registers at most [`MAX_NAMESPACES`] namespaces holding at most +//! [`MAX_REGISTRY_BYTES`] bytes, each URI at most [`MAX_URI_BYTES`] bytes and each prefix at most +//! [`MAX_PREFIX_BYTES`] bytes. use std::collections::{HashMap, HashSet}; @@ -49,6 +51,14 @@ const MAX_NODES: usize = 1 << 20; const MAX_ATTRS: usize = 1024; /// The most namespaces a realm registers. const MAX_NAMESPACES: usize = 4096; +/// The most bytes of a namespace URI a realm registers. +pub(crate) const MAX_URI_BYTES: usize = 1024; +/// The most bytes of a namespace prefix a realm registers, a `_n_` suffix included. +pub(crate) const MAX_PREFIX_BYTES: usize = 128; +/// The most bytes a realm's namespaces hold, counted by [`Registry::bytes`]. +pub(crate) const MAX_REGISTRY_BYTES: usize = 1 << 20; +/// The bytes counted for each namespace besides its URI and prefix. +const ENTRY_BYTES: usize = 96; /// The `id` of a packet wrapper (XMP Specification Part 1, 7.3.2). const WRAPPER_ID: &str = "W5M0MpCehiHzreSzNTczkc9d"; @@ -74,9 +84,11 @@ pub(crate) const ARRAY_IS_ALTTEXT: u32 = 0x1000; pub(crate) enum XmpError { /// The packet is not well-formed XML, or not XMP. Malformed, - /// The packet, or the packet written, is longer than [`MAX_BYTES`]. + /// The packet, or the packet written, is longer than [`MAX_BYTES`], or a namespace URI is longer + /// than [`MAX_URI_BYTES`] or its prefix longer than [`MAX_PREFIX_BYTES`]. TooLarge, - /// The realm already has [`MAX_NAMESPACES`] namespaces. + /// The realm already has [`MAX_NAMESPACES`] namespaces, or one more would take its namespaces + /// over [`MAX_REGISTRY_BYTES`]. Namespaces, /// A name that is not an XML name without a colon, or a prefix that names another namespace. BadName, @@ -228,6 +240,13 @@ pub(crate) struct Registry { /// names one namespace. prefixes: HashMap, uris: HashMap, + /// The bytes the namespaces hold, as [`entry_bytes`] counts them. + bytes: usize, +} + +/// The bytes counted for the namespace `uri` with the prefix `prefix`: both strings are kept twice. +fn entry_bytes(uri: &str, prefix: &str) -> usize { + ENTRY_BYTES + 2 * (uri.len() + prefix.len()) } impl Default for Registry { @@ -237,11 +256,17 @@ impl Default for Registry { Self { prefixes: standard.iter().map(|(p, u)| ((*u).to_string(), (*p).to_string())).collect(), uris: standard.iter().map(|(p, u)| ((*p).to_string(), (*u).to_string())).collect(), + bytes: standard.iter().map(|(p, u)| entry_bytes(u, p)).sum(), } } } impl Registry { + /// The bytes the namespaces hold, at most [`MAX_REGISTRY_BYTES`]. + pub(crate) fn bytes(&self) -> usize { + self.bytes + } + /// The prefix of the namespace `uri`. pub(crate) fn prefix_of(&self, uri: &str) -> Option<&str> { self.prefixes.get(uri).map(String::as_str) @@ -254,12 +279,17 @@ impl Registry { /// Registers the namespace `uri` with the prefix `suggested` (a trailing colon is left out), or /// with `suggested_1_`, `suggested_2_` … when that one names another namespace. → the prefix - /// the namespace has, which is its earlier one when it was registered before. + /// the namespace has, which is its earlier one when it was registered before. A URI over + /// [`MAX_URI_BYTES`] or a prefix over [`MAX_PREFIX_BYTES`] is [`XmpError::TooLarge`], and a + /// namespace past [`MAX_NAMESPACES`] or [`MAX_REGISTRY_BYTES`] is [`XmpError::Namespaces`]. pub(crate) fn register(&mut self, uri: &str, suggested: &str) -> Result { if let Some(p) = self.prefix_of(uri) { return Ok(p.to_string()); } let suggested = suggested.strip_suffix(':').unwrap_or(suggested); + if uri.len() > MAX_URI_BYTES || suggested.len() > MAX_PREFIX_BYTES { + return Err(XmpError::TooLarge); + } // XML does not allow the prefix `xmlns` to be declared or a prefix to name its namespace. if uri.is_empty() || !is_text(uri) || !is_ncname(suggested) || suggested == "xmlns" || uri == XMLNS { return Err(XmpError::BadName); @@ -273,6 +303,14 @@ impl Registry { prefix = format!("{suggested}_{n}_"); n += 1; } + if prefix.len() > MAX_PREFIX_BYTES { + return Err(XmpError::TooLarge); + } + let bytes = self.bytes.saturating_add(entry_bytes(uri, &prefix)); + if bytes > MAX_REGISTRY_BYTES { + return Err(XmpError::Namespaces); + } + self.bytes = bytes; self.prefixes.insert(uri.to_string(), prefix.clone()); self.uris.insert(prefix.clone(), uri.to_string()); Ok(prefix) diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index ab6c2a6174..0efd7fb53b 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -103,6 +103,7 @@ fn not_yet(i: &mut Interp, what: &str) -> Abrupt { } fn not_handled(i: &mut Interp, what: &str, value: &str) -> Abrupt { + let value = shown(value); i.throw(ErrorType::Range, &format!("{what}: the value {value} is not available yet")) } @@ -110,26 +111,35 @@ fn wrong_object(i: &mut Interp, what: &str, class: &str) -> Abrupt { i.type_error(&format!("{what}: the object is not an {class} object")) } +/// The first 200 characters of `s`, the most of a script's text an error message holds. +fn shown(s: &str) -> String { + s.chars().take(200).collect() +} + /// The exception for `e`, which `what` met with the name or path `name`. fn xmp_error(i: &mut Interp, what: &str, e: XmpError, name: &str) -> Abrupt { + let name = shown(name); match e { XmpError::Malformed => i.throw(ErrorType::Error, &format!("{what}: the XMP packet is not well-formed XMP")), XmpError::TooLarge | XmpError::Namespaces => i.throw(ErrorType::Range, &format!("{what}: the XMP data is too large")), XmpError::BadName => i.throw(ErrorType::Error, &format!("{what}: {name} is not a valid property name")), XmpError::BadText => i.throw(ErrorType::Error, &format!("{what}: the text holds a character XML does not allow")), - XmpError::NotYet => not_handled(i, what, name), + XmpError::NotYet => not_handled(i, what, &name), } } fn not_array(i: &mut Interp, what: &str, name: &str) -> Abrupt { + let name = shown(name); i.throw(ErrorType::Error, &format!("{what}: {name} is not an array")) } fn not_simple(i: &mut Interp, what: &str, name: &str) -> Abrupt { + let name = shown(name); i.throw(ErrorType::Error, &format!("{what}: {name} is not a simple property")) } fn not_alt_text(i: &mut Interp, what: &str, name: &str) -> Abrupt { + let name = shown(name); i.throw(ErrorType::Error, &format!("{what}: {name} is not a language alternative array")) } @@ -138,6 +148,7 @@ fn out_of_range(i: &mut Interp, what: &str, index: i64) -> Abrupt { } fn unregistered(i: &mut Interp, what: &str, uri: &str) -> Abrupt { + let uri = shown(uri); i.throw(ErrorType::Error, &format!("{what}: the namespace {uri} is not registered")) } @@ -224,7 +235,7 @@ fn record(i: &mut Interp, proto: Option, fields: Vec<(&'static str, Value fn external_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let name = text(i, &arg(args, 0))?; if name != LIBRARY { - let name: String = name.chars().take(200).collect(); + let name = shown(&name); let what = "ExternalObject"; return Err(i.throw(ErrorType::Error, &format!("{what}: the library {name} is not available"))); } @@ -297,7 +308,9 @@ fn new_meta(i: &mut Interp, meta: Meta) -> JsResult { /// The metadata of the packet `text`, read for `what`. fn parse_packet(i: &mut Interp, what: &str, text: &str) -> JsResult { - spend(i, text.len())?; + // Reading copies the realm's namespaces. + let copied = registry(i)?.bytes(); + spend(i, text.len().saturating_add(copied))?; let r = xmp::parse(text, registry(i)?); r.map_err(|e| xmp_error(i, what, e, "")) } @@ -1036,7 +1049,7 @@ fn packet_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { // A packet is checked by reading it into a copy of the realm's namespaces, so checking it // registers nothing. let mut scratch = registry(i)?.clone(); - spend(i, s.len())?; + spend(i, s.len().saturating_add(2 * scratch.bytes()))?; xmp::parse(&s, &mut scratch).map_err(|e| xmp_error(i, what, e, ""))?; Ok(s) } diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 5641ff77d7..653cd913e4 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -247,6 +247,74 @@ fn blank_values_and_failed_packets_keep_their_state() { assert_eq!(string(&src), "undefined", "a packet that fails to read registers no namespace"); } +/// A namespace URI or prefix over its limit is refused, and so is a namespace that would take the +/// realm's namespaces over their byte budget; a refused namespace leaves the registry as it was. +#[test] +fn namespace_lengths_and_the_registry_budget_are_bounded() { + let mut registry = Registry::default(); + let uri = |n: usize, fill: usize| format!("http://n/{n}/{}", "u".repeat(fill)); + let at_limit = uri(0, xmp::MAX_URI_BYTES - uri(0, 0).len()); + assert_eq!(at_limit.len(), xmp::MAX_URI_BYTES); + assert_eq!(registry.register(&at_limit, "a"), Ok("a".to_string())); + let over = format!("{at_limit}u"); + assert_eq!(registry.register(&over, "b"), Err(XmpError::TooLarge)); + assert_eq!(registry.register("http://p/", &"p".repeat(xmp::MAX_PREFIX_BYTES)), Ok("p".repeat(xmp::MAX_PREFIX_BYTES))); + assert_eq!(registry.register("http://q/", &"q".repeat(xmp::MAX_PREFIX_BYTES + 1)), Err(XmpError::TooLarge)); + assert_eq!(registry.register("http://p2/", &"p".repeat(xmp::MAX_PREFIX_BYTES)), Err(XmpError::TooLarge), "the `_1_` suffix counts"); + assert_eq!(registry.prefix_of(&over), None); + let mut n = 1; + let refused = loop { + let before = registry.bytes(); + match registry.register(&uri(n, 900), &format!("p{n}")) { + Ok(_) => n += 1, + Err(e) => break (e, before), + } + assert!(n < 4096, "the byte budget ends registration before the namespace count does"); + }; + assert_eq!(refused.0, XmpError::Namespaces); + assert_eq!(registry.bytes(), refused.1, "a refused namespace adds no bytes"); + assert!(registry.bytes() <= xmp::MAX_REGISTRY_BYTES); + assert_eq!(registry.prefix_of(&uri(n, 900)), None); + assert_eq!(registry.register(&at_limit, "z"), Ok("a".to_string()), "a namespace registered before keeps its prefix"); +} + +#[test] +fn long_namespaces_from_scripts_and_packets_are_refused() { + assert_eq!( + thrown("XMPMeta.registerNamespace('http://n/' + new Array(2000).join('u'), 'a')"), + "RangeError: XMPMeta.registerNamespace: the XMP data is too large" + ); + assert_eq!( + thrown("XMPMeta.registerNamespace('http://n/', new Array(200).join('a'))"), + "RangeError: XMPMeta.registerNamespace: the XMP data is too large" + ); + let long = format!("http://n/{}", "u".repeat(xmp::MAX_URI_BYTES)); + let packet = format!( + "v" + ); + let mut registry = Registry::default(); + assert_eq!(xmp::parse(&packet, &mut registry), Err(XmpError::TooLarge)); + assert_eq!(registry.prefix_of(&long), None); + assert_eq!(thrown(&format!("new XMPMeta({packet:?})")), "RangeError: XMPMeta: the XMP data is too large"); +} + +/// An error message holds at most the first 200 characters of a name, path, value or namespace +/// the script gave. +#[test] +fn error_messages_hold_a_bounded_part_of_the_script_text() { + let cases = [ + ("new XMPMeta().getProperty('http://none/' + s, 'a')", "Error: XMPMeta.getProperty: the namespace http://none/"), + ("new XMPMeta().setProperty(XMPConst.NS_DC, '1' + s, 'x')", "Error: XMPMeta.setProperty: 1"), + ("new XMPMeta().getProperty(XMPConst.NS_DC, 'a/' + s)", "RangeError: XMPMeta.getProperty: the value a/"), + ("new XMPMeta().getProperty(XMPConst.NS_DC, 'a', s)", "RangeError: XMPMeta.getProperty: the value "), + ]; + for (src, start) in cases { + let message = thrown(&format!("var s = new Array(100000).join('x'); {src}")); + assert!(message.starts_with(start), "{message}"); + assert!(message.len() < start.len() + 260, "{src}: {} characters", message.len()); + } +} + #[test] fn array_forms_follow_their_options() { assert_eq!(Form::from_options(0x200), Form::Bag); diff --git a/docs/mcp.md b/docs/mcp.md index c4a5f73998..a1c0de7c34 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3064,7 +3064,9 @@ rules for these objects: `prefix:name`, or either with `[n]` (from 1) or `[last()]` for an array item. 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. Namespaces a packet declares are registered with the prefix it gives them, or `prefix_1_` when that prefix names - another namespace. + another namespace. 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 declares the namespace. - `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, From 1a33ff7326f3a1354260d45feb04f3d66bdf4341 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:54:42 -0800 Subject: [PATCH 03/21] Scripts: XMP generic-language updates and packets that serialize too deep - setLocalizedText reads its generic language argument. With no item in the specific language and exactly one item in the generic language or a variant of it, that item changes, as the XMP Toolkit SDK's SetLocalizedText does (XMPCore/source/XMPMeta-GetSet.cpp); with several, the specific language is added. - A packet read from rdf:RDF alone could hold a value nested 64 elements deep that serialize() then wrote under x:xmpmeta, 65 deep, so the written packet did not read back. A value is now measured as deep as serialize() writes it, and one past 64 elements throws when the packet is read. Tests: localized_text_updates_a_single_generic_language_item and deeply_nested_values_read_back_after_serializing in crates/js/src/xmp_tests.rs. Docs: docs/mcp.md. --- crates/js/src/xmp.rs | 13 +++++++++++ crates/js/src/xmp_classes.rs | 44 +++++++++++++++++++++++------------- crates/js/src/xmp_tests.rs | 34 ++++++++++++++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 77 insertions(+), 17 deletions(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 60d07d4cce..c81533b1f5 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -529,12 +529,25 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

MAX_DEPTH { + return Err(XmpError::TooLarge); + } other(p, &own, &children, scope, mark) }; scope.truncate(mark); Ok(Prop { ns, name: local.to_string(), value }) } +/// The elements a written packet holds around a property. +const PROPERTY_DEPTH: usize = 3; + +/// The elements `el` nests, itself included. +fn height(el: &El) -> usize { + 1 + el.elements().map(height).max().unwrap_or(0) +} + /// The array of simple items the only child of a property element holds, when it is one. fn array_of(children: &[&El], scope: &mut Scope) -> Option { let [container] = children else { return None }; diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 0efd7fb53b..0987011607 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -696,22 +696,25 @@ fn same_lang(lang: Option<&str>, want: &str) -> bool { lang.is_some_and(|l| l.eq_ignore_ascii_case(want)) } +/// Is language tag `lang` the language `generic`, or one of its variants (`generic-…`), ignoring +/// case? Never for an empty `generic`. +fn generic_lang(lang: Option<&str>, generic: &str) -> bool { + !generic.is_empty() + && lang.is_some_and(|l| { + l.eq_ignore_ascii_case(generic) + || l.len() > generic.len() + && l.get(..generic.len()).is_some_and(|p| p.eq_ignore_ascii_case(generic)) + && l.as_bytes().get(generic.len()) == Some(&b'-') + }) +} + /// The item of `items` for `specific`, else one whose language starts with `generic`, else the /// `x-default` item, else the first. fn pick_lang<'a>(items: &'a [Item], generic: &str, specific: &str) -> Option<&'a Item> { - let generic_match = |i: &&Item| { - !generic.is_empty() - && i.lang.as_deref().is_some_and(|l| { - l.eq_ignore_ascii_case(generic) - || l.len() > generic.len() - && l.get(..generic.len()).is_some_and(|p| p.eq_ignore_ascii_case(generic)) - && l.as_bytes().get(generic.len()) == Some(&b'-') - }) - }; items .iter() .find(|i| same_lang(i.lang.as_deref(), specific)) - .or_else(|| items.iter().find(generic_match)) + .or_else(|| items.iter().find(|i| generic_lang(i.lang.as_deref(), generic))) .or_else(|| items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default"))) .or_else(|| items.first()) } @@ -745,6 +748,7 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let what = "XMPMeta.setLocalizedText"; let o = this_meta(i, &this, what)?; let (ns, name) = array_target(i, args, what)?; + let generic = lang(i, &arg(args, 2), what)?; let specific = lang(i, &arg(args, 3), what)?; if specific.is_empty() || specific.contains(char::is_whitespace) { return Err(not_handled(i, what, &specific)); @@ -763,15 +767,16 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let grow = 2 * (64 + value.len() + specific.len()); change(i, o, grow, |m, _| { let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|p| &mut p.value) else { return }; - set_lang(items, &specific, value); + set_lang(items, &generic, &specific, value); })?; Ok(Value::Undefined) } -/// Sets the item of `items` in `specific` to `value`. VectorCraft's own rule: the `x-default` item -/// is first; it is added with the value when there is none, and follows a change to an item that -/// had the same text. -fn set_lang(items: &mut Vec, specific: &str, value: String) { +/// Sets the item of `items` in `specific` to `value`, or, when there is none, the one item in the +/// language `generic` or a variant of it. VectorCraft's own rule: the `x-default` item is first; it +/// is added with the value when there is none, and follows a change to an item that had the same +/// text. +fn set_lang(items: &mut Vec, generic: &str, specific: &str, value: String) { let default = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")); if specific.eq_ignore_ascii_case("x-default") { match default { @@ -784,7 +789,14 @@ fn set_lang(items: &mut Vec, specific: &str, value: String) { } return; } - let old = items.iter().position(|i| same_lang(i.lang.as_deref(), specific)); + let old = items.iter().position(|i| same_lang(i.lang.as_deref(), specific)).or_else(|| { + let mut generic_items = + items.iter().enumerate().filter(|(_, i)| !same_lang(i.lang.as_deref(), "x-default") && generic_lang(i.lang.as_deref(), generic)); + match (generic_items.next(), generic_items.next()) { + (Some((at, _)), None) => Some(at), + _ => None, + } + }); let follows = match (old, default) { (Some(o), Some(d)) => items.get(o).map(|i| &i.text) == items.get(d).map(|i| &i.text), (None, Some(_)) => false, diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 653cd913e4..872f338cab 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -315,6 +315,40 @@ fn error_messages_hold_a_bounded_part_of_the_script_text() { } } +/// With no item in the specific language, `setLocalizedText` changes the one item in the generic +/// language, and adds the specific language when there are several. +#[test] +fn localized_text_updates_a_single_generic_language_item() { + let src = "var ns = 'http://example.com/lt/'; XMPMeta.registerNamespace(ns, 'lt'); var m = new XMPMeta(); + m.setLocalizedText(ns, 'label', null, 'en-GB', 'Colour'); + m.setLocalizedText(ns, 'label', 'en', 'en-US', 'Color'); + var one = [m.countArrayItems(ns, 'label'), m.getLocalizedText(ns, 'label', null, 'en-GB'), m.getLocalizedText(ns, 'label', null, 'x-default')]; + m.setLocalizedText(ns, 'label', null, 'en-AU', 'Colour'); + m.setLocalizedText(ns, 'label', 'en', 'en-CA', 'Couleur'); + one.concat([m.countArrayItems(ns, 'label'), m.getLocalizedText(ns, 'label', null, 'en-CA'), m.getLocalizedText(ns, 'label', null, 'en-GB')]).join('|')"; + assert_eq!(string(src), "2|Color|Color|4|Couleur|Color"); +} + +/// A packet read from `rdf:RDF` alone reads back from what it serializes to, which adds the +/// `x:xmpmeta` element around it, also with values nested near the depth limit. +#[test] +fn deeply_nested_values_read_back_after_serializing() { + let mut read = 0; + for height in 55..=66 { + let nest = format!("{}x{}", "".repeat(height - 1), "".repeat(height - 1)); + let packet = format!( + "{nest}" + ); + let mut registry = Registry::default(); + let Ok(meta) = xmp::parse(&packet, &mut registry) else { continue }; + read += 1; + let out = xmp::serialize(&meta, ®istry, true); + let again = out.as_ref().ok().map(|out| xmp::parse(out, &mut registry)); + assert_eq!(again, Some(Ok(meta)), "a value {height} elements high"); + } + assert!(read > 0, "some of the packets are read"); +} + #[test] fn array_forms_follow_their_options() { assert_eq!(Form::from_options(0x200), Form::Bag); diff --git a/docs/mcp.md b/docs/mcp.md index a1c0de7c34..b61b5471ef 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3081,7 +3081,8 @@ rules for these objects: `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. - A packet over 8 MiB, one that is not well-formed XML, one with a document type declaration or an undefined entity, - and one nested more than 64 elements deep throws. Members of the help page that are not built yet (iterators, + and one nested more than 64 elements deep throws; a value is counted as deep as `serialize()` would write it, + under `x:xmpmeta`, `rdf:RDF` and `rdf:Description`. 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. From cac32433a99ef5aadaeb0a17b8f67e09292462f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:08:10 -0800 Subject: [PATCH 04/21] Scripts: XMP packets register the namespaces inside kept values A namespace declared only inside a structure, an array of structures or on a qualifier was not registered when the packet was read, so XMPMeta.getNamespacePrefix gave undefined for it. Reading a value that is kept as it was written now registers the namespaces its element and attribute names use, other than RDF and XML. Test: namespaces_inside_kept_values_are_registered in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp.rs | 27 +++++++++++++++++++++++++++ crates/js/src/xmp_tests.rs | 13 +++++++++++++ 2 files changed, 40 insertions(+) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index c81533b1f5..88663527c2 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -534,12 +534,39 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

MAX_DEPTH { return Err(XmpError::TooLarge); } + register_names(p, scope, registry)?; + register_nested(p, scope, registry)?; other(p, &own, &children, scope, mark) }; scope.truncate(mark); Ok(Prop { ns, name: local.to_string(), value }) } +/// Registers the namespaces of the name and the attributes of `el`, with `scope` holding the +/// bindings in scope there, other than RDF, XML and no namespace. +fn register_names(el: &El, scope: &Scope, registry: &mut Registry) -> Result<(), XmpError> { + let names = std::iter::once((el.name.as_str(), true)).chain(attrs(el).into_iter().map(|(k, _)| (k, false))); + for (name, element) in names { + let Some((ns, _)) = resolve(name, scope, element) else { continue }; + if !ns.is_empty() && ns != RDF && ns != XML { + registry.register(&ns, name.split_once(':').map_or("ns", |(p, _)| p))?; + } + } + Ok(()) +} + +/// Registers the namespaces the elements inside `el` use, as [`register_names`] does. +fn register_nested(el: &El, scope: &mut Scope, registry: &mut Registry) -> Result<(), XmpError> { + for c in el.elements() { + let mark = scope.len(); + push_decls(c, scope); + let r = register_names(c, scope, registry).and_then(|()| register_nested(c, scope, registry)); + scope.truncate(mark); + r?; + } + Ok(()) +} + /// The elements a written packet holds around a property. const PROPERTY_DEPTH: usize = 3; diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 872f338cab..a6438aaf39 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -349,6 +349,19 @@ fn deeply_nested_values_read_back_after_serializing() { assert!(read > 0, "some of the packets are read"); } +/// Namespaces declared only inside a structure or on a qualifier are registered when the packet +/// is read. +#[test] +fn namespaces_inside_kept_values_are_registered() { + let packet = PACKET.replace( + "", + "s1", + ); + let src = + format!("var m = new XMPMeta({packet:?}); [XMPMeta.getNamespacePrefix('http://inner/'), XMPMeta.getNamespacePrefix('http://q/')].join('|')"); + assert_eq!(string(&src), "in:|q:"); +} + #[test] fn array_forms_follow_their_options() { assert_eq!(Form::from_options(0x200), Form::Bag); From b8bf41b7a93419541dc008a17f85649de587ce11 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:20:30 -0800 Subject: [PATCH 05/21] Scripts: an undeclared prefix inside a kept XMP value is malformed A structure or qualifier whose element or attribute used a prefix that nothing declared was read and then serialized with the prefix unbound. Such a packet is now refused as not well-formed XMP. Test: namespaces_inside_kept_values_are_registered in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp.rs | 5 +++-- crates/js/src/xmp_classes.rs | 1 + crates/js/src/xmp_tests.rs | 6 ++++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 88663527c2..497cc7ca61 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -543,11 +543,12 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

Result<(), XmpError> { let names = std::iter::once((el.name.as_str(), true)).chain(attrs(el).into_iter().map(|(k, _)| (k, false))); for (name, element) in names { - let Some((ns, _)) = resolve(name, scope, element) else { continue }; + let (ns, _) = resolve(name, scope, element).ok_or(XmpError::Malformed)?; if !ns.is_empty() && ns != RDF && ns != XML { registry.register(&ns, name.split_once(':').map_or("ns", |(p, _)| p))?; } diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 0987011607..11e2414d68 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -944,6 +944,7 @@ fn file_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult1", "x"] { + let packet = format!( + "{value}" + ); + assert_eq!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed), "an undeclared prefix in {value}"); + } } #[test] From 84acd52710ff9df56c24e64c5ba85378c01bdd3a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:36:05 -0800 Subject: [PATCH 06/21] Scripts: text beside an XMP array keeps the property as written A property holding text next to its rdf:Bag, rdf:Seq or rdf:Alt was read as an array of simple items, and serialize() dropped the text. Such a property is now kept as the XML it was written in. Test: text_beside_an_array_is_kept in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp.rs | 2 +- crates/js/src/xmp_tests.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 497cc7ca61..d4973603d5 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -526,7 +526,7 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

Date: Sun, 22 Nov 2026 08:11:31 -0800 Subject: [PATCH 07/21] Scripts: a sidecar XMPFile replaces keeps its Unix permission bits closeFile() writes a sidecar through a new temporary file and renames it over the sidecar, so a 0600 sidecar became 0644 under a 022 umask. The temporary file now takes the sidecar's permission bits before the rename, as File.copy does for its target. Test: a_replaced_sidecar_keeps_its_permissions (Unix only) in crates/engine/src/tests/script_xmp.rs. --- crates/engine/src/script/files.rs | 13 ++++++++++--- crates/engine/src/tests/script_xmp.rs | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index d22db3dc6a..e556449148 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1981,9 +1981,16 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { }; let r = write_temp(); drop(out); - let r = r.and_then(|()| std::fs::rename(&temp, &target)).inspect_err(|_| { - let _ = std::fs::remove_file(&temp); - }); + // The replacement keeps the sidecar's permission bits. On Windows the only permission is the + // read-only attribute, and a read-only temporary file could not be removed after a failed + // rename. + let permissions = if cfg!(unix) { std::fs::metadata(&target).map(|m| m.permissions()).ok() } else { None }; + let r = r + .and_then(|()| permissions.map_or(Ok(()), |p| std::fs::set_permissions(&temp, p))) + .and_then(|()| std::fs::rename(&temp, &target)) + .inspect_err(|_| { + let _ = std::fs::remove_file(&temp); + }); let changed = r.is_ok(); (r, changed) } else { diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index a89efbc14f..b2c68e2b95 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -356,6 +356,31 @@ fn a_link_to_another_kind_of_file_is_not_written() { 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() { From 4a51aa4d4893b321861c0f1a569207b473f86868 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:24:53 -0800 Subject: [PATCH 08/21] Scripts: XMP properties in the RDF or XML namespace are refused setProperty and the other property members took a path in the RDF or XML namespace, and serialize() wrote a packet that XMPMeta could not read back. Such a path now throws "... is not a valid property name". Test: rdf_and_xml_namespaces_hold_no_properties in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp_classes.rs | 4 ++++ crates/js/src/xmp_tests.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 11e2414d68..aadfb83fcb 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -342,6 +342,10 @@ fn namespace(i: &mut Interp, v: &Value, what: &str) -> JsResult { fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult<(String, String, Step)> { let ns = namespace(i, &arg(args, at), what)?; let path = text(i, &arg(args, at + 1))?; + // A packet holds no property in the RDF or XML namespace. + if ns == xmp::RDF || ns == xmp::XML { + return Err(xmp_error(i, what, XmpError::BadName, &path)); + } let r = xmp::parse_path(&path, &ns, registry(i)?); match r { Ok((name, step)) => Ok((ns, name, step)), diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 7995905dc8..9a821f7f3a 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -380,6 +380,22 @@ fn text_beside_an_array_is_kept() { assert_eq!(xmp::parse(&out, &mut registry), Ok(meta)); } +/// No property is set in the RDF or XML namespace, which a packet cannot hold. +#[test] +fn rdf_and_xml_namespaces_hold_no_properties() { + for ns in ["http://www.w3.org/1999/02/22-rdf-syntax-ns#", "http://www.w3.org/XML/1998/namespace"] { + assert_eq!( + thrown(&format!("new XMPMeta().setProperty({ns:?}, 'foo', 'x')")), + "Error: XMPMeta.setProperty: foo is not a valid property name", + "{ns}" + ); + assert_eq!( + thrown(&format!("new XMPMeta().appendArrayItem({ns:?}, 'foo', 'x', XMPConst.PROP_IS_ARRAY)")), + "Error: XMPMeta.appendArrayItem: foo is not a valid property name" + ); + } +} + #[test] fn array_forms_follow_their_options() { assert_eq!(Form::from_options(0x200), Form::Bag); From 72c4875990a8b01d04d147c7fccc2a7a95a5f4ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:44:46 -0800 Subject: [PATCH 09/21] Scripts: a script cannot change the state an XMPFile keeps An XMPFile kept its path, open flags and pending packet in writable, configurable properties, so a script could assign a packet to a file opened for reading and closeFile wrote it without checking the update flag or reading the packet. - The properties holding an XMPFile's state are not writable, enumerable or configurable, and the pending packet is one of them from the start. - The XMPMeta docs say that only the namespaces a packet's names use are registered, which is what reading a packet does. Test: a_script_cannot_change_the_state_of_an_xmp_file in crates/engine/src/tests/script_xmp.rs. Docs: docs/mcp.md. --- crates/engine/src/tests/script_xmp.rs | 25 +++++++++++++++++++++++++ crates/js/src/xmp.rs | 7 ++++--- crates/js/src/xmp_classes.rs | 5 ++++- docs/mcp.md | 9 +++++---- 4 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index b2c68e2b95..b839da8893 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -161,6 +161,31 @@ fn a_scanned_sidecar_is_read_only() { 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 +/// hold the packet, the path and the open flags. +#[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;\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\ + x.closeFile(); out.push(delete x.__vcXmpPath); vc.log(out); vc.log(p);" + ), + ); + assert_eq!(log[0], json!(["TypeError", "undefined", true, false])); + let text = std::fs::read_to_string(log[1].as_str().unwrap()).unwrap(); + assert_eq!(text, PACKET); + let _ = std::fs::remove_dir_all(base); +} + /// 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. diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index d4973603d5..0348da2e16 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -10,9 +10,10 @@ //! a simple value (text, or a URI in `rdf:resource`), an array of simple items (`rdf:Bag`, //! `rdf:Seq` or `rdf:Alt`, each item with an optional `xml:lang`), or any other value (a structure, //! a value with qualifiers, an array of structures), which is kept as the XML it was written in and -//! written back with the namespace declarations it uses. Namespaces a packet declares are added to -//! the realm's [`Registry`] with the prefix the packet gives them, or a new prefix when that one is -//! taken. +//! written back with the namespace declarations it uses. The namespaces of the property, element and +//! attribute names under `rdf:Description` are added to the realm's [`Registry`] with the prefix the +//! packet gives them, or a new prefix when that one is taken; a namespace the packet declares and no +//! such name uses is not added. //! //! VectorCraft's own rules: a packet or a written packet holds at most [`MAX_BYTES`] bytes, //! elements nest at most 64 deep, a child of `rdf:RDF` other than `rdf:Description` makes the diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index aadfb83fcb..5733d28e9a 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -203,11 +203,13 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { }) } +/// Sets the slot `name` of `o` as a property that is not writable, enumerable or configurable, so +/// a script cannot assign, redefine or delete it. fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { if let Value::String(s) = &value { i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; } - i.define(o, key(name), Prop::Data { value, flags: HIDDEN }) + i.define(o, key(name), Prop::Data { value, flags: 0 }) } /// A string value, charged to the heap. @@ -983,6 +985,7 @@ fn file_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult Date: Sun, 22 Nov 2026 11:09:01 -0800 Subject: [PATCH 10/21] Scripts: XMPFile methods take only XMPFile objects, and x-default updates its matches - XMPFile's methods refuse an object the XMPFile constructor did not make, so a plain object or one made from XMPFile.prototype with properties of the same names is not read or written as a file. - setLocalizedText for x-default also changes the items that had the text of the x-default item. Tests: a_script_cannot_change_the_state_of_an_xmp_file in crates/engine/src/tests/script_xmp.rs and localized_text_for_x_default_changes_the_items_that_matched_it in crates/js/src/xmp_tests.rs. --- crates/engine/src/tests/script_xmp.rs | 9 +++++++-- crates/js/src/heap.rs | 4 +++- crates/js/src/xmp_classes.rs | 25 +++++++++++++++++-------- crates/js/src/xmp_tests.rs | 11 +++++++++++ 4 files changed, 38 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index b839da8893..6c68cadcff 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -163,7 +163,8 @@ fn a_scanned_sidecar_is_read_only() { /// 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 -/// hold the packet, the path and the open flags. +/// hold 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"); @@ -177,10 +178,14 @@ fn a_script_cannot_change_the_state_of_an_xmp_file() { x.__vcXmpPending = 'not a packet'; x.__vcXmpFlags = XMPConst.OPEN_FOR_UPDATE;\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!(["TypeError", "undefined", true, false])); + assert_eq!(log[0], json!(["TypeError", "undefined", true, "TypeError", "TypeError", false])); let text = std::fs::read_to_string(log[1].as_str().unwrap()).unwrap(); assert_eq!(text, PACKET); let _ = std::fs::remove_dir_all(base); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index fc665342dc..4e3cf3dd87 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -248,6 +248,8 @@ pub(crate) enum Class { XmlFilter(Box), /// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]). Xmp(Box), + /// An object the `XMPFile` constructor made ([`crate::xmp_classes`]). + XmpFile, } /// What an XML value is. @@ -311,7 +313,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) | Class::Xmp(_) => "Object", + Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile => "Object", Class::Math => "Math", Class::Json => "JSON", Class::Ordinary | Class::ForIn(_) => "Object", diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 5733d28e9a..3357336a5f 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -770,7 +770,15 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J meta_of(i, o)?.find(&ns, &name).unwrap_or(0) } }; - let grow = 2 * (64 + value.len() + specific.len()); + // An item and the `x-default` item change, or every item with the text of the `x-default` one. + let changed = match meta_of(i, o)?.props.get(at).map(|p| &p.value) { + Some(xmp::Value::Array { items, .. }) if specific.eq_ignore_ascii_case("x-default") => { + let old = items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default")).map(|i| &i.text); + items.iter().filter(|i| Some(&i.text) == old).count().max(2) + } + _ => 2, + }; + let grow = changed.saturating_mul(64 + value.len() + specific.len()); change(i, o, grow, |m, _| { let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|p| &mut p.value) else { return }; set_lang(items, &generic, &specific, value); @@ -781,14 +789,14 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J /// Sets the item of `items` in `specific` to `value`, or, when there is none, the one item in the /// language `generic` or a variant of it. VectorCraft's own rule: the `x-default` item is first; it /// is added with the value when there is none, and follows a change to an item that had the same -/// text. +/// text; a change to the `x-default` item also changes the items that had its text. fn set_lang(items: &mut Vec, generic: &str, specific: &str, value: String) { let default = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")); if specific.eq_ignore_ascii_case("x-default") { - match default { - Some(d) => { - if let Some(item) = items.get_mut(d) { - item.text = value; + match default.and_then(|d| items.get(d)).map(|i| i.text.clone()) { + Some(old) => { + for item in items.iter_mut().filter(|i| i.text == old) { + item.text.clone_from(&value); } } None => items.insert(0, Item { text: value, lang: Some("x-default".into()) }), @@ -917,9 +925,10 @@ not_yet_fns! { // ---- XMPFile ---- -/// The `XMPFile` `this`, refused when it is not one. +/// The `XMPFile` `this`, refused when the `XMPFile` constructor did not make it. fn this_file(i: &mut Interp, this: &Value, what: &str) -> JsResult { if let Some(o) = this.as_object() + && matches!(i.heap.object(o).map(|ob| &ob.class), Some(Class::XmpFile)) && matches!(slot(i, o, PATH)?, Value::String(_)) { return Ok(o); @@ -970,7 +979,7 @@ fn file_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult Date: Sun, 22 Nov 2026 11:15:46 -0800 Subject: [PATCH 11/21] Scripts: XMP item paths take no options, and alt-text needs a language on each item - setProperty with an array item path, such as list[1], and any option throws that the value is not available yet instead of setting the item and leaving the option out. - getLocalizedText and setLocalizedText throw that the array is not a language alternative array for an rdf:Alt with an item that has no xml:lang. Tests: bad_arguments_and_unbuilt_members_throw in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp_classes.rs | 17 ++++++++++++++--- crates/js/src/xmp_tests.rs | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 3357336a5f..964e9acf89 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -430,6 +430,8 @@ fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul } let value = arg(args, 2); if let Step::Item(index) = step { + // An array item is a simple value, which takes no options. + only(i, options, 0, what)?; let v = xml_text(i, &value, what)?; return set_item(i, o, &ns, &name, index, v, false, what); } @@ -730,14 +732,23 @@ fn lang(i: &mut Interp, v: &Value, what: &str) -> JsResult { if matches!(v, Value::Null | Value::Undefined) { Ok(String::new()) } else { xml_text(i, v, what) } } +/// Is the property at `at` of `o` a language alternative: an `rdf:Alt` whose items, if it has any, +/// all have a language? +fn is_alt_text(i: &Interp, o: ObjId, at: usize) -> JsResult { + Ok(match meta_of(i, o)?.props.get(at).map(|p| &p.value) { + Some(xmp::Value::Array { form: Form::Alt, items }) => items.iter().all(|item| item.lang.is_some()), + _ => false, + }) +} + fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.getLocalizedText"; let o = this_meta(i, &this, what)?; let (ns, name) = array_target(i, args, what)?; let generic = lang(i, &arg(args, 2), what)?; let specific = lang(i, &arg(args, 3), what)?; - let Some((at, form, _)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; - if form != Form::Alt { + let Some((at, _, _)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + if !is_alt_text(i, o, at)? { return Err(not_alt_text(i, what, &name)); } let found = match &meta_of(i, o)?.props[at].value { @@ -762,7 +773,7 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let value = xml_text(i, &arg(args, 4), what)?; let found = array_items(i, o, &ns, &name, what)?; let at = match found { - Some((_, form, _)) if form != Form::Alt => return Err(not_alt_text(i, what, &name)), + Some((at, _, _)) if !is_alt_text(i, o, at)? => return Err(not_alt_text(i, what, &name)), Some((at, _, _)) => at, None => { let prop = xmp::Prop { ns: ns.clone(), name: name.clone(), value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } }; diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 96e864bec8..de94872808 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -141,6 +141,21 @@ fn bad_arguments_and_unbuilt_members_throw() { thrown(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'subject', null, 'en')")), "Error: XMPMeta.getLocalizedText: subject is not a language alternative array" ); + assert_eq!( + thrown(&with_packet("m.setProperty(XMPConst.NS_DC, 'subject[1]', 'x', XMPConst.PROP_IS_ARRAY)")), + "RangeError: XMPMeta.setProperty: the value 0x200 is not available yet" + ); + // An `rdf:Alt` with an item that has no language is not a language alternative. + let untagged = "var m = new XMPMeta(\"\ + ab\");"; + assert_eq!( + thrown(&format!("{untagged} m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'en')")), + "Error: XMPMeta.getLocalizedText: title is not a language alternative array" + ); + assert_eq!( + thrown(&format!("{untagged} m.setLocalizedText(XMPConst.NS_DC, 'title', null, 'en', 'c')")), + "Error: XMPMeta.setLocalizedText: title is not a language alternative array" + ); assert_eq!( thrown("new XMPMeta().getStructField(XMPConst.NS_DC, 'a', XMPConst.NS_DC, 'b')"), "Error: XMPMeta.getStructField is not available yet" From 7a96c6c0916c0dde6e2ffc74e1d4094599be6d87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:44:03 -0800 Subject: [PATCH 12/21] Scripts: XMP packet scanning needs the wrapper id, and failed alt-text sets add nothing - A packet starts at a `. +const MAX_HEADER: usize = 256; /// The property is a URI (`rdf:resource`). pub(crate) const PROP_VALUE_IS_URI: u32 = 0x2; @@ -819,21 +822,36 @@ pub(crate) fn pad_size(packet: &str) -> usize { } /// The first UTF-8 packet in `bytes` that has both ends of its wrapper (XMP Specification Part 1, -/// 7.3), or `None`. A start with no end before the next start is skipped, and so is a trailer that -/// does not close before the next start. +/// 7.3), or `None`. A start is a ` Option { const BEGIN: &[u8] = b"").and_then(|close| head.get(..close)).unwrap_or_default(); + ids.iter().any(|id| head.windows(id.len()).any(|w| w == id.as_bytes())) + }; + // The first start from `from` that begins before `to`. + let start_in = |mut from: usize, to: usize| loop { + let at = find(from, to, BEGIN)?; + if is_header(at) { + return Some(at); + } + from = at + BEGIN.len(); + }; + let mut start = start_in(0, len)?; loop { let end_tag = find(start + BEGIN.len(), len, END)?; - while let Some(next) = find(start + BEGIN.len(), end_tag, BEGIN) { + while let Some(next) = start_in(start + BEGIN.len(), end_tag) { start = next; } let after = end_tag + END.len(); - let next = find(after, len, BEGIN); + let next = start_in(after, len); match find(after, next.unwrap_or(len), b"?>") { Some(close) => return Some(PacketSpan { start, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }), None => start = next?, diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 964e9acf89..9d7db14901 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -772,25 +772,29 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J } let value = xml_text(i, &arg(args, 4), what)?; let found = array_items(i, o, &ns, &name, what)?; - let at = match found { + // A new array is added in the same change that sets its item, so a refused change adds nothing. + let (at, new) = match found { Some((at, _, _)) if !is_alt_text(i, o, at)? => return Err(not_alt_text(i, what, &name)), - Some((at, _, _)) => at, - None => { - let prop = xmp::Prop { ns: ns.clone(), name: name.clone(), value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } }; - change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop))?; - meta_of(i, o)?.find(&ns, &name).unwrap_or(0) - } + Some((at, _, _)) => (Some(at), None), + None => (None, Some(xmp::Prop { ns, name, value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } })), }; // An item and the `x-default` item change, or every item with the text of the `x-default` one. - let changed = match meta_of(i, o)?.props.get(at).map(|p| &p.value) { + let changed = match at.and_then(|at| meta_of(i, o).ok()?.props.get(at)).map(|p| &p.value) { Some(xmp::Value::Array { items, .. }) if specific.eq_ignore_ascii_case("x-default") => { let old = items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default")).map(|i| &i.text); items.iter().filter(|i| Some(&i.text) == old).count().max(2) } _ => 2, }; - let grow = changed.saturating_mul(64 + value.len() + specific.len()); + let grow = changed.saturating_mul(64 + value.len() + specific.len()).saturating_add(new.as_ref().map_or(0, xmp::Prop::heap_bytes)); change(i, o, grow, |m, _| { + let at = match new { + Some(prop) => { + m.props.push(prop); + m.props.len() - 1 + } + None => at.unwrap_or(usize::MAX), + }; let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|p| &mut p.value) else { return }; set_lang(items, &generic, &specific, value); })?; diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index de94872808..293b4d3157 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -211,6 +211,11 @@ fn packets_are_found_in_file_bytes() { let open_end = format!(" junk image/svg+xml", "]]>"); + let bytes = format!("binary\0{inner}"); + assert_eq!(xmp::find_packet(bytes.as_bytes()).map(|s| (s.start, s.end)), Some((7, bytes.len()))); } /// An array whose container declares the RDF prefix itself is read as an array, also when its @@ -344,6 +349,35 @@ fn localized_text_updates_a_single_generic_language_item() { assert_eq!(string(src), "2|Color|Color|4|Couleur|Color"); } +/// A `setLocalizedText` that stops at the heap limit adds no array. The heap limits tried run from +/// one that holds the text to one that also holds the change. +#[test] +fn localized_text_past_the_heap_limit_adds_no_array() { + let mut stopped = 0; + let mut seen = vec![]; + for step in 0..128 { + let mut r = Realm::with_options(crate::Options::default(), Limits { heap_bytes: (256 << 10) + step * (16 << 10), ..Limits::default() }); + if let Err(e) = r.define_external_object() { + panic!("{e:?}"); + } + let text = "new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta(); var s = 'x'; for (var k = 0; k < 18; k++) s += s;"; + if let Err(e) = r.run(text) { + seen.push(format!("{step} text {e:?}")); + continue; + } + if r.run("m.setLocalizedText(XMPConst.NS_DC, 'title', null, s, s);").is_ok() { + seen.push(format!("{step} set")); + break; + } + stopped += 1; + match r.run("m.doesPropertyExist(XMPConst.NS_DC, 'title')") { + Ok(v) => assert_eq!(v, JsValue::Bool(false), "heap step {step}"), + Err(e) => panic!("{e:?}"), + } + } + assert!(stopped > 0, "no heap limit stopped the change: {seen:?}"); +} + /// Setting the `x-default` item also changes the items that had its text, and leaves the others. #[test] fn localized_text_for_x_default_changes_the_items_that_matched_it() { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a931d02068..e4271f7926 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6573,21 +6573,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg the script passed more data to and from commands than one run may pass l'script ha passat més dades a les ordres i des de les ordres de les que pot passar una execució @msg the script added more objects and data to the documents than one run may add l'script ha afegit als documents més objectes i dades dels que pot afegir una execució @msg {what}: the object is not a File or a Folder {what}: l'objecte no és un File ni un Folder -@msg {what}: the library {name} is not available {what}: la biblioteca {name} no està disponible -@msg {what} is not available yet {what} encara no està disponible -@msg {what}: the value {value} is not available yet {what}: el valor {value} encara no està disponible -@msg {what}: the object is not an {class} object {what}: l'objecte no és un objecte {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: el paquet XMP no és XMP ben format -@msg {what}: the XMP data is too large {what}: les dades XMP són massa grans -@msg {what}: {name} is not a valid property name {what}: {name} no és un nom de propietat vàlid -@msg {what}: the text holds a character XML does not allow {what}: el text conté un caràcter que XML no permet -@msg {what}: {name} is not an array {what}: {name} no és una matriu -@msg {what}: {name} is not a simple property {what}: {name} no és una propietat simple -@msg {what}: {name} is not a language alternative array {what}: {name} no és una matriu d'alternatives d'idioma -@msg {what}: the array index {index} is out of range {what}: l'índex de matriu {index} és fora de l'interval -@msg {what}: the namespace {uri} is not registered {what}: l'espai de noms {uri} no està registrat -@msg {what}: the file is closed {what}: el fitxer està tancat -@msg {what}: the file cannot be updated {what}: el fitxer no es pot actualitzar @msg {what}: the count must be a finite number, 0 or more {what}: el recompte ha de ser un nombre finit, 0 o més @msg File.seek: the position must be a finite number File.seek: la posició ha de ser un nombre finit @msg File.seek: the mode must be 0, 1 or 2 File.seek: el mode ha de ser 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e4c6c614ad..488df173c3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5368,21 +5368,6 @@ liquify-list-end {0}, {1} {0} a {1} @msg the script passed more data to and from commands than one run may pass skript předal příkazům a z příkazů více dat, než smí předat jeden běh @msg the script added more objects and data to the documents than one run may add skript přidal do dokumentů více objektů a dat, než smí přidat jeden běh @msg {what}: the object is not a File or a Folder {what}: objekt není File ani Folder -@msg {what}: the library {name} is not available {what}: knihovna {name} není k dispozici -@msg {what} is not available yet {what} zatím není k dispozici -@msg {what}: the value {value} is not available yet {what}: hodnota {value} zatím není k dispozici -@msg {what}: the object is not an {class} object {what}: objekt není objekt {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: paket XMP není správně utvořené XMP -@msg {what}: the XMP data is too large {what}: data XMP jsou příliš velká -@msg {what}: {name} is not a valid property name {what}: {name} není platný název vlastnosti -@msg {what}: the text holds a character XML does not allow {what}: text obsahuje znak, který XML nepovoluje -@msg {what}: {name} is not an array {what}: {name} není pole -@msg {what}: {name} is not a simple property {what}: {name} není jednoduchá vlastnost -@msg {what}: {name} is not a language alternative array {what}: {name} není pole jazykových alternativ -@msg {what}: the array index {index} is out of range {what}: index pole {index} je mimo rozsah -@msg {what}: the namespace {uri} is not registered {what}: obor názvů {uri} není registrován -@msg {what}: the file is closed {what}: soubor je zavřený -@msg {what}: the file cannot be updated {what}: soubor nelze aktualizovat @msg {what}: the count must be a finite number, 0 or more {what}: počet musí být konečné číslo, 0 nebo více @msg File.seek: the position must be a finite number File.seek: pozice musí být konečné číslo @msg File.seek: the mode must be 0, 1 or 2 File.seek: režim musí být 0, 1 nebo 2 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7c2c34978b..302ab6aa69 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -216,21 +216,6 @@ liquify-list-end {0}, {1} {0} og {1} @msg the script passed more data to and from commands than one run may pass scriptet sendte flere data til og fra kommandoer, end én kørsel må sende @msg the script added more objects and data to the documents than one run may add scriptet tilføjede flere objekter og data til dokumenterne, end én kørsel må tilføje @msg {what}: the object is not a File or a Folder {what}: objektet er ikke en File eller en Folder -@msg {what}: the library {name} is not available {what}: biblioteket {name} er ikke tilgængeligt -@msg {what} is not available yet {what} er endnu ikke tilgængelig -@msg {what}: the value {value} is not available yet {what}: værdien {value} er endnu ikke tilgængelig -@msg {what}: the object is not an {class} object {what}: objektet er ikke et {class}-objekt -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-pakken er ikke velformet XMP -@msg {what}: the XMP data is too large {what}: XMP-dataene er for store -@msg {what}: {name} is not a valid property name {what}: {name} er ikke et gyldigt egenskabsnavn -@msg {what}: the text holds a character XML does not allow {what}: teksten indeholder et tegn, som XML ikke tillader -@msg {what}: {name} is not an array {what}: {name} er ikke en matrix -@msg {what}: {name} is not a simple property {what}: {name} er ikke en simpel egenskab -@msg {what}: {name} is not a language alternative array {what}: {name} er ikke en matrix af sprogalternativer -@msg {what}: the array index {index} is out of range {what}: matrixindekset {index} er uden for området -@msg {what}: the namespace {uri} is not registered {what}: navnerummet {uri} er ikke registreret -@msg {what}: the file is closed {what}: filen er lukket -@msg {what}: the file cannot be updated {what}: filen kan ikke opdateres @msg {what}: the count must be a finite number, 0 or more {what}: antallet skal være et endeligt tal, 0 eller mere @msg File.seek: the position must be a finite number File.seek: positionen skal være et endeligt tal @msg File.seek: the mode must be 0, 1 or 2 File.seek: tilstanden skal være 0, 1 eller 2 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d36b965b27..9482345f18 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4953,21 +4953,6 @@ liquify-list-end {0}, {1} {0} und {1} @msg the script passed more data to and from commands than one run may pass das Skript hat mehr Daten an Befehle und von Befehlen übergeben, als ein Lauf übergeben darf @msg the script added more objects and data to the documents than one run may add das Skript hat den Dokumenten mehr Objekte und Daten hinzugefügt, als ein Lauf hinzufügen darf @msg {what}: the object is not a File or a Folder {what}: Das Objekt ist weder ein File noch ein Folder -@msg {what}: the library {name} is not available {what}: Die Bibliothek {name} ist nicht verfügbar -@msg {what} is not available yet {what} ist noch nicht verfügbar -@msg {what}: the value {value} is not available yet {what}: Der Wert {value} ist noch nicht verfügbar -@msg {what}: the object is not an {class} object {what}: Das Objekt ist kein {class}-Objekt -@msg {what}: the XMP packet is not well-formed XMP {what}: Das XMP-Paket ist kein wohlgeformtes XMP -@msg {what}: the XMP data is too large {what}: Die XMP-Daten sind zu groß -@msg {what}: {name} is not a valid property name {what}: {name} ist kein gültiger Eigenschaftsname -@msg {what}: the text holds a character XML does not allow {what}: Der Text enthält ein Zeichen, das XML nicht zulässt -@msg {what}: {name} is not an array {what}: {name} ist kein Array -@msg {what}: {name} is not a simple property {what}: {name} ist keine einfache Eigenschaft -@msg {what}: {name} is not a language alternative array {what}: {name} ist kein Array mit Sprachalternativen -@msg {what}: the array index {index} is out of range {what}: Der Array-Index {index} liegt außerhalb des Bereichs -@msg {what}: the namespace {uri} is not registered {what}: Der Namensraum {uri} ist nicht registriert -@msg {what}: the file is closed {what}: Die Datei ist geschlossen -@msg {what}: the file cannot be updated {what}: Die Datei kann nicht aktualisiert werden @msg {what}: the count must be a finite number, 0 or more {what}: Die Anzahl muss eine endliche Zahl sein, 0 oder mehr @msg File.seek: the position must be a finite number File.seek: Die Position muss eine endliche Zahl sein @msg File.seek: the mode must be 0, 1 or 2 File.seek: Der Modus muss 0, 1 oder 2 sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ac46fef527..434d0cc0b8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2770,21 +2770,6 @@ liquify-list-end {0}, {1} {0} και {1} @msg the script passed more data to and from commands than one run may pass το σενάριο μετέφερε περισσότερα δεδομένα προς και από εντολές από όσα επιτρέπονται σε μία εκτέλεση @msg the script added more objects and data to the documents than one run may add το σενάριο πρόσθεσε στα έγγραφα περισσότερα αντικείμενα και δεδομένα από όσα επιτρέπονται σε μία εκτέλεση @msg {what}: the object is not a File or a Folder {what}: το αντικείμενο δεν είναι File ούτε Folder -@msg {what}: the library {name} is not available {what}: η βιβλιοθήκη {name} δεν είναι διαθέσιμη -@msg {what} is not available yet {what} δεν είναι ακόμη διαθέσιμο -@msg {what}: the value {value} is not available yet {what}: η τιμή {value} δεν είναι ακόμη διαθέσιμη -@msg {what}: the object is not an {class} object {what}: το αντικείμενο δεν είναι αντικείμενο {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: το πακέτο XMP δεν είναι σωστά διαμορφωμένο XMP -@msg {what}: the XMP data is too large {what}: τα δεδομένα XMP είναι πολύ μεγάλα -@msg {what}: {name} is not a valid property name {what}: το {name} δεν είναι έγκυρο όνομα ιδιότητας -@msg {what}: the text holds a character XML does not allow {what}: το κείμενο περιέχει χαρακτήρα που η XML δεν επιτρέπει -@msg {what}: {name} is not an array {what}: το {name} δεν είναι πίνακας -@msg {what}: {name} is not a simple property {what}: το {name} δεν είναι απλή ιδιότητα -@msg {what}: {name} is not a language alternative array {what}: το {name} δεν είναι πίνακας γλωσσικών εναλλακτικών -@msg {what}: the array index {index} is out of range {what}: ο δείκτης πίνακα {index} είναι εκτός εύρους -@msg {what}: the namespace {uri} is not registered {what}: ο χώρος ονομάτων {uri} δεν είναι καταχωρισμένος -@msg {what}: the file is closed {what}: το αρχείο είναι κλειστό -@msg {what}: the file cannot be updated {what}: το αρχείο δεν μπορεί να ενημερωθεί @msg {what}: the count must be a finite number, 0 or more {what}: το πλήθος πρέπει να είναι πεπερασμένος αριθμός, 0 ή περισσότερο @msg File.seek: the position must be a finite number File.seek: η θέση πρέπει να είναι πεπερασμένος αριθμός @msg File.seek: the mode must be 0, 1 or 2 File.seek: ο τρόπος πρέπει να είναι 0, 1 ή 2 diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 415b46a8b0..3f83e928e4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5045,21 +5045,6 @@ liquify-list-end {0}, {1} {0}, {1} @msg the script passed more data to and from commands than one run may pass el script pasó más datos a los comandos y desde ellos de los que puede pasar una ejecución @msg the script added more objects and data to the documents than one run may add el script añadió a los documentos más objetos y datos de los que puede añadir una ejecución @msg {what}: the object is not a File or a Folder {what}: el objeto no es un File ni un Folder -@msg {what}: the library {name} is not available {what}: la biblioteca {name} no está disponible -@msg {what} is not available yet {what} aún no está disponible -@msg {what}: the value {value} is not available yet {what}: el valor {value} aún no está disponible -@msg {what}: the object is not an {class} object {what}: el objeto no es un objeto {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: el paquete XMP no es XMP bien formado -@msg {what}: the XMP data is too large {what}: los datos XMP son demasiado grandes -@msg {what}: {name} is not a valid property name {what}: {name} no es un nombre de propiedad válido -@msg {what}: the text holds a character XML does not allow {what}: el texto contiene un carácter que XML no permite -@msg {what}: {name} is not an array {what}: {name} no es una matriz -@msg {what}: {name} is not a simple property {what}: {name} no es una propiedad simple -@msg {what}: {name} is not a language alternative array {what}: {name} no es una matriz de alternativas de idioma -@msg {what}: the array index {index} is out of range {what}: el índice de matriz {index} está fuera de rango -@msg {what}: the namespace {uri} is not registered {what}: el espacio de nombres {uri} no está registrado -@msg {what}: the file is closed {what}: el archivo está cerrado -@msg {what}: the file cannot be updated {what}: el archivo no se puede actualizar @msg {what}: the count must be a finite number, 0 or more {what}: la cantidad debe ser un número finito, 0 o más @msg File.seek: the position must be a finite number File.seek: la posición debe ser un número finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: el modo debe ser 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ad7e813fe5..a4d85b23e8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5286,21 +5286,6 @@ liquify-list-end {0}, {1} {0} ja {1} @msg the script passed more data to and from commands than one run may pass skripti välitti komennoille ja komennoilta enemmän tietoa kuin yksi ajo saa välittää @msg the script added more objects and data to the documents than one run may add skripti lisäsi asiakirjoihin enemmän objekteja ja tietoja kuin yksi ajo saa lisätä @msg {what}: the object is not a File or a Folder {what}: objekti ei ole File eikä Folder -@msg {what}: the library {name} is not available {what}: kirjasto {name} ei ole käytettävissä -@msg {what} is not available yet {what} ei ole vielä käytettävissä -@msg {what}: the value {value} is not available yet {what}: arvo {value} ei ole vielä käytettävissä -@msg {what}: the object is not an {class} object {what}: objekti ei ole {class}-objekti -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-paketti ei ole hyvin muodostettua XMP:tä -@msg {what}: the XMP data is too large {what}: XMP-tiedot ovat liian suuret -@msg {what}: {name} is not a valid property name {what}: {name} ei ole kelvollinen ominaisuuden nimi -@msg {what}: the text holds a character XML does not allow {what}: teksti sisältää merkin, jota XML ei salli -@msg {what}: {name} is not an array {what}: {name} ei ole taulukko -@msg {what}: {name} is not a simple property {what}: {name} ei ole yksinkertainen ominaisuus -@msg {what}: {name} is not a language alternative array {what}: {name} ei ole kielivaihtoehtojen taulukko -@msg {what}: the array index {index} is out of range {what}: taulukon indeksi {index} on alueen ulkopuolella -@msg {what}: the namespace {uri} is not registered {what}: nimiavaruutta {uri} ei ole rekisteröity -@msg {what}: the file is closed {what}: tiedosto on suljettu -@msg {what}: the file cannot be updated {what}: tiedostoa ei voi päivittää @msg {what}: the count must be a finite number, 0 or more {what}: määrän on oltava äärellinen luku, 0 tai enemmän @msg File.seek: the position must be a finite number File.seek: sijainnin on oltava äärellinen luku @msg File.seek: the mode must be 0, 1 or 2 File.seek: tilan on oltava 0, 1 tai 2 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 40cd203c0e..8f56486157 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5013,21 +5013,6 @@ liquify-list-end {0}, {1} {0} et {1} @msg the script made more host calls than one run may make le script a fait plus d’appels à l’hôte qu’une exécution ne peut en faire @msg the script passed more data to and from commands than one run may pass le script a transmis plus de données vers et depuis les commandes qu’une exécution ne peut en transmettre @msg the script added more objects and data to the documents than one run may add le script a ajouté aux documents plus d’objets et de données qu’une exécution ne peut en ajouter -@msg {what}: the library {name} is not available {what} : la bibliothèque {name} n’est pas disponible -@msg {what} is not available yet {what} n’est pas encore disponible -@msg {what}: the value {value} is not available yet {what} : la valeur {value} n’est pas encore disponible -@msg {what}: the object is not an {class} object {what} : l’objet n’est pas un objet {class} -@msg {what}: the XMP packet is not well-formed XMP {what} : le paquet XMP n’est pas du XMP bien formé -@msg {what}: the XMP data is too large {what} : les données XMP sont trop volumineuses -@msg {what}: {name} is not a valid property name {what} : {name} n’est pas un nom de propriété valide -@msg {what}: the text holds a character XML does not allow {what} : le texte contient un caractère que XML n’autorise pas -@msg {what}: {name} is not an array {what} : {name} n’est pas un tableau -@msg {what}: {name} is not a simple property {what} : {name} n’est pas une propriété simple -@msg {what}: {name} is not a language alternative array {what} : {name} n’est pas un tableau d’alternatives linguistiques -@msg {what}: the array index {index} is out of range {what} : l’index de tableau {index} est hors limites -@msg {what}: the namespace {uri} is not registered {what} : l’espace de noms {uri} n’est pas enregistré -@msg {what}: the file is closed {what} : le fichier est fermé -@msg {what}: the file cannot be updated {what} : le fichier ne peut pas être mis à jour @msg {what}: the object is not a File or a Folder {what} : l’objet n’est ni un File ni un Folder @msg {what}: the count must be a finite number, 0 or more {what} : le nombre doit être un nombre fini, 0 ou plus @msg File.seek: the position must be a finite number File.seek : la position doit être un nombre fini diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 331aa30575..e9509d9202 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7719,21 +7719,6 @@ liquify-list-end {0}, {1} {0} और {1} @msg the script passed more data to and from commands than one run may pass स्क्रिप्ट ने कमांड को और कमांड से एक रन में अनुमत से अधिक डेटा भेजा @msg the script added more objects and data to the documents than one run may add स्क्रिप्ट ने दस्तावेज़ों में एक रन में अनुमत से अधिक ऑब्जेक्ट और डेटा जोड़े @msg {what}: the object is not a File or a Folder {what}: ऑब्जेक्ट न File है न Folder -@msg {what}: the library {name} is not available {what}: लाइब्रेरी {name} उपलब्ध नहीं है -@msg {what} is not available yet {what} अभी उपलब्ध नहीं है -@msg {what}: the value {value} is not available yet {what}: मान {value} अभी उपलब्ध नहीं है -@msg {what}: the object is not an {class} object {what}: ऑब्जेक्ट {class} ऑब्जेक्ट नहीं है -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP पैकेट सही ढंग से बना XMP नहीं है -@msg {what}: the XMP data is too large {what}: XMP डेटा बहुत बड़ा है -@msg {what}: {name} is not a valid property name {what}: {name} मान्य प्रॉपर्टी नाम नहीं है -@msg {what}: the text holds a character XML does not allow {what}: टेक्स्ट में ऐसा वर्ण है जिसकी XML अनुमति नहीं देता -@msg {what}: {name} is not an array {what}: {name} ऐरे नहीं है -@msg {what}: {name} is not a simple property {what}: {name} सरल प्रॉपर्टी नहीं है -@msg {what}: {name} is not a language alternative array {what}: {name} भाषा विकल्पों का ऐरे नहीं है -@msg {what}: the array index {index} is out of range {what}: ऐरे इंडेक्स {index} सीमा से बाहर है -@msg {what}: the namespace {uri} is not registered {what}: नेमस्पेस {uri} पंजीकृत नहीं है -@msg {what}: the file is closed {what}: फ़ाइल बंद है -@msg {what}: the file cannot be updated {what}: फ़ाइल अपडेट नहीं की जा सकती @msg {what}: the count must be a finite number, 0 or more {what}: गिनती एक सीमित संख्या होनी चाहिए, 0 या अधिक @msg File.seek: the position must be a finite number File.seek: स्थिति एक सीमित संख्या होनी चाहिए @msg File.seek: the mode must be 0, 1 or 2 File.seek: मोड 0, 1 या 2 होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8171b8d3f6..87f050ef0d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5885,21 +5885,6 @@ liquify-list-end {0}, {1} {0} és {1} @msg the script passed more data to and from commands than one run may pass a parancsfájl több adatot adott át a parancsoknak és a parancsoktól, mint amennyit egy futás átadhat @msg the script added more objects and data to the documents than one run may add a parancsfájl több objektumot és adatot adott a dokumentumokhoz, mint amennyit egy futás hozzáadhat @msg {what}: the object is not a File or a Folder {what}: az objektum nem File és nem Folder -@msg {what}: the library {name} is not available {what}: a(z) {name} könyvtár nem érhető el -@msg {what} is not available yet {what} még nem érhető el -@msg {what}: the value {value} is not available yet {what}: a(z) {value} érték még nem érhető el -@msg {what}: the object is not an {class} object {what}: az objektum nem {class} objektum -@msg {what}: the XMP packet is not well-formed XMP {what}: az XMP-csomag nem jól formázott XMP -@msg {what}: the XMP data is too large {what}: az XMP-adatok túl nagyok -@msg {what}: {name} is not a valid property name {what}: a(z) {name} nem érvényes tulajdonságnév -@msg {what}: the text holds a character XML does not allow {what}: a szöveg olyan karaktert tartalmaz, amelyet az XML nem enged meg -@msg {what}: {name} is not an array {what}: a(z) {name} nem tömb -@msg {what}: {name} is not a simple property {what}: a(z) {name} nem egyszerű tulajdonság -@msg {what}: {name} is not a language alternative array {what}: a(z) {name} nem nyelvi alternatívák tömbje -@msg {what}: the array index {index} is out of range {what}: a(z) {index} tömbindex a tartományon kívül esik -@msg {what}: the namespace {uri} is not registered {what}: a(z) {uri} névtér nincs regisztrálva -@msg {what}: the file is closed {what}: a fájl be van zárva -@msg {what}: the file cannot be updated {what}: a fájl nem frissíthető @msg {what}: the count must be a finite number, 0 or more {what}: a darabszámnak véges számnak kell lennie, 0 vagy több @msg File.seek: the position must be a finite number File.seek: a pozíciónak véges számnak kell lennie @msg File.seek: the mode must be 0, 1 or 2 File.seek: a mód csak 0, 1 vagy 2 lehet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4e1170ad31..924d3d80b5 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -159,21 +159,6 @@ @msg the script passed more data to and from commands than one run may pass skrip mengirim lebih banyak data ke dan dari perintah daripada yang boleh dikirim satu proses @msg the script added more objects and data to the documents than one run may add skrip menambahkan lebih banyak objek dan data ke dokumen daripada yang boleh ditambahkan satu proses @msg {what}: the object is not a File or a Folder {what}: objek bukan File atau Folder -@msg {what}: the library {name} is not available {what}: pustaka {name} tidak tersedia -@msg {what} is not available yet {what} belum tersedia -@msg {what}: the value {value} is not available yet {what}: nilai {value} belum tersedia -@msg {what}: the object is not an {class} object {what}: objek bukan objek {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: paket XMP bukan XMP yang tersusun dengan benar -@msg {what}: the XMP data is too large {what}: data XMP terlalu besar -@msg {what}: {name} is not a valid property name {what}: {name} bukan nama properti yang valid -@msg {what}: the text holds a character XML does not allow {what}: teks berisi karakter yang tidak diizinkan XML -@msg {what}: {name} is not an array {what}: {name} bukan larik -@msg {what}: {name} is not a simple property {what}: {name} bukan properti sederhana -@msg {what}: {name} is not a language alternative array {what}: {name} bukan larik alternatif bahasa -@msg {what}: the array index {index} is out of range {what}: indeks larik {index} di luar rentang -@msg {what}: the namespace {uri} is not registered {what}: ruang nama {uri} tidak terdaftar -@msg {what}: the file is closed {what}: berkas tertutup -@msg {what}: the file cannot be updated {what}: berkas tidak dapat diperbarui @msg {what}: the count must be a finite number, 0 or more {what}: jumlah harus berupa angka berhingga, 0 atau lebih @msg File.seek: the position must be a finite number File.seek: posisi harus berupa angka berhingga @msg File.seek: the mode must be 0, 1 or 2 File.seek: mode harus 0, 1 atau 2 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 3638fab939..5f47e3f117 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5091,21 +5091,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg the script passed more data to and from commands than one run may pass lo script ha passato ai comandi e dai comandi più dati di quanti ne possa passare un'esecuzione @msg the script added more objects and data to the documents than one run may add lo script ha aggiunto ai documenti più oggetti e dati di quanti ne possa aggiungere un'esecuzione @msg {what}: the object is not a File or a Folder {what}: l'oggetto non è un File né un Folder -@msg {what}: the library {name} is not available {what}: la libreria {name} non è disponibile -@msg {what} is not available yet {what} non è ancora disponibile -@msg {what}: the value {value} is not available yet {what}: il valore {value} non è ancora disponibile -@msg {what}: the object is not an {class} object {what}: l'oggetto non è un oggetto {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: il pacchetto XMP non è XMP ben formato -@msg {what}: the XMP data is too large {what}: i dati XMP sono troppo grandi -@msg {what}: {name} is not a valid property name {what}: {name} non è un nome di proprietà valido -@msg {what}: the text holds a character XML does not allow {what}: il testo contiene un carattere che XML non consente -@msg {what}: {name} is not an array {what}: {name} non è un array -@msg {what}: {name} is not a simple property {what}: {name} non è una proprietà semplice -@msg {what}: {name} is not a language alternative array {what}: {name} non è un array di alternative di lingua -@msg {what}: the array index {index} is out of range {what}: l'indice di array {index} è fuori intervallo -@msg {what}: the namespace {uri} is not registered {what}: lo spazio dei nomi {uri} non è registrato -@msg {what}: the file is closed {what}: il file è chiuso -@msg {what}: the file cannot be updated {what}: il file non può essere aggiornato @msg {what}: the count must be a finite number, 0 or more {what}: il conteggio deve essere un numero finito, 0 o più @msg File.seek: the position must be a finite number File.seek: la posizione deve essere un numero finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: la modalità deve essere 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d40d4202d1..9a1b5f6354 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5917,21 +5917,6 @@ liquify-list-end {0}, {1} {0}、{1} @msg the script passed more data to and from commands than one run may pass スクリプトが 1 回の実行で許されるより多くのデータをコマンドとやり取りしました @msg the script added more objects and data to the documents than one run may add スクリプトが 1 回の実行で許されるより多くのオブジェクトとデータをドキュメントに追加しました @msg {what}: the object is not a File or a Folder {what}: オブジェクトは File でも Folder でもありません -@msg {what}: the library {name} is not available {what}: ライブラリ {name} は利用できません -@msg {what} is not available yet {what} はまだ利用できません -@msg {what}: the value {value} is not available yet {what}: 値 {value} はまだ利用できません -@msg {what}: the object is not an {class} object {what}: オブジェクトは {class} オブジェクトではありません -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP パケットが整形式の XMP ではありません -@msg {what}: the XMP data is too large {what}: XMP データが大きすぎます -@msg {what}: {name} is not a valid property name {what}: {name} は有効なプロパティ名ではありません -@msg {what}: the text holds a character XML does not allow {what}: テキストに XML で使えない文字が含まれています -@msg {what}: {name} is not an array {what}: {name} は配列ではありません -@msg {what}: {name} is not a simple property {what}: {name} は単純なプロパティではありません -@msg {what}: {name} is not a language alternative array {what}: {name} は言語の代替配列ではありません -@msg {what}: the array index {index} is out of range {what}: 配列のインデックス {index} が範囲外です -@msg {what}: the namespace {uri} is not registered {what}: 名前空間 {uri} は登録されていません -@msg {what}: the file is closed {what}: ファイルは閉じています -@msg {what}: the file cannot be updated {what}: ファイルを更新できません @msg {what}: the count must be a finite number, 0 or more {what}: 数は 0 以上の有限の数値にしてください @msg File.seek: the position must be a finite number File.seek: 位置は有限の数値にしてください @msg File.seek: the mode must be 0, 1 or 2 File.seek: モードは 0, 1 または 2 にしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 48372764c1..8eeacee621 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8586,21 +8586,6 @@ liquify-list-end {0}, {1} {0} და {1} @msg the script passed more data to and from commands than one run may pass სკრიპტმა ბრძანებებს და ბრძანებებიდან იმაზე მეტი მონაცემი გადასცა, ვიდრე ერთ გაშვებას შეუძლია @msg the script added more objects and data to the documents than one run may add სკრიპტმა დოკუმენტებს იმაზე მეტი ობიექტი და მონაცემი დაამატა, ვიდრე ერთ გაშვებას შეუძლია @msg {what}: the object is not a File or a Folder {what}: ობიექტი არც File-ია და არც Folder -@msg {what}: the library {name} is not available {what}: ბიბლიოთეკა {name} მიუწვდომელია -@msg {what} is not available yet {what} ჯერ მიუწვდომელია -@msg {what}: the value {value} is not available yet {what}: მნიშვნელობა {value} ჯერ მიუწვდომელია -@msg {what}: the object is not an {class} object {what}: ობიექტი არ არის {class} ობიექტი -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP პაკეტი არ არის სწორად აგებული XMP -@msg {what}: the XMP data is too large {what}: XMP მონაცემები ზედმეტად დიდია -@msg {what}: {name} is not a valid property name {what}: {name} არ არის თვისების სწორი სახელი -@msg {what}: the text holds a character XML does not allow {what}: ტექსტი შეიცავს სიმბოლოს, რომელსაც XML არ უშვებს -@msg {what}: {name} is not an array {what}: {name} არ არის მასივი -@msg {what}: {name} is not a simple property {what}: {name} არ არის მარტივი თვისება -@msg {what}: {name} is not a language alternative array {what}: {name} არ არის ენობრივი ალტერნატივების მასივი -@msg {what}: the array index {index} is out of range {what}: მასივის ინდექსი {index} დიაპაზონს გარეთაა -@msg {what}: the namespace {uri} is not registered {what}: სახელთა სივრცე {uri} არ არის რეგისტრირებული -@msg {what}: the file is closed {what}: ფაილი დახურულია -@msg {what}: the file cannot be updated {what}: ფაილის განახლება შეუძლებელია @msg {what}: the count must be a finite number, 0 or more {what}: რაოდენობა უნდა იყოს სასრული რიცხვი, 0 ან მეტი @msg File.seek: the position must be a finite number File.seek: პოზიცია უნდა იყოს სასრული რიცხვი @msg File.seek: the mode must be 0, 1 or 2 File.seek: რეჟიმი უნდა იყოს 0, 1 ან 2 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3e85928817..57e0b8be10 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5846,21 +5846,6 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg the script passed more data to and from commands than one run may pass 스크립트가 한 번의 실행에 허용된 것보다 많은 데이터를 명령과 주고받았습니다 @msg the script added more objects and data to the documents than one run may add 스크립트가 한 번의 실행에 허용된 것보다 많은 객체와 데이터를 문서에 추가했습니다 @msg {what}: the object is not a File or a Folder {what}: 객체가 File도 Folder도 아닙니다 -@msg {what}: the library {name} is not available {what}: 라이브러리 {name}을(를) 사용할 수 없습니다 -@msg {what} is not available yet {what}은(는) 아직 사용할 수 없습니다 -@msg {what}: the value {value} is not available yet {what}: 값 {value}은(는) 아직 사용할 수 없습니다 -@msg {what}: the object is not an {class} object {what}: 객체가 {class} 객체가 아닙니다 -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP 패킷이 올바른 형식의 XMP가 아닙니다 -@msg {what}: the XMP data is too large {what}: XMP 데이터가 너무 큽니다 -@msg {what}: {name} is not a valid property name {what}: {name}은(는) 올바른 속성 이름이 아닙니다 -@msg {what}: the text holds a character XML does not allow {what}: 텍스트에 XML이 허용하지 않는 문자가 있습니다 -@msg {what}: {name} is not an array {what}: {name}은(는) 배열이 아닙니다 -@msg {what}: {name} is not a simple property {what}: {name}은(는) 단순 속성이 아닙니다 -@msg {what}: {name} is not a language alternative array {what}: {name}은(는) 언어 대체 배열이 아닙니다 -@msg {what}: the array index {index} is out of range {what}: 배열 인덱스 {index}이(가) 범위를 벗어났습니다 -@msg {what}: the namespace {uri} is not registered {what}: 네임스페이스 {uri}이(가) 등록되지 않았습니다 -@msg {what}: the file is closed {what}: 파일이 닫혀 있습니다 -@msg {what}: the file cannot be updated {what}: 파일을 업데이트할 수 없습니다 @msg {what}: the count must be a finite number, 0 or more {what}: 개수는 0 이상의 유한한 숫자여야 합니다 @msg File.seek: the position must be a finite number File.seek: 위치는 유한한 숫자여야 합니다 @msg File.seek: the mode must be 0, 1 or 2 File.seek: 모드는 0, 1 또는 2여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b23412f1ec..5ed5cdc3e0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -205,21 +205,6 @@ liquify-list-end {0}, {1} {0} en {1} @msg the script passed more data to and from commands than one run may pass het script heeft meer gegevens van en naar opdrachten doorgegeven dan één uitvoering mag doorgeven @msg the script added more objects and data to the documents than one run may add het script heeft meer objecten en gegevens aan de documenten toegevoegd dan één uitvoering mag toevoegen @msg {what}: the object is not a File or a Folder {what}: het object is geen File of Folder -@msg {what}: the library {name} is not available {what}: de bibliotheek {name} is niet beschikbaar -@msg {what} is not available yet {what} is nog niet beschikbaar -@msg {what}: the value {value} is not available yet {what}: de waarde {value} is nog niet beschikbaar -@msg {what}: the object is not an {class} object {what}: het object is geen {class}-object -@msg {what}: the XMP packet is not well-formed XMP {what}: het XMP-pakket is geen goed gevormde XMP -@msg {what}: the XMP data is too large {what}: de XMP-gegevens zijn te groot -@msg {what}: {name} is not a valid property name {what}: {name} is geen geldige eigenschapsnaam -@msg {what}: the text holds a character XML does not allow {what}: de tekst bevat een teken dat XML niet toestaat -@msg {what}: {name} is not an array {what}: {name} is geen array -@msg {what}: {name} is not a simple property {what}: {name} is geen eenvoudige eigenschap -@msg {what}: {name} is not a language alternative array {what}: {name} is geen array van taalalternatieven -@msg {what}: the array index {index} is out of range {what}: de array-index {index} valt buiten het bereik -@msg {what}: the namespace {uri} is not registered {what}: de naamruimte {uri} is niet geregistreerd -@msg {what}: the file is closed {what}: het bestand is gesloten -@msg {what}: the file cannot be updated {what}: het bestand kan niet worden bijgewerkt @msg {what}: the count must be a finite number, 0 or more {what}: het aantal moet een eindig getal zijn, 0 of meer @msg File.seek: the position must be a finite number File.seek: de positie moet een eindig getal zijn @msg File.seek: the mode must be 0, 1 or 2 File.seek: de modus moet 0, 1 of 2 zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index d12a0430d9..74029133dc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5196,21 +5196,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg the script passed more data to and from commands than one run may pass skrypt przekazał do poleceń i z poleceń więcej danych, niż może przekazać jedno uruchomienie @msg the script added more objects and data to the documents than one run may add skrypt dodał do dokumentów więcej obiektów i danych, niż może dodać jedno uruchomienie @msg {what}: the object is not a File or a Folder {what}: obiekt nie jest ani File, ani Folder -@msg {what}: the library {name} is not available {what}: biblioteka {name} jest niedostępna -@msg {what} is not available yet {what} nie jest jeszcze dostępne -@msg {what}: the value {value} is not available yet {what}: wartość {value} nie jest jeszcze dostępna -@msg {what}: the object is not an {class} object {what}: obiekt nie jest obiektem {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: pakiet XMP nie jest poprawnie zbudowanym XMP -@msg {what}: the XMP data is too large {what}: dane XMP są za duże -@msg {what}: {name} is not a valid property name {what}: {name} nie jest prawidłową nazwą właściwości -@msg {what}: the text holds a character XML does not allow {what}: tekst zawiera znak niedozwolony w XML -@msg {what}: {name} is not an array {what}: {name} nie jest tablicą -@msg {what}: {name} is not a simple property {what}: {name} nie jest prostą właściwością -@msg {what}: {name} is not a language alternative array {what}: {name} nie jest tablicą alternatyw językowych -@msg {what}: the array index {index} is out of range {what}: indeks tablicy {index} jest poza zakresem -@msg {what}: the namespace {uri} is not registered {what}: przestrzeń nazw {uri} nie jest zarejestrowana -@msg {what}: the file is closed {what}: plik jest zamknięty -@msg {what}: the file cannot be updated {what}: nie można zaktualizować pliku @msg {what}: the count must be a finite number, 0 or more {what}: liczba musi być liczbą skończoną, 0 lub większą @msg File.seek: the position must be a finite number File.seek: pozycja musi być liczbą skończoną @msg File.seek: the mode must be 0, 1 or 2 File.seek: tryb musi wynosić 0, 1 lub 2 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 868a243cef..a1747af0b2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6235,21 +6235,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg the script passed more data to and from commands than one run may pass o script passou mais dados para os comandos e a partir deles do que uma execução pode passar @msg the script added more objects and data to the documents than one run may add o script adicionou aos documentos mais objetos e dados do que uma execução pode adicionar @msg {what}: the object is not a File or a Folder {what}: o objeto não é um File nem um Folder -@msg {what}: the library {name} is not available {what}: a biblioteca {name} não está disponível -@msg {what} is not available yet {what} ainda não está disponível -@msg {what}: the value {value} is not available yet {what}: o valor {value} ainda não está disponível -@msg {what}: the object is not an {class} object {what}: o objeto não é um objeto {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: o pacote XMP não é um XMP bem formado -@msg {what}: the XMP data is too large {what}: os dados XMP são grandes demais -@msg {what}: {name} is not a valid property name {what}: {name} não é um nome de propriedade válido -@msg {what}: the text holds a character XML does not allow {what}: o texto contém um caractere que o XML não permite -@msg {what}: {name} is not an array {what}: {name} não é uma matriz -@msg {what}: {name} is not a simple property {what}: {name} não é uma propriedade simples -@msg {what}: {name} is not a language alternative array {what}: {name} não é uma matriz de alternativas de idioma -@msg {what}: the array index {index} is out of range {what}: o índice de matriz {index} está fora do intervalo -@msg {what}: the namespace {uri} is not registered {what}: o namespace {uri} não está registrado -@msg {what}: the file is closed {what}: o arquivo está fechado -@msg {what}: the file cannot be updated {what}: o arquivo não pode ser atualizado @msg {what}: the count must be a finite number, 0 or more {what}: a contagem deve ser um número finito, 0 ou mais @msg File.seek: the position must be a finite number File.seek: a posição deve ser um número finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: o modo deve ser 0, 1 ou 2 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9af201db91..ca0c8d5145 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5067,21 +5067,6 @@ liquify-list-end {0}, {1} {0} и {1} @msg the script passed more data to and from commands than one run may pass скрипт передал командам и получил от них больше данных, чем разрешено одному запуску @msg the script added more objects and data to the documents than one run may add скрипт добавил в документы больше объектов и данных, чем разрешено одному запуску @msg {what}: the object is not a File or a Folder {what}: объект не является ни File, ни Folder -@msg {what}: the library {name} is not available {what}: библиотека {name} недоступна -@msg {what} is not available yet {what} пока недоступно -@msg {what}: the value {value} is not available yet {what}: значение {value} пока недоступно -@msg {what}: the object is not an {class} object {what}: объект не является объектом {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: пакет XMP не является правильно построенным XMP -@msg {what}: the XMP data is too large {what}: данные XMP слишком велики -@msg {what}: {name} is not a valid property name {what}: {name} не является допустимым именем свойства -@msg {what}: the text holds a character XML does not allow {what}: текст содержит символ, недопустимый в XML -@msg {what}: {name} is not an array {what}: {name} не является массивом -@msg {what}: {name} is not a simple property {what}: {name} не является простым свойством -@msg {what}: {name} is not a language alternative array {what}: {name} не является массивом языковых вариантов -@msg {what}: the array index {index} is out of range {what}: индекс массива {index} вне диапазона -@msg {what}: the namespace {uri} is not registered {what}: пространство имен {uri} не зарегистрировано -@msg {what}: the file is closed {what}: файл закрыт -@msg {what}: the file cannot be updated {what}: файл нельзя обновить @msg {what}: the count must be a finite number, 0 or more {what}: количество должно быть конечным числом, 0 или больше @msg File.seek: the position must be a finite number File.seek: позиция должна быть конечным числом @msg File.seek: the mode must be 0, 1 or 2 File.seek: режим должен быть 0, 1 или 2 diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c69017b569..c26474cf93 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4942,21 +4942,6 @@ liquify-list-end {0}, {1} {0} och {1} @msg the script passed more data to and from commands than one run may pass skriptet skickade mer data till och från kommandon än en körning får skicka @msg the script added more objects and data to the documents than one run may add skriptet lade till fler objekt och mer data i dokumenten än en körning får lägga till @msg {what}: the object is not a File or a Folder {what}: objektet är varken en File eller en Folder -@msg {what}: the library {name} is not available {what}: biblioteket {name} är inte tillgängligt -@msg {what} is not available yet {what} är inte tillgängligt än -@msg {what}: the value {value} is not available yet {what}: värdet {value} är inte tillgängligt än -@msg {what}: the object is not an {class} object {what}: objektet är inte ett {class}-objekt -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-paketet är inte välformad XMP -@msg {what}: the XMP data is too large {what}: XMP-data är för stora -@msg {what}: {name} is not a valid property name {what}: {name} är inte ett giltigt egenskapsnamn -@msg {what}: the text holds a character XML does not allow {what}: texten innehåller ett tecken som XML inte tillåter -@msg {what}: {name} is not an array {what}: {name} är inte en matris -@msg {what}: {name} is not a simple property {what}: {name} är inte en enkel egenskap -@msg {what}: {name} is not a language alternative array {what}: {name} är inte en matris med språkalternativ -@msg {what}: the array index {index} is out of range {what}: matrisindexet {index} ligger utanför intervallet -@msg {what}: the namespace {uri} is not registered {what}: namnrymden {uri} är inte registrerad -@msg {what}: the file is closed {what}: filen är stängd -@msg {what}: the file cannot be updated {what}: filen kan inte uppdateras @msg {what}: the count must be a finite number, 0 or more {what}: antalet måste vara ett ändligt tal, 0 eller mer @msg File.seek: the position must be a finite number File.seek: positionen måste vara ett ändligt tal @msg File.seek: the mode must be 0, 1 or 2 File.seek: läget måste vara 0, 1 eller 2 diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 59fa066b58..82186ebcdd 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4789,21 +4789,6 @@ liquify-list-end {0}, {1} {0} ve {1} @msg the script passed more data to and from commands than one run may pass betik, komutlara ve komutlardan bir çalıştırmanın aktarabileceğinden daha fazla veri aktardı @msg the script added more objects and data to the documents than one run may add betik, belgelere bir çalıştırmanın ekleyebileceğinden daha fazla nesne ve veri ekledi @msg {what}: the object is not a File or a Folder {what}: nesne ne File ne de Folder -@msg {what}: the library {name} is not available {what}: {name} kitaplığı kullanılamıyor -@msg {what} is not available yet {what} henüz kullanılamıyor -@msg {what}: the value {value} is not available yet {what}: {value} değeri henüz kullanılamıyor -@msg {what}: the object is not an {class} object {what}: nesne bir {class} nesnesi değil -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP paketi düzgün biçimli XMP değil -@msg {what}: the XMP data is too large {what}: XMP verileri çok büyük -@msg {what}: {name} is not a valid property name {what}: {name} geçerli bir özellik adı değil -@msg {what}: the text holds a character XML does not allow {what}: metin XML'in izin vermediği bir karakter içeriyor -@msg {what}: {name} is not an array {what}: {name} bir dizi değil -@msg {what}: {name} is not a simple property {what}: {name} basit bir özellik değil -@msg {what}: {name} is not a language alternative array {what}: {name} bir dil alternatifleri dizisi değil -@msg {what}: the array index {index} is out of range {what}: {index} dizi dizini aralık dışında -@msg {what}: the namespace {uri} is not registered {what}: {uri} ad alanı kayıtlı değil -@msg {what}: the file is closed {what}: dosya kapalı -@msg {what}: the file cannot be updated {what}: dosya güncellenemiyor @msg {what}: the count must be a finite number, 0 or more {what}: sayı 0 veya daha büyük, sonlu bir sayı olmalıdır @msg File.seek: the position must be a finite number File.seek: konum sonlu bir sayı olmalıdır @msg File.seek: the mode must be 0, 1 or 2 File.seek: mod 0, 1 veya 2 olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dcde17615c..de3329ef10 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5075,21 +5075,6 @@ liquify-list-end {0}, {1} {0} і {1} @msg the script passed more data to and from commands than one run may pass скрипт передав командам і отримав від них більше даних, ніж дозволено одному запуску @msg the script added more objects and data to the documents than one run may add скрипт додав до документів більше об'єктів і даних, ніж дозволено одному запуску @msg {what}: the object is not a File or a Folder {what}: об'єкт не є ні File, ні Folder -@msg {what}: the library {name} is not available {what}: бібліотека {name} недоступна -@msg {what} is not available yet {what} поки що недоступне -@msg {what}: the value {value} is not available yet {what}: значення {value} поки що недоступне -@msg {what}: the object is not an {class} object {what}: об'єкт не є об'єктом {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: пакет XMP не є правильно побудованим XMP -@msg {what}: the XMP data is too large {what}: дані XMP завеликі -@msg {what}: {name} is not a valid property name {what}: {name} не є допустимою назвою властивості -@msg {what}: the text holds a character XML does not allow {what}: текст містить символ, який XML не дозволяє -@msg {what}: {name} is not an array {what}: {name} не є масивом -@msg {what}: {name} is not a simple property {what}: {name} не є простою властивістю -@msg {what}: {name} is not a language alternative array {what}: {name} не є масивом мовних варіантів -@msg {what}: the array index {index} is out of range {what}: індекс масиву {index} поза діапазоном -@msg {what}: the namespace {uri} is not registered {what}: простір імен {uri} не зареєстровано -@msg {what}: the file is closed {what}: файл закрито -@msg {what}: the file cannot be updated {what}: файл неможливо оновити @msg {what}: the count must be a finite number, 0 or more {what}: кількість має бути скінченним числом, 0 або більше @msg File.seek: the position must be a finite number File.seek: позиція має бути скінченним числом @msg File.seek: the mode must be 0, 1 or 2 File.seek: режим має бути 0, 1 або 2 diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 02d2aa1ff4..675143a8d6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5566,21 +5566,6 @@ liquify-list-end {0}, {1} {0} và {1} @msg the script passed more data to and from commands than one run may pass tập lệnh đã truyền đến và từ các lệnh nhiều dữ liệu hơn mức một lần chạy được phép @msg the script added more objects and data to the documents than one run may add tập lệnh đã thêm vào tài liệu nhiều đối tượng và dữ liệu hơn mức một lần chạy được phép @msg {what}: the object is not a File or a Folder {what}: đối tượng không phải File cũng không phải Folder -@msg {what}: the library {name} is not available {what}: thư viện {name} không khả dụng -@msg {what} is not available yet {what} chưa khả dụng -@msg {what}: the value {value} is not available yet {what}: giá trị {value} chưa khả dụng -@msg {what}: the object is not an {class} object {what}: đối tượng không phải đối tượng {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: gói XMP không phải XMP đúng định dạng -@msg {what}: the XMP data is too large {what}: dữ liệu XMP quá lớn -@msg {what}: {name} is not a valid property name {what}: {name} không phải tên thuộc tính hợp lệ -@msg {what}: the text holds a character XML does not allow {what}: văn bản chứa ký tự mà XML không cho phép -@msg {what}: {name} is not an array {what}: {name} không phải mảng -@msg {what}: {name} is not a simple property {what}: {name} không phải thuộc tính đơn -@msg {what}: {name} is not a language alternative array {what}: {name} không phải mảng phương án ngôn ngữ -@msg {what}: the array index {index} is out of range {what}: chỉ số mảng {index} nằm ngoài phạm vi -@msg {what}: the namespace {uri} is not registered {what}: không gian tên {uri} chưa được đăng ký -@msg {what}: the file is closed {what}: tệp đã đóng -@msg {what}: the file cannot be updated {what}: không thể cập nhật tệp @msg {what}: the count must be a finite number, 0 or more {what}: số lượng phải là một số hữu hạn, 0 trở lên @msg File.seek: the position must be a finite number File.seek: vị trí phải là một số hữu hạn @msg File.seek: the mode must be 0, 1 or 2 File.seek: chế độ phải là 0, 1 hoặc 2 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e20c89b2f1..57f6a4403b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5582,21 +5582,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg the script passed more data to and from commands than one run may pass 脚本与命令之间传递的数据超过了一次运行允许的数量 @msg the script added more objects and data to the documents than one run may add 脚本向文档添加的对象和数据超过了一次运行允许的数量 @msg {what}: the object is not a File or a Folder {what}:该对象既不是 File 也不是 Folder -@msg {what}: the library {name} is not available {what}:库 {name} 不可用 -@msg {what} is not available yet {what} 尚不可用 -@msg {what}: the value {value} is not available yet {what}:值 {value} 尚不可用 -@msg {what}: the object is not an {class} object {what}:该对象不是 {class} 对象 -@msg {what}: the XMP packet is not well-formed XMP {what}:XMP 数据包不是格式正确的 XMP -@msg {what}: the XMP data is too large {what}:XMP 数据过大 -@msg {what}: {name} is not a valid property name {what}:{name} 不是有效的属性名称 -@msg {what}: the text holds a character XML does not allow {what}:文本包含 XML 不允许的字符 -@msg {what}: {name} is not an array {what}:{name} 不是数组 -@msg {what}: {name} is not a simple property {what}:{name} 不是简单属性 -@msg {what}: {name} is not a language alternative array {what}:{name} 不是语言替代数组 -@msg {what}: the array index {index} is out of range {what}:数组索引 {index} 超出范围 -@msg {what}: the namespace {uri} is not registered {what}:命名空间 {uri} 未注册 -@msg {what}: the file is closed {what}:文件已关闭 -@msg {what}: the file cannot be updated {what}:文件无法更新 @msg {what}: the count must be a finite number, 0 or more {what}:数量必须是 0 或更大的有限数 @msg File.seek: the position must be a finite number File.seek:位置必须是有限数 @msg File.seek: the mode must be 0, 1 or 2 File.seek:模式必须是 0, 1 或 2 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c18488af0e..9834c17ea6 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2928,21 +2928,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg the script passed more data to and from commands than one run may pass 指令碼與命令之間傳遞的資料超過一次執行允許的數量 @msg the script added more objects and data to the documents than one run may add 指令碼加入文件的物件和資料超過一次執行允許的數量 @msg {what}: the object is not a File or a Folder {what}:此物件既不是 File 也不是 Folder -@msg {what}: the library {name} is not available {what}:程式庫 {name} 無法使用 -@msg {what} is not available yet {what} 尚無法使用 -@msg {what}: the value {value} is not available yet {what}:值 {value} 尚無法使用 -@msg {what}: the object is not an {class} object {what}:此物件不是 {class} 物件 -@msg {what}: the XMP packet is not well-formed XMP {what}:XMP 封包不是格式正確的 XMP -@msg {what}: the XMP data is too large {what}:XMP 資料過大 -@msg {what}: {name} is not a valid property name {what}:{name} 不是有效的屬性名稱 -@msg {what}: the text holds a character XML does not allow {what}:文字含有 XML 不允許的字元 -@msg {what}: {name} is not an array {what}:{name} 不是陣列 -@msg {what}: {name} is not a simple property {what}:{name} 不是簡單屬性 -@msg {what}: {name} is not a language alternative array {what}:{name} 不是語言替代陣列 -@msg {what}: the array index {index} is out of range {what}:陣列索引 {index} 超出範圍 -@msg {what}: the namespace {uri} is not registered {what}:命名空間 {uri} 未註冊 -@msg {what}: the file is closed {what}:檔案已關閉 -@msg {what}: the file cannot be updated {what}:檔案無法更新 @msg {what}: the count must be a finite number, 0 or more {what}:數量必須是 0 或更大的有限數 @msg File.seek: the position must be a finite number File.seek:位置必須是有限數 @msg File.seek: the mode must be 0, 1 or 2 File.seek:模式必須是 0, 1 或 2 diff --git a/docs/mcp.md b/docs/mcp.md index 5f394538d3..c1022c5933 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3072,7 +3072,8 @@ rules for these objects: 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. Only a `.xmp` file + `XMPConst.OPEN_USE_PACKET_SCANNING`, is scanned for its first UTF-8 packet and is read only. A packet starts at a + ` Date: Sun, 22 Nov 2026 13:40:36 -0800 Subject: [PATCH 13/21] Scripts: XMP packets are checked as they are read and written, and safe closes use a temporary file - closeFile with XMPConst.CLOSE_UPDATE_SAFELY passes the flag to xmpWrite, which then writes only through a temporary file; where none may be made it throws and leaves the sidecar and the packet as they are. - On Unix the temporary file is created with mode 0600 and takes the sidecar's permission bits after the packet is written. - canPutXMP and putXMP check again that the file is open for update after converting the packet argument, since a toString may close it. - Path arguments are converted once, so a toString that changes between calls cannot mix two paths. - setLocalizedText moves an existing x-default item to the front. - A second ExternalObject install is refused and keeps the registered namespaces. - Text beside rdf:Description elements or their properties makes a packet malformed. - Properties read from a packet share one copy of each namespace URI, and reading stops once the properties exceed the script heap. - A value with qualifiers in the rdf:value form gives the text and options of its rdf:value, and an empty property element whose attributes are fields is a structure. - serialize() and reading refuse a value that would be written with more than 1,024 attributes or namespace declarations in scope at one element. - find_packet treats packet markers inside CDATA sections and comments as text, and passes over a packet that is not UTF-8 for the next one. A section that holds a trailer and then a start does not hide that start, and each marker search starts where the last one stopped, so the scan reads the bytes about once. - An rdf:Alt item with xml:lang="" has no language, so its array is not a language alternative; the empty attribute is written back as it was. - The rdf:about value counts toward the parse budget, also in a packet with no properties. - docs/mcp.md says that the prefix limit applies to a namespace being registered. - The round-trip property test generates valid packets, the retry test closes the same XMPFile again after a failed write, and the heap-limit test requires a heap-limit error and a change that goes through. --- crates/engine/src/script/files.rs | 35 ++- crates/engine/src/tests/script_xmp.rs | 137 ++++++++-- crates/js/src/realm.rs | 5 +- crates/js/src/xmp.rs | 377 +++++++++++++++++++++----- crates/js/src/xmp_classes.rs | 112 +++++--- crates/js/src/xmp_tests.rs | 288 +++++++++++++++++++- docs/mcp.md | 26 +- 7 files changed, 821 insertions(+), 159 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index e556449148..2a6d2ec971 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1925,13 +1925,14 @@ fn xmp_open(host: &Host, a: &[Data]) -> Result { ])) } -/// `xmpWrite(path, packet)`: 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. Open objects of the -/// file hold the new bytes. +/// `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. fn xmp_write(host: &Host, a: &[Data]) -> Result { let path = arg_text(a, 0); let packet = arg_text(a, 1).into_bytes(); + let safely = matches!(a.get(2), Some(Data::Bool(true))); if !is_sidecar(&path) { return Ok(error(ACCESS_DENIED)); } @@ -1955,12 +1956,16 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { if disk.open.values().any(|o| o.dirty && o.holds(&target)) { 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)))?; 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 { @@ -1968,7 +1973,15 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { // 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| allowed(t).then(|| std::fs::OpenOptions::new().write(true).create_new(true).open(t).ok()).flatten(); + 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)); }; @@ -1977,6 +1990,11 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { 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) }; let r = write_temp(); @@ -2650,6 +2668,9 @@ thread_local! { pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell = 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 = 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> = const { std::cell::Cell::new(None) }; } #[cfg(test)] diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index 6c68cadcff..b39f3b28d7 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -491,33 +491,56 @@ fn a_huge_sidecar_is_refused_before_it_is_read() { 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 { + 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` writes it; an `XMPFile` from an earlier run is closed. +/// 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); - let setup = format!( - "var p = Folder.userData.fsName + '/k.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\ - $.global.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\ - vc.log(out); vc.log(p);" - ); crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(true)); - let log = logged(&mut s, &base, &setup); - crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(false)); - assert_eq!(log[0], json!(["Script file could not be written", "changed"])); - let path = PathBuf::from(log[1].as_str().unwrap()); - assert!(std::fs::read_to_string(&path).unwrap().contains("image/svg+xml"), "the failed write leaves the file as it was"); - let log = logged( + start_framed( &mut s, &base, &format!( - "{setup}\nvc.log(new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ).getXMP().getProperty(XMPConst.NS_DC, 'format').value);" + "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);" ), ); - assert_eq!(log, json!([["closed"], path.to_string_lossy(), "changed"])); + 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("changed"), "the same XMPFile writes on its next close"); + let _ = std::fs::remove_dir_all(base); +} + +/// 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()); @@ -532,3 +555,85 @@ fn a_failed_write_keeps_the_packet_for_a_later_close() { 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 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("changed")); + let names: Vec = 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); +} diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index a9826703ed..4fc7619fb9 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -508,7 +508,10 @@ impl Realm { /// 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. + /// `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 second call fails with an internal error and leaves the realm's + /// `ExternalObject` and its registered namespaces as they are. pub fn define_external_object(&mut self) -> Result<(), RunError> { match crate::xmp_classes::install(&mut self.interp) { Ok(()) => Ok(()), diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 8b508c1d6c..2d4be10caf 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -10,19 +10,23 @@ //! a simple value (text, or a URI in `rdf:resource`), an array of simple items (`rdf:Bag`, //! `rdf:Seq` or `rdf:Alt`, each item with an optional `xml:lang`), or any other value (a structure, //! a value with qualifiers, an array of structures), which is kept as the XML it was written in and -//! written back with the namespace declarations it uses. The namespaces of the property, element and +//! written back with the namespace declarations it uses; a value with qualifiers in the `rdf:value` +//! form gives the text and the options of its `rdf:value`. The namespaces of the property, element and //! attribute names under `rdf:Description` are added to the realm's [`Registry`] with the prefix the //! packet gives them, or a new prefix when that one is taken; a namespace the packet declares and no //! such name uses is not added. //! //! VectorCraft's own rules: a packet or a written packet holds at most [`MAX_BYTES`] bytes, -//! elements nest at most 64 deep, a child of `rdf:RDF` other than `rdf:Description` makes the -//! packet malformed, a property given twice keeps its first value, and [`find_packet`] finds only a -//! UTF-8 packet. A realm registers at most [`MAX_NAMESPACES`] namespaces holding at most +//! elements nest at most 64 deep, and each holds at most 1,024 attributes and has at most 1,024 +//! namespace declarations in scope, both as read and as written; a +//! child of `rdf:RDF` other than `rdf:Description` and text beside the descriptions or their +//! properties make the packet malformed, a property given twice keeps its first value, and +//! [`find_packet`] finds only a UTF-8 packet. A realm registers at most [`MAX_NAMESPACES`] namespaces holding at most //! [`MAX_REGISTRY_BYTES`] bytes, each URI at most [`MAX_URI_BYTES`] bytes and each prefix at most //! [`MAX_PREFIX_BYTES`] bytes. use std::collections::{HashMap, HashSet}; +use std::rc::Rc; use craft_xml::{Doctype, El, Limits, Names, Node, Options, UnknownEntity, XML_NS}; @@ -100,6 +104,8 @@ pub(crate) enum XmpError { BadText, /// A path form not read yet: a structure field, a qualifier or a selector. NotYet, + /// The metadata a packet gives is larger than the budget [`parse_within`] was given. + Heap, } /// The kind of an array. @@ -148,6 +154,13 @@ pub(crate) struct Item { pub(crate) lang: Option, } +impl Item { + /// Does the item name a language? `xml:lang=""` names none. + pub(crate) fn has_lang(&self) -> bool { + self.lang.as_deref().is_some_and(|l| !l.is_empty()) + } +} + /// A property's value. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Value { @@ -165,6 +178,8 @@ pub(crate) enum Value { xml: String, options: u32, text: Option, + /// The most namespace declarations `xml` puts in scope at one of its elements. + decls: usize, }, } @@ -180,7 +195,7 @@ impl Value { } } Value::Array { form, items } => { - let alt_text = *form == Form::Alt && !items.is_empty() && items.iter().all(|i| i.lang.is_some()); + let alt_text = *form == Form::Alt && !items.is_empty() && items.iter().all(Item::has_lang); form.options() | if alt_text { ARRAY_IS_ALTTEXT } else { 0 } } Value::Other { options, .. } => *options, @@ -200,7 +215,8 @@ impl Value { /// A top-level property. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Prop { - pub(crate) ns: String, + /// The namespace, which the properties a packet gives in the same namespace share. + pub(crate) ns: Rc, pub(crate) name: String, pub(crate) value: Value, } @@ -232,7 +248,7 @@ impl Meta { /// The position of the property `name` in the namespace `ns`. pub(crate) fn find(&self, ns: &str, name: &str) -> Option { - self.props.iter().position(|p| p.ns == ns && p.name == name) + self.props.iter().position(|p| &*p.ns == ns && p.name == name) } } @@ -445,16 +461,64 @@ fn find_rdf<'a>(el: &'a El, scope: &mut Scope) -> Option<&'a El> { None } -/// Reads the packet `text`, registering the namespaces it uses in `registry`. A packet that fails -/// to read leaves `registry` unchanged. +/// Tests: reads the packet `text` with no budget ([`parse_within`]). +#[cfg(test)] pub(crate) fn parse(text: &str, registry: &mut Registry) -> Result { + parse_within(text, registry, usize::MAX) +} + +/// Reads the packet `text`, registering the namespaces it uses in `registry`, and stops with +/// [`XmpError::Heap`] as soon as the properties read hold more than `budget` bytes, as +/// [`Meta::heap_bytes`] counts them. A packet that fails to read leaves `registry` unchanged. +pub(crate) fn parse_within(text: &str, registry: &mut Registry, budget: usize) -> Result { let mut staged = registry.clone(); - let meta = parse_into(text, &mut staged)?; + let meta = parse_into(text, &mut staged, budget)?; *registry = staged; Ok(meta) } -fn parse_into(text: &str, registry: &mut Registry) -> Result { +/// The properties a packet has given so far. +struct Reading { + meta: Meta, + /// The names `meta` has. + seen: HashSet<(Rc, String)>, + /// The namespaces of the properties, each held once. + pool: HashSet>, + /// The bytes `meta` holds, and the most it may hold. + bytes: usize, + budget: usize, +} + +impl Reading { + /// The shared copy of the namespace `ns`. + fn intern(&mut self, ns: String) -> Rc { + if let Some(shared) = self.pool.get(ns.as_str()) { + return Rc::clone(shared); + } + let shared: Rc = ns.into(); + self.pool.insert(Rc::clone(&shared)); + shared + } + + /// Adds `prop` unless a property of that name was read before. + fn add(&mut self, prop: Prop) -> Result<(), XmpError> { + if self.seen.insert((Rc::clone(&prop.ns), prop.name.clone())) { + self.bytes = self.bytes.saturating_add(prop.heap_bytes()); + if self.bytes > self.budget { + return Err(XmpError::Heap); + } + self.meta.props.push(prop); + } + Ok(()) + } +} + +/// Is `node` text that is not XML whitespace alone? +fn is_stray_text(node: &Node) -> bool { + matches!(node, Node::Text(t) | Node::CData(t) if !t.trim_matches([' ', '\t', '\r', '\n']).is_empty()) +} + +fn parse_into(text: &str, registry: &mut Registry, budget: usize) -> Result { if text.len() > MAX_BYTES { return Err(XmpError::TooLarge); } @@ -472,19 +536,26 @@ fn parse_into(text: &str, registry: &mut Registry) -> Result { let root = opts.parse(text.as_bytes()).map_err(|e| if e.is_limit() { XmpError::TooLarge } else { XmpError::Malformed })?; let mut scope = Scope::new(); let rdf = find_rdf(&root, &mut scope).ok_or(XmpError::Malformed)?; - let mut meta = Meta::default(); - let mut seen = HashSet::new(); + // Text beside the descriptions or their properties is not RDF. + if rdf.children.iter().any(is_stray_text) { + return Err(XmpError::Malformed); + } + let mut reading = Reading { meta: Meta::default(), seen: HashSet::new(), pool: HashSet::new(), bytes: 32, budget }; for d in rdf.elements() { let mark = scope.len(); push_decls(d, &mut scope); - if !is_named(&d.name, &scope, true, RDF, "Description") { + if !is_named(&d.name, &scope, true, RDF, "Description") || d.children.iter().any(is_stray_text) { return Err(XmpError::Malformed); } for (k, v) in attrs(d) { let Some((ns, local)) = resolve(k, &scope, false) else { return Err(XmpError::Malformed) }; if ns == RDF { - if local == "about" && meta.about.is_empty() { - meta.about = v.to_string(); + if local == "about" && reading.meta.about.is_empty() { + reading.meta.about = v.to_string(); + reading.bytes = reading.bytes.saturating_add(v.len()); + if reading.bytes > reading.budget { + return Err(XmpError::Heap); + } } continue; } @@ -493,26 +564,19 @@ fn parse_into(text: &str, registry: &mut Registry) -> Result { } let prefix = k.split_once(':').map_or("ns", |(p, _)| p); registry.register(&ns, prefix)?; - add(&mut meta, &mut seen, Prop { ns, name: local.to_string(), value: Value::Simple { text: v.to_string(), uri: false } }); + let ns = reading.intern(ns); + reading.add(Prop { ns, name: local.to_string(), value: Value::Simple { text: v.to_string(), uri: false } })?; } for p in d.elements() { - let prop = read_property(p, &mut scope, registry)?; - add(&mut meta, &mut seen, prop); + let prop = read_property(p, &mut scope, registry, &mut reading)?; + reading.add(prop)?; } scope.truncate(mark); } - Ok(meta) + Ok(reading.meta) } -/// Adds `prop` to `meta` unless it already has a property of that name; `seen` holds the names -/// `meta` has. -fn add(meta: &mut Meta, seen: &mut HashSet<(String, String)>, prop: Prop) { - if seen.insert((prop.ns.clone(), prop.name.clone())) { - meta.props.push(prop); - } -} - -fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result { +fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry, reading: &mut Reading) -> Result { let mark = scope.len(); push_decls(p, scope); let (ns, local) = resolve(&p.name, scope, true).ok_or(XmpError::Malformed)?; @@ -540,10 +604,10 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

Option { } } -/// A value kept as the XML it was read as. -fn other(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope, mark: usize) -> Value { - // The first child's name is read with the prefixes it declares itself. - let form = children.first().and_then(|c| { - let inner = scope.len(); - push_decls(c, scope); - let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&c.name, scope, true, RDF, &f.element()[4..])); - scope.truncate(inner); - form - }); +/// A value kept as the XML it was read as, refused when the element written for it would hold more +/// than [`MAX_ATTRS`] attributes or declarations in scope, which a packet could then not read back. +fn other(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope, mark: usize) -> Result { + let (options, text) = match qualified_value(own, children, scope) { + Some(found) => found, + None => kept_form(p, own, children, scope), + }; + let mut xml = String::new(); + let added = write_fragment(p, scope.get(..mark).unwrap_or(&[]), &mut xml); + let decls = added + nested_decls(p); + if p.attrs.len() + added > MAX_ATTRS || decls > MAX_ATTRS { + return Err(XmpError::TooLarge); + } + Ok(Value::Other { xml, options, text, decls }) +} + +/// The most namespace declarations `el` and the elements inside it put in scope at one element. +fn nested_decls(el: &El) -> usize { + el.ns_decls().count() + el.elements().map(nested_decls).max().unwrap_or(0) +} + +/// The array form of the container `el`, read with the prefixes it declares itself. +fn container_form(el: &El, scope: &mut Scope) -> Option { + let inner = scope.len(); + push_decls(el, scope); + let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&el.name, scope, true, RDF, &f.element()[4..])); + scope.truncate(inner); + form +} + +/// The options and text of a kept value that is not in the `rdf:value` form. +fn kept_form(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope) -> (u32, Option) { + let form = children.first().and_then(|c| container_form(c, scope)); let resource = own.iter().find(|(k, _)| is_named(k, scope, false, RDF, "resource")).map(|(_, v)| (*v).to_string()); let lang = own.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")); - let (options, text) = match form { + // An empty property element whose attributes are fields is a structure. + let fields = own.iter().any(|(k, _)| resolve(k, scope, false).is_some_and(|(ns, _)| !ns.is_empty() && ns != RDF && ns != XML)); + match form { Some(f) if children.len() == 1 => (f.options() | PROP_HAS_QUALIFIERS, None), _ if !children.is_empty() || own.iter().any(|(k, _)| is_named(k, scope, false, RDF, "parseType")) => (PROP_IS_STRUCT, None), + _ if fields && resource.is_none() && !p.children.iter().any(is_stray_text) => (PROP_IS_STRUCT, None), _ => { let uri = if resource.is_some() { PROP_VALUE_IS_URI } else { 0 }; (PROP_HAS_QUALIFIERS | uri | if lang { PROP_HAS_LANG } else { 0 }, Some(resource.unwrap_or_else(|| text_of(p)))) } + } +} + +/// The options and text of a value with qualifiers in the `rdf:value` form (XMP Specification +/// Part 1, 7.9.2.5): `rdf:value` and the qualifiers are the fields of the property, written with +/// `rdf:parseType="Resource"`, in its one `rdf:Description`, or as the attributes of an empty +/// property element. `None` for a value in another form. +fn qualified_value(own: &[(&str, &str)], children: &[&El], scope: &mut Scope) -> Option<(u32, Option)> { + let lang = if own.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")) { PROP_HAS_LANG | PROP_HAS_QUALIFIERS } else { 0 }; + let resource_type = own.iter().any(|(k, v)| is_named(k, scope, false, RDF, "parseType") && *v == "Resource"); + let found = if children.is_empty() || resource_type { + value_field(children, own, scope) + } else if let [d] = children { + let mark = scope.len(); + push_decls(d, scope); + let found = if is_named(&d.name, scope, true, RDF, "Description") { + let fields: Vec<&El> = d.elements().collect(); + value_field(&fields, &attrs(d), scope) + } else { + None + }; + scope.truncate(mark); + found + } else { + None }; - let mut xml = String::new(); - write_fragment(p, scope.get(..mark).unwrap_or(&[]), &mut xml); - Value::Other { xml, options, text } + found.map(|(options, text)| (options | lang, text)) +} + +/// The options and text the `rdf:value` among the field elements `fields` and the attributes +/// `held` of one structure gives; the other fields and the attributes outside the RDF namespace +/// are its qualifiers. +fn value_field(fields: &[&El], held: &[(&str, &str)], scope: &mut Scope) -> Option<(u32, Option)> { + let is_rdf = |k: &str, scope: &Scope| resolve(k, scope, false).is_some_and(|(ns, _)| ns == RDF); + let lang_in = |list: &[(&str, &str)], scope: &Scope| list.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")); + let mut qualifiers = held.iter().any(|(k, _)| !is_rdf(k, scope)); + let mut lang = lang_in(held, scope); + if let Some((_, text)) = held.iter().find(|(k, _)| is_named(k, scope, false, RDF, "value")) { + qualifiers |= !fields.is_empty(); + return Some((option_bits(0, qualifiers, lang), Some((*text).to_string()))); + } + let at = fields.iter().position(|f| { + let mark = scope.len(); + push_decls(f, scope); + let found = is_named(&f.name, scope, true, RDF, "value"); + scope.truncate(mark); + found + })?; + let value = fields.get(at)?; + qualifiers |= fields.len() > 1; + let mark = scope.len(); + push_decls(value, scope); + let own = attrs(value); + lang |= lang_in(&own, scope); + let resource = own.iter().find(|(k, _)| is_named(k, scope, false, RDF, "resource")).map(|(_, v)| (*v).to_string()); + let inner: Vec<&El> = value.elements().collect(); + let found = match inner.as_slice() { + [] => match resource { + Some(uri) => (PROP_VALUE_IS_URI, Some(uri)), + None => (0, Some(text_of(value))), + }, + [c] => match container_form(c, scope) { + Some(f) => (f.options(), None), + None => (PROP_IS_STRUCT, None), + }, + _ => (PROP_IS_STRUCT, None), + }; + scope.truncate(mark); + Some((option_bits(found.0, qualifiers, lang), found.1)) +} + +/// `options` with [`PROP_HAS_QUALIFIERS`] when the value has `qualifiers`, and with +/// [`PROP_HAS_LANG`] as well when one of them is `xml:lang`. +fn option_bits(options: u32, qualifiers: bool, lang: bool) -> u32 { + let qualifiers = if qualifiers || lang { PROP_HAS_QUALIFIERS } else { 0 }; + options | qualifiers | if lang { PROP_HAS_LANG } else { 0 } } /// Writes the element `p` as XML, declaring on it the prefixes from `outer` that it and the -/// elements inside it use and do not declare themselves. -fn write_fragment(p: &El, outer: &[(String, String)], out: &mut String) { +/// elements inside it use and do not declare themselves. → the declarations it added. +fn write_fragment(p: &El, outer: &[(String, String)], out: &mut String) -> usize { let mut used: Vec = Vec::new(); collect_prefixes(p, &mut used); let own: Vec<&str> = p.ns_decls().map(|(prefix, _)| prefix).collect(); out.push('<'); out.push_str(&p.name); + let mut added = 0; for prefix in used.iter().filter(|u| !own.contains(&u.as_str())) { if let Some((_, uri)) = outer.iter().rev().find(|(q, _)| q == prefix) { + added += 1; if prefix.is_empty() { out.push_str(" xmlns=\""); } else { @@ -661,6 +825,7 @@ fn write_fragment(p: &El, outer: &[(String, String)], out: &mut String) { } } write_rest(p, out); + added } /// The prefixes the names of `el` and the elements inside it use, `""` for an unprefixed element. @@ -740,11 +905,19 @@ pub(crate) fn serialize(meta: &Meta, registry: &Registry, wrapper: bool) -> Resu let mut namespaces: Vec<(&str, &str)> = Vec::new(); let mut declared = HashSet::new(); for p in &meta.props { - if matches!(p.value, Value::Other { .. }) || !declared.insert(p.ns.as_str()) { + if matches!(p.value, Value::Other { .. }) || !declared.insert(&*p.ns) { continue; } let prefix = registry.prefix_of(&p.ns).ok_or(XmpError::BadName)?; - namespaces.push((prefix, &p.ns)); + namespaces.push((prefix, &*p.ns)); + } + // A read takes at most `MAX_ATTRS` declarations in scope at one element: those of `x:xmpmeta` + // and `rdf:RDF`, a declaration on `rdf:Description` for each namespace, and the declarations of a + // kept value. + let around = 2 + namespaces.len(); + let kept = meta.props.iter().map(|p| if let Value::Other { decls, .. } = p.value { decls } else { 0 }).max().unwrap_or(0); + if around + kept > MAX_ATTRS { + return Err(XmpError::TooLarge); } let prefix = |ns: &str| registry.prefix_of(ns).ok_or(XmpError::BadName); let mut out = Out(String::new()); @@ -824,37 +997,97 @@ pub(crate) fn pad_size(packet: &str) -> usize { /// The first UTF-8 packet in `bytes` that has both ends of its wrapper (XMP Specification Part 1, /// 7.3), or `None`. A start is a ` Option { const BEGIN: &[u8] = b""), (b"")]; let len = bytes.len(); + let rest = |at: usize| bytes.get(at..).unwrap_or_default(); let ids = [format!("id=\"{WRAPPER_ID}\""), format!("id='{WRAPPER_ID}'")]; - let is_header = |at: usize| { - let head = bytes.get(at..len.min(at.saturating_add(MAX_HEADER))).unwrap_or_default(); - let head = head.windows(2).position(|w| w == b"?>").and_then(|close| head.get(..close)).unwrap_or_default(); - ids.iter().any(|id| head.windows(id.len()).any(|w| w == id.as_bytes())) + let is_start = |at: usize| { + rest(at).starts_with(BEGIN) && { + let head = bytes.get(at..len.min(at.saturating_add(MAX_HEADER))).unwrap_or_default(); + let head = head.windows(2).position(|w| w == b"?>").and_then(|close| head.get(..close)).unwrap_or_default(); + ids.iter().any(|id| head.windows(id.len()).any(|w| w == id.as_bytes())) + } }; - // The first start from `from` that begins before `to`. - let start_in = |mut from: usize, to: usize| loop { - let at = find(from, to, BEGIN)?; - if is_header(at) { - return Some(at); + // Every start, in order. + let starts: Vec = bytes.windows(BEGIN.len()).enumerate().filter(|(at, w)| *w == BEGIN && is_start(*at)).map(|(at, _)| at).collect(); + let start_after = |from: usize| starts.get(starts.partition_point(|&s| s < from)).copied(); + let mut ends = Later::new(END); + let mut closes = Later::new(b"?>"); + let mut section_ends = SECTIONS.map(|(_, close)| Later::new(close)); + let mut start = None; + let mut pos = 0; + while let Some(at) = rest(pos).iter().position(|&b| b == b'<').map(|i| i + pos) { + pos = at + 1; + if starts.binary_search(&at).is_ok() { + start = Some(at); + pos = at + BEGIN.len(); + continue; } - from = at + BEGIN.len(); - }; - let mut start = start_in(0, len)?; - loop { - let end_tag = find(start + BEGIN.len(), len, END)?; - while let Some(next) = start_in(start + BEGIN.len(), end_tag) { - start = next; + let Some(from) = start else { + // Nothing before the next start matters. + pos = start_after(pos)?; + continue; + }; + let here = rest(at); + if let Some(kind) = SECTIONS.iter().position(|(open, _)| here.starts_with(open)) { + let (open, close) = SECTIONS[kind]; + let inside = at + open.len(); + let end = section_ends[kind].find(bytes, inside); + // A trailer and then a start inside the section belong to packets of their own. + let hides_packet = end.is_some_and(|end| ends.find(bytes, inside).is_some_and(|e| e < end && start_after(e).is_some_and(|s| s < end))); + if let (Some(end), false) = (end, hides_packet) { + pos = end + close.len(); + } + continue; } - let after = end_tag + END.len(); - let next = start_in(after, len); - match find(after, next.unwrap_or(len), b"?>") { - Some(close) => return Some(PacketSpan { start, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }), - None => start = next?, + if !here.starts_with(END) { + continue; } + let after = at + END.len(); + let close = closes.find(bytes, after)?; + if let Some(next) = start_after(after).filter(|&next| next < close) { + start = Some(next); + pos = next + BEGIN.len(); + continue; + } + let span = PacketSpan { start: from, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }; + if bytes.get(span.start..span.end).is_some_and(|p| std::str::from_utf8(p).is_ok()) { + return Some(span); + } + start = None; + pos = span.end; + } + None +} + +/// The next place of a marker at or after a given point. While the points do not go back, each +/// search starts past the last one, so the searches together read the bytes about once. +struct Later { + marker: &'static [u8], + /// The point of the last search, and what it found. + from: usize, + found: Option, +} + +impl Later { + fn new(marker: &'static [u8]) -> Later { + Later { marker, from: usize::MAX, found: None } + } + + fn find(&mut self, bytes: &[u8], from: usize) -> Option { + if self.from <= from && self.found.is_none_or(|f| f >= from) { + return self.found; + } + self.from = from; + self.found = bytes.get(from..).and_then(|r| r.windows(self.marker.len()).position(|w| w == self.marker)).map(|i| i + from); + self.found } } diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 9d7db14901..974be6b645 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -24,7 +24,8 @@ //! `putXMP` keeps the packet and `closeFile` writes it. //! //! VectorCraft's own rules: only a `.xmp` file opened with `OPEN_FOR_UPDATE` takes `putXMP`; -//! `closeFile` always replaces the file through a temporary one when the folder may hold one; an +//! `closeFile` always replaces the file through a temporary one when the folder may hold one, and +//! with `CLOSE_UPDATE_SAFELY` it writes no other way, throwing and keeping the packet instead; an //! `XMPFile` is open only in the run that opened it, and a packet it kept and did not write is //! dropped when the run ends. A member the reference lists that is not built yet, and a flag, //! format or option not handled yet, throws an error that says so. @@ -125,6 +126,7 @@ fn xmp_error(i: &mut Interp, what: &str, e: XmpError, name: &str) -> Abrupt { XmpError::BadName => i.throw(ErrorType::Error, &format!("{what}: {name} is not a valid property name")), XmpError::BadText => i.throw(ErrorType::Error, &format!("{what}: the text holds a character XML does not allow")), XmpError::NotYet => not_handled(i, what, &name), + XmpError::Heap => Abrupt::Limit(crate::LimitKind::Heap), } } @@ -313,7 +315,8 @@ fn parse_packet(i: &mut Interp, what: &str, text: &str) -> JsResult { // Reading copies the realm's namespaces. let copied = registry(i)?.bytes(); spend(i, text.len().saturating_add(copied))?; - let r = xmp::parse(text, registry(i)?); + let budget = i.limits.heap_bytes; + let r = xmp::parse_within(text, registry(i)?, budget); r.map_err(|e| xmp_error(i, what, e, "")) } @@ -340,8 +343,18 @@ fn namespace(i: &mut Interp, v: &Value, what: &str) -> JsResult { Ok(uri) } -/// The namespace and path arguments at `at`: the namespace, the property name and its step. -fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult<(String, String, Step)> { +/// The namespace and path arguments at `at`, each converted once. +struct Target { + ns: String, + /// The property name and its step. + name: String, + step: Step, + /// The path as given. + path: String, +} + +/// The namespace and path arguments at `at`. +fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult { let ns = namespace(i, &arg(args, at), what)?; let path = text(i, &arg(args, at + 1))?; // A packet holds no property in the RDF or XML namespace. @@ -350,7 +363,7 @@ fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult<(St } let r = xmp::parse_path(&path, &ns, registry(i)?); match r { - Ok((name, step)) => Ok((ns, name, step)), + Ok((name, step)) => Ok(Target { ns, name, step, path }), Err(e) => Err(xmp_error(i, what, e, &path)), } } @@ -395,12 +408,11 @@ fn property_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsRe fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.getProperty"; let o = this_meta(i, &this, what)?; - let (ns, name, step) = target(i, args, 0, what)?; + let Target { ns, name, step, path } = target(i, args, 0, what)?; if !matches!(arg(args, 2), Value::Undefined) { let v = text(i, &arg(args, 2))?; return Err(not_handled(i, what, &v)); } - let path = text(i, &arg(args, 1))?; let found = { let m = meta_of(i, o)?; m.find(&ns, &name).map(|at| m.props[at].value.clone()) @@ -421,7 +433,7 @@ fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.setProperty"; let o = this_meta(i, &this, what)?; - let (ns, name, step) = target(i, args, 0, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; let options = flags(i, &arg(args, 3), what)?; only(i, options, xmp::PROP_IS_ARRAY | xmp::ARRAY_IS_ORDERED | xmp::ARRAY_IS_ALTERNATIVE, what)?; if !matches!(arg(args, 4), Value::Undefined) { @@ -449,7 +461,7 @@ fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul Some(true) => Ok(Value::Undefined), Some(false) => Err(not_array(i, what, &name)), None => { - let prop = xmp::Prop { ns, name, value: xmp::Value::Array { form: Form::from_options(options), items: Vec::new() } }; + let prop = xmp::Prop { ns: ns.into(), name, value: xmp::Value::Array { form: Form::from_options(options), items: Vec::new() } }; change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop)).map(|()| Value::Undefined) } }; @@ -471,7 +483,7 @@ fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul }) } None => { - let prop = xmp::Prop { ns, name, value: new }; + let prop = xmp::Prop { ns: ns.into(), name, value: new }; change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop)) } } @@ -481,7 +493,7 @@ fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul fn delete_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.deleteProperty"; let o = this_meta(i, &this, what)?; - let (ns, name, step) = target(i, args, 0, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; match step { Step::Whole => { let at = meta_of(i, o)?.find(&ns, &name); @@ -497,7 +509,7 @@ fn delete_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe fn does_property_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.doesPropertyExist"; let o = this_meta(i, &this, what)?; - let (ns, name, step) = target(i, args, 0, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; let m = meta_of(i, o)?; let exists = match (m.find(&ns, &name).map(|at| &m.props[at].value), step) { (None, _) => false, @@ -525,20 +537,19 @@ fn array_items(i: &mut Interp, o: ObjId, ns: &str, name: &str, what: &str) -> Js } } -/// The array name argument at `at` after the namespace: a whole property. -fn array_target(i: &mut Interp, args: &[Value], what: &str) -> JsResult<(String, String)> { - let (ns, name, step) = target(i, args, 0, what)?; - if step != Step::Whole { - let path = text(i, &arg(args, 1))?; - return Err(not_handled(i, what, &path)); +/// The namespace and array name arguments: a whole property. +fn array_target(i: &mut Interp, args: &[Value], what: &str) -> JsResult { + let t = target(i, args, 0, what)?; + if t.step != Step::Whole { + return Err(not_handled(i, what, &t.path)); } - Ok((ns, name)) + Ok(t) } fn count_array_items(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.countArrayItems"; let o = this_meta(i, &this, what)?; - let (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; let n = array_items(i, o, &ns, &name, what)?.map_or(0, |(_, _, len)| len); Ok(Value::Number(n as f64)) } @@ -546,7 +557,7 @@ fn count_array_items(i: &mut Interp, this: Value, args: &[Value], _: bool) -> Js fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.getArrayItem"; let o = this_meta(i, &this, what)?; - let (ns, name) = array_target(i, args, what)?; + let Target { ns, name, path, .. } = array_target(i, args, what)?; let index = item_index(i, &arg(args, 2), what)?; let Some((at, _, len)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; let Some(p) = position(index, len) else { return Ok(Value::Undefined) }; @@ -555,14 +566,14 @@ fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes _ => None, }; let Some(item) = item else { return Ok(Value::Undefined) }; - let path = format!("{}[{}]", text(i, &arg(args, 1))?, p + 1); + let path = format!("{path}[{}]", p + 1); property(i, &ns, &path, Some(&item.text), 0, item.lang.as_deref().unwrap_or("")) } fn does_array_item_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.doesArrayItemExist"; let o = this_meta(i, &this, what)?; - let (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; let index = item_index(i, &arg(args, 2), what)?; let len = array_items(i, o, &ns, &name, what)?.map_or(0, |(_, _, len)| len); Ok(Value::Bool(position(index, len).is_some())) @@ -597,11 +608,8 @@ fn insert_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: Option { let Some(form) = form else { return Err(not_array(i, what, name)) }; - let prop = xmp::Prop { - ns: ns.to_string(), - name: name.to_string(), - value: xmp::Value::Array { form, items: vec![Item { text: value, lang: None }] }, - }; + let prop = + xmp::Prop { ns: ns.into(), name: name.to_string(), value: xmp::Value::Array { form, items: vec![Item { text: value, lang: None }] } }; change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop))?; } } @@ -655,7 +663,7 @@ fn delete_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: i64, what: fn append_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.appendArrayItem"; let o = this_meta(i, &this, what)?; - let (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; // `itemOptions` may be left out: a string or `null` third argument is the item's value. let (value, array_options) = match arg(args, 2) { Value::Number(_) => { @@ -674,7 +682,7 @@ fn append_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> Js fn insert_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.insertArrayItem"; let o = this_meta(i, &this, what)?; - let (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; let index = item_index(i, &arg(args, 2), what)?; let value = xml_text(i, &arg(args, 3), what)?; item_options(i, &arg(args, 4), what)?; @@ -684,7 +692,7 @@ fn insert_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> Js fn set_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.setArrayItem"; let o = this_meta(i, &this, what)?; - let (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; let index = item_index(i, &arg(args, 2), what)?; let value = xml_text(i, &arg(args, 3), what)?; item_options(i, &arg(args, 4), what)?; @@ -694,7 +702,7 @@ fn set_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes fn delete_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.deleteArrayItem"; let o = this_meta(i, &this, what)?; - let (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; let index = item_index(i, &arg(args, 2), what)?; delete_item(i, o, &ns, &name, index, what, false) } @@ -733,10 +741,10 @@ fn lang(i: &mut Interp, v: &Value, what: &str) -> JsResult { } /// Is the property at `at` of `o` a language alternative: an `rdf:Alt` whose items, if it has any, -/// all have a language? +/// all have a language? An item with `xml:lang=""` has none. fn is_alt_text(i: &Interp, o: ObjId, at: usize) -> JsResult { Ok(match meta_of(i, o)?.props.get(at).map(|p| &p.value) { - Some(xmp::Value::Array { form: Form::Alt, items }) => items.iter().all(|item| item.lang.is_some()), + Some(xmp::Value::Array { form: Form::Alt, items }) => items.iter().all(Item::has_lang), _ => false, }) } @@ -744,7 +752,7 @@ fn is_alt_text(i: &Interp, o: ObjId, at: usize) -> JsResult { fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.getLocalizedText"; let o = this_meta(i, &this, what)?; - let (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; let generic = lang(i, &arg(args, 2), what)?; let specific = lang(i, &arg(args, 3), what)?; let Some((at, _, _)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; @@ -764,7 +772,7 @@ fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.setLocalizedText"; let o = this_meta(i, &this, what)?; - let (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; let generic = lang(i, &arg(args, 2), what)?; let specific = lang(i, &arg(args, 3), what)?; if specific.is_empty() || specific.contains(char::is_whitespace) { @@ -776,7 +784,7 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let (at, new) = match found { Some((at, _, _)) if !is_alt_text(i, o, at)? => return Err(not_alt_text(i, what, &name)), Some((at, _, _)) => (Some(at), None), - None => (None, Some(xmp::Prop { ns, name, value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } })), + None => (None, Some(xmp::Prop { ns: ns.into(), name, value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } })), }; // An item and the `x-default` item change, or every item with the text of the `x-default` one. let changed = match at.and_then(|at| meta_of(i, o).ok()?.props.get(at)).map(|p| &p.value) { @@ -806,6 +814,13 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J /// is added with the value when there is none, and follows a change to an item that had the same /// text; a change to the `x-default` item also changes the items that had its text. fn set_lang(items: &mut Vec, generic: &str, specific: &str, value: String) { + // An `x-default` item a packet gave later moves to the front; the others keep their order. + if let Some(d) = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")) + && d > 0 + { + let item = items.remove(d); + items.insert(0, item); + } let default = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")); if specific.eq_ignore_ascii_case("x-default") { match default.and_then(|d| items.get(d)).map(|i| i.text.clone()) { @@ -1094,7 +1109,7 @@ fn packet_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { // registers nothing. let mut scratch = registry(i)?.clone(); spend(i, s.len().saturating_add(2 * scratch.bytes()))?; - xmp::parse(&s, &mut scratch).map_err(|e| xmp_error(i, what, e, ""))?; + xmp::parse_within(&s, &mut scratch, i.limits.heap_bytes).map_err(|e| xmp_error(i, what, e, ""))?; Ok(s) } @@ -1106,7 +1121,11 @@ fn can_put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } let packet = packet_arg(i, &arg(args, 0), what); match packet { - Ok(_) => Ok(Value::Bool(true)), + // Converting the argument runs script code, which may have closed the file. + Ok(_) => { + let o = open_file(i, &this, what)?; + Ok(Value::Bool(can_update(i, o)?)) + } Err(Abrupt::Throw(_)) => Ok(Value::Bool(false)), Err(e) => Err(e), } @@ -1119,6 +1138,11 @@ fn put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult< let pending = slot(i, o, PENDING)?; if this_run && slot(i, o, OPEN)?.truthy() && matches!(pending, Value::String(_)) { let path = slot(i, o, PATH)?; - let r = i.rooted(&[path.clone(), pending.clone()], |i| crate::file_classes::call_host(i, "xmpWrite", &[path.clone(), pending.clone()]))?; + let safely = Value::Bool(close_flags & CLOSE_UPDATE_SAFELY != 0); + let r = + i.rooted(&[path.clone(), pending.clone()], |i| crate::file_classes::call_host(i, "xmpWrite", &[path.clone(), pending.clone(), safely]))?; let error = i.rooted(std::slice::from_ref(&r), |i| crate::file_classes::record_field(i, &r, "error"))?; if let Value::String(_) = error { // The file stays open with its packet, so a later `closeFile` tries again. @@ -1247,8 +1273,12 @@ fn link(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { } /// Adds the global `ExternalObject`, which defines `XMPMeta`, `XMPFile` and `XMPConst` when a -/// script loads the XMP library ([`crate::Realm::define_external_object`]). +/// script loads the XMP library ([`crate::Realm::define_external_object`]). A second call is +/// refused and changes nothing, so the namespaces registered stay. pub(crate) fn install(i: &mut Interp) -> JsResult<()> { + if i.xmp.is_some() { + return Err(Abrupt::Internal("ExternalObject is already added".into())); + } let object_proto = i.intrinsics.object_proto; i.reserve_heap(4 * OBJECT_BYTES)?; let external_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 293b4d3157..039d111a8b 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -1,7 +1,7 @@ use proptest::prelude::*; use crate::xmp::{self, Form, Registry, XmpError}; -use crate::{JsValue, Limits, Realm, RunErrorKind}; +use crate::{JsValue, LimitKind, Limits, Realm, RunErrorKind}; fn realm() -> Realm { let mut r = Realm::with_options(crate::Options::default(), Limits::default()); @@ -354,6 +354,7 @@ fn localized_text_updates_a_single_generic_language_item() { #[test] fn localized_text_past_the_heap_limit_adds_no_array() { let mut stopped = 0; + let mut created = false; let mut seen = vec![]; for step in 0..128 { let mut r = Realm::with_options(crate::Options::default(), Limits { heap_bytes: (256 << 10) + step * (16 << 10), ..Limits::default() }); @@ -365,17 +366,24 @@ fn localized_text_past_the_heap_limit_adds_no_array() { seen.push(format!("{step} text {e:?}")); continue; } - if r.run("m.setLocalizedText(XMPConst.NS_DC, 'title', null, s, s);").is_ok() { - seen.push(format!("{step} set")); - break; - } - stopped += 1; - match r.run("m.doesPropertyExist(XMPConst.NS_DC, 'title')") { - Ok(v) => assert_eq!(v, JsValue::Bool(false), "heap step {step}"), - Err(e) => panic!("{e:?}"), + let set = r.run("m.setLocalizedText(XMPConst.NS_DC, 'title', null, s, s);"); + let exists = r.run("m.doesPropertyExist(XMPConst.NS_DC, 'title')"); + match (set, exists) { + (Ok(_), Ok(v)) => { + assert_eq!(v, JsValue::Bool(true), "heap step {step}: the change adds the array"); + created = true; + break; + } + (Err(e), Ok(v)) => { + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "heap step {step}: {e:?}"); + assert_eq!(v, JsValue::Bool(false), "heap step {step}"); + stopped += 1; + } + (_, Err(e)) => panic!("{e:?}"), } } assert!(stopped > 0, "no heap limit stopped the change: {seen:?}"); + assert!(created, "no heap limit let the change through: {seen:?}"); } /// Setting the `x-default` item also changes the items that had its text, and leaves the others. @@ -444,11 +452,13 @@ fn text_beside_an_array_is_kept() { #[test] fn rdf_and_xml_namespaces_hold_no_properties() { for ns in ["http://www.w3.org/1999/02/22-rdf-syntax-ns#", "http://www.w3.org/XML/1998/namespace"] { - assert_eq!( - thrown(&format!("new XMPMeta().setProperty({ns:?}, 'foo', 'x')")), - "Error: XMPMeta.setProperty: foo is not a valid property name", - "{ns}" - ); + for name in ["foo", "li"] { + assert_eq!( + thrown(&format!("new XMPMeta().setProperty({ns:?}, {name:?}, 'x')")), + format!("Error: XMPMeta.setProperty: {name} is not a valid property name"), + "{ns}" + ); + } assert_eq!( thrown(&format!("new XMPMeta().appendArrayItem({ns:?}, 'foo', 'x', XMPConst.PROP_IS_ARRAY)")), "Error: XMPMeta.appendArrayItem: foo is not a valid property name" @@ -456,6 +466,196 @@ fn rdf_and_xml_namespaces_hold_no_properties() { } } +/// A second `define_external_object` is refused and keeps the namespaces the realm registered. +#[test] +fn a_second_external_object_is_refused() { + let mut r = realm(); + let kept = r.run("new ExternalObject('lib:AdobeXMPScript'); XMPMeta.registerNamespace('http://kept/', 'kept')"); + assert_eq!(kept.ok(), Some(JsValue::String("kept:".into()))); + let again = r.define_external_object(); + assert_eq!(again.map_err(|e| e.kind), Err(RunErrorKind::Internal)); + let prefix = r.run("new ExternalObject('lib:AdobeXMPScript'); XMPMeta.getNamespacePrefix('http://kept/')"); + assert_eq!(prefix.ok(), Some(JsValue::String("kept:".into()))); +} + +/// A path argument is converted to text once, so one whose text changes on each conversion names +/// one property. +#[test] +fn paths_are_converted_once() { + let src = "function p(a, b) { var k = 0; return { toString: function () { return k++ ? b : a; } }; } + [m.getProperty(XMPConst.NS_DC, p('format', 'title')).path, m.getArrayItem(XMPConst.NS_DC, p('subject', 'title'), 1).path].join('|')"; + assert_eq!(string(&with_packet(src)), "format|subject[1]"); +} + +/// A change to a language alternative moves an `x-default` item a packet gave later to the front, +/// and keeps the order of the others. +#[test] +fn localized_text_moves_x_default_first() { + let packet = PACKET.replace( + "HelloBonjour", + "HelloHelloSalut", + ); + let src = format!( + "var m = new XMPMeta({packet:?}); m.setLocalizedText(XMPConst.NS_DC, 'title', null, 'en', 'Hi'); + [1, 2, 3].map(function (n) {{ var p = m.getArrayItem(XMPConst.NS_DC, 'title', n); return p.locale + '=' + p.value; }}).join('|')" + ); + assert_eq!(string(&src), "x-default=Hi|en=Hi|fr=Salut"); +} + +/// An item with `xml:lang=""` names no language, so its `rdf:Alt` is not a language alternative +/// and has no `ARRAY_IS_ALTTEXT` (0x1000) option, and the empty attribute is written back. +#[test] +fn an_empty_language_is_no_language() { + let packet = PACKET.replace("Bonjour", "Bonjour"); + assert!(packet.contains("xml:lang=\"\"")); + let src = format!( + "var m = new XMPMeta({packet:?}); var out = []; + try {{ m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'x-default'); out.push('read'); }} catch (e) {{ out.push(e.message); }} + try {{ m.setLocalizedText(XMPConst.NS_DC, 'title', null, 'x-default', 'Hi'); out.push('set'); }} catch (e) {{ out.push(e.message); }} + out.push((m.getProperty(XMPConst.NS_DC, 'title').options & 0x1000) != 0); + out.push(m.serialize().indexOf('xml:lang=\"\"') >= 0); + out.join('|')" + ); + assert_eq!( + string(&src), + "XMPMeta.getLocalizedText: title is not a language alternative array|XMPMeta.setLocalizedText: title is not a language alternative array|false|true" + ); +} + +/// Text beside the descriptions or their properties makes a packet malformed; whitespace there and +/// text inside a property do not. +#[test] +fn text_beside_descriptions_is_malformed() { + let rdf = |body: &str| format!("{body}"); + for body in [ + "strayx", + "x", + "strayx", + ] { + assert_eq!(xmp::parse(&rdf(body), &mut Registry::default()), Err(XmpError::Malformed), "{body}"); + } + let fine = rdf("\n \n x \n \n"); + let meta = xmp::parse(&fine, &mut Registry::default()).unwrap(); + assert_eq!(meta.props.first().and_then(|p| p.value.text()), Some(" x ")); +} + +/// The properties of one namespace share its URI, and a read stops at its budget. +#[test] +fn many_properties_under_one_long_namespace_share_it() { + let uri = format!("http://long/{}/", "u".repeat(1000)); + let body: String = (0..2000).map(|n| format!("v")).collect(); + let packet = format!( + "{body}" + ); + let meta = xmp::parse(&packet, &mut Registry::default()).unwrap(); + assert_eq!(meta.props.len(), 2000); + assert!(meta.props.windows(2).all(|w| std::rc::Rc::ptr_eq(&w[0].ns, &w[1].ns)), "one copy of the URI"); + let bytes = meta.heap_bytes(); + assert_eq!(xmp::parse_within(&packet, &mut Registry::default(), bytes / 2), Err(XmpError::Heap)); + assert_eq!(xmp::parse_within(&packet, &mut Registry::default(), bytes), Ok(meta)); + // The `rdf:about` value counts toward the budget too, in a packet with no properties. + let about = + format!("", "a".repeat(4096)); + let meta = xmp::parse(&about, &mut Registry::default()).unwrap(); + assert!(meta.props.is_empty()); + assert_eq!(xmp::parse_within(&about, &mut Registry::default(), meta.heap_bytes() - 1), Err(XmpError::Heap)); + assert_eq!(xmp::parse_within(&about, &mut Registry::default(), meta.heap_bytes()), Ok(meta)); + let r = realm().run(&format!( + "new ExternalObject('lib:AdobeXMPScript'); var s = {packet:?}; var m = new XMPMeta(s); m.getProperty('{uri}', 'p0').value + ':' + m.getProperty('{uri}', 'p1999').value" + )); + assert_eq!(r.ok(), Some(JsValue::String("v:v".into()))); +} + +/// A value with qualifiers in the `rdf:value` form gives the text and options of its `rdf:value`, +/// and an empty property element with fields as attributes is a structure; both write back as +/// they were read. +#[test] +fn rdf_value_forms_give_their_text() { + let packet = PACKET.replace( + "", + "srcv\ + rv\ + \ + \ + 1\ + plain", + ); + let shown = "['source', 'rights', 'relation', 'coverage', 'type', 'language'].map(function (n) { + var p = m.getProperty(XMPConst.NS_DC, n); return p.value + ':' + p.options; }).join('|')"; + let want = "src:16|r:80|rel:16|undefined:256|http://t/:18|plain:0"; + assert_eq!(string(&format!("var m = new XMPMeta({packet:?}); {shown}")), want); + assert_eq!(string(&format!("var m = new XMPMeta(new XMPMeta({packet:?}).serialize()); {shown}")), want); +} + +/// A packet is not written with more attributes on one element than a read takes, and a packet +/// whose `rdf:RDF` lies deep reads back from what it writes. +#[test] +fn written_packets_keep_to_the_read_limits() { + let mut registry = Registry::default(); + let mut meta = xmp::Meta::default(); + for n in 0..1023 { + let uri = format!("http://n/{n}/"); + registry.register(&uri, "n").unwrap(); + meta.props.push(xmp::Prop { ns: uri.into(), name: "p".into(), value: xmp::Value::Simple { text: "v".into(), uri: false } }); + } + assert_eq!(xmp::serialize(&meta, ®istry, false), Err(XmpError::TooLarge), "1,025 declarations in scope"); + meta.props.pop(); + let out = xmp::serialize(&meta, ®istry, false).unwrap(); + assert_eq!(xmp::parse(&out, &mut registry), Ok(meta)); + let decls: String = (0..600).map(|n| format!(" xmlns:b{n}='http://b/{n}/'")).collect(); + let fields: String = (0..600).map(|n| format!(" b{n}:k='v'")).collect(); + let kept = format!( + "x" + ); + assert_eq!(xmp::parse(&kept, &mut Registry::default()), Err(XmpError::TooLarge), "a kept value that takes 600 declarations"); + let simple: String = (0..600).map(|n| format!("v")).collect(); + let inner: String = (0..500).map(|n| format!(" xmlns:c{n}='http://c/{n}/'")).collect(); + let spread = format!( + "{simple}\ + 1" + ); + let mut registry = Registry::default(); + let meta = xmp::parse(&spread, &mut registry).unwrap(); + assert_eq!(xmp::serialize(&meta, ®istry, false), Err(XmpError::TooLarge), "600 declarations around a kept value with 502"); + let wrap = 60; + let deep = format!( + "{}v\ + 1{}", + "".repeat(wrap), + "".repeat(wrap) + ); + let mut registry = Registry::default(); + let meta = xmp::parse(&deep, &mut registry).unwrap(); + let out = xmp::serialize(&meta, ®istry, true).unwrap(); + assert_eq!(xmp::parse(&out, &mut registry), Ok(meta)); +} + +/// Inside a packet, a start or a trailer in a CDATA section or a comment is text, and a packet that +/// is not UTF-8 is passed over for the next one. +#[test] +fn packet_markers_in_sections_are_text() { + let start = ""; + for section in [format!(""), format!(""), "]]>".to_string()] { + let inner = PACKET.replace("image/svg+xml", &format!("{section}")); + let bytes = format!("binary\0{inner}"); + assert_eq!(xmp::find_packet(bytes.as_bytes()).map(|s| (s.start, s.end)), Some((7, bytes.len())), "{section}"); + } + let mut bad = PACKET.as_bytes().to_vec(); + if let Some(at) = PACKET.find("image") { + bad[at] = 0xFF; + } + let both = [bad.as_slice(), b"gap", PACKET.as_bytes()].concat(); + let span = xmp::find_packet(&both).map(|s| (s.start, s.end)); + assert_eq!(span, Some((bad.len() + 3, both.len())), "the UTF-8 packet after one that is not"); + // A section that a trailer and then a later packet's start come before the end of does not + // hide that start. + let first = [start.as_bytes(), b""].concat(); + let second = PACKET.replace("image/svg+xml", "image/svg+xml"); + let both = [first.as_slice(), second.as_bytes()].concat(); + let span = xmp::find_packet(&both).map(|s| (s.start, s.end)); + assert_eq!(span, Some((first.len(), both.len())), "the packet after an unclosed section"); +} + #[test] fn array_forms_follow_their_options() { assert_eq!(Form::from_options(0x200), Form::Bag); @@ -490,9 +690,69 @@ const PIECES: &[&str] = &[ "", ]; +/// A property of a generated packet that reads. +#[derive(Clone, Debug)] +enum Generated { + Simple(String), + Uri(String), + Array(usize, Vec<(String, Option)>), + Kept(String), +} + +fn generated_property() -> impl Strategy { + let text = "[a-zA-Z0-9 &<>\"']{0,8}"; + prop_oneof![ + text.prop_map(Generated::Simple), + "[a-z]{1,6}".prop_map(|s| Generated::Uri(format!("http://r/{s}"))), + (0..3usize, proptest::collection::vec((text, proptest::option::of("[a-z]{2}(-[A-Z]{2})?")), 0..4)) + .prop_map(|(f, items)| Generated::Array(f, items)), + text.prop_map(Generated::Kept), + ] +} + +/// The packet the properties `props` make, each named by its position. +fn generated_packet(props: &[Generated]) -> String { + let mut body = String::new(); + for (n, p) in props.iter().enumerate() { + match p { + Generated::Simple(t) => body.push_str(&format!("{}", craft_xml::esc(t))), + Generated::Uri(u) => body.push_str(&format!("")), + Generated::Array(form, items) => { + let form = ["rdf:Bag", "rdf:Seq", "rdf:Alt"][*form]; + body.push_str(&format!("<{form}>")); + for (t, lang) in items { + let lang = lang.as_ref().map(|l| format!(" xml:lang='{l}'")).unwrap_or_default(); + body.push_str(&format!("{}", craft_xml::esc(t))); + } + body.push_str(&format!("")); + } + Generated::Kept(t) => body.push_str(&format!("{}", craft_xml::esc(t))), + } + } + format!( + "{body}" + ) +} + proptest! { #![proptest_config(ProptestConfig::with_cases(256))] + /// A packet of simple values, URIs, arrays and kept values reads, and reads back the same from + /// what it serializes to. + #[test] + fn valid_packets_round_trip(props in proptest::collection::vec(generated_property(), 0..12)) { + let text = generated_packet(&props); + let mut registry = Registry::default(); + let meta = xmp::parse(&text, &mut registry); + prop_assert!(meta.is_ok(), "{}", text); + let meta = meta.unwrap_or_default(); + prop_assert_eq!(meta.props.len(), props.len()); + let out = xmp::serialize(&meta, ®istry, true); + prop_assert!(out.is_ok(), "{}", text); + let again = xmp::parse(&out.unwrap_or_default(), &mut registry); + prop_assert_eq!(again.as_ref().ok(), Some(&meta), "{}", text); + } + /// Any arrangement of packet pieces reads without a panic, and what reads serializes to a packet /// that reads back the same. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index c1022c5933..11446fc177 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3062,29 +3062,39 @@ rules for these objects: `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. 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. - The namespaces that a packet's property, element and attribute names use are registered with the prefix the packet + or a value with qualifiers that a packet holds is kept as it was written, and `getProperty` gives its options. 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. + 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 - ` Date: Sun, 22 Nov 2026 16:01:53 -0800 Subject: [PATCH 14/21] Scripts: a replaced XMP sidecar keeps its group and access ACL closeFile() now replaces a sidecar through vectorcraft_format::keep_permissions, the same step a saved document takes. On Unix the temporary file takes the sidecar's permission bits, group and (on Linux) access ACL, or stays readable by its owner alone where the group or the ACL cannot be kept. Permission bits that cannot be set fail the write, and the sidecar stays as it was. A Linux test checks that a folder's default ACL does not reach a replaced sidecar. --- crates/engine/src/script/files.rs | 20 ++++++++--------- crates/engine/src/tests/script_xmp.rs | 31 +++++++++++++++++++++++++++ crates/format/src/atomic.rs | 8 ++++--- crates/format/src/lib.rs | 2 +- docs/mcp.md | 4 +++- 5 files changed, 50 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 2a6d2ec971..d0de6896c7 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1999,16 +1999,16 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { }; let r = write_temp(); drop(out); - // The replacement keeps the sidecar's permission bits. On Windows the only permission is the - // read-only attribute, and a read-only temporary file could not be removed after a failed - // rename. - let permissions = if cfg!(unix) { std::fs::metadata(&target).map(|m| m.permissions()).ok() } else { None }; - let r = r - .and_then(|()| permissions.map_or(Ok(()), |p| std::fs::set_permissions(&temp, p))) - .and_then(|()| std::fs::rename(&temp, &target)) - .inspect_err(|_| { - let _ = std::fs::remove_file(&temp); - }); + // 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. Permission + // bits that cannot be set fail the write, and the sidecar stays as it was. + #[cfg(not(target_arch = "wasm32"))] + let r = r.and_then(|()| 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 { diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index b39f3b28d7..40352cdd3d 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -583,6 +583,37 @@ fn a_temporary_file_starts_private() { 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("changed")); + 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] diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index e8f3c42b8e..8d034ab5df 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -302,9 +302,10 @@ fn temp_path(target: &Path) -> io::Result { /// 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(()) }; @@ -340,8 +341,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(()) } diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 430769069d..996bad2b4a 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -56,7 +56,7 @@ use vectorcraft_brush::stored_art::StoredArt; use vectorcraft_doc::{Document, ImageBlob}; #[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}; diff --git a/docs/mcp.md b/docs/mcp.md index 11446fc177..d365ca743b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3084,7 +3084,9 @@ rules for these objects: 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. With `XMPConst.CLOSE_UPDATE_SAFELY`, `closeFile()` writes only + when no temporary name is free, nothing is written. 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. 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 From a0cc0230b034809149c9945e183e0020caf0f3c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:52:35 -0800 Subject: [PATCH 15/21] Scripts: an XMP sidecar update flushes the packet first and goes through on volumes without Unix permissions - closeFile() flushes the temporary file to the disk with vectorcraft_format::sync_file before it takes the sidecar's name, as a saved document's temporary file is flushed. - Keeping the sidecar's permissions is best effort, as in write_atomic: a volume that refuses Unix permissions (SMB, FAT) no longer makes every update throw "Script file could not be written". - docs/mcp.md says both. --- crates/engine/src/script/files.rs | 15 +++++++++++---- docs/mcp.md | 3 ++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index d0de6896c7..762dae099a 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1995,17 +1995,24 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { 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) + 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. Permission - // bits that cannot be set fail the write, and the sidecar stays as it was. + // 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"))] - let r = r.and_then(|()| vectorcraft_format::keep_permissions(&target, &temp)); + 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); }); diff --git a/docs/mcp.md b/docs/mcp.md index d365ca743b..5fd06c6901 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3086,7 +3086,8 @@ rules for these objects: 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. 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. With `XMPConst.CLOSE_UPDATE_SAFELY`, `closeFile()` writes only + 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 From c17e7936efc62a33cbbc204a99e80c9551cc0310 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:01:22 -0800 Subject: [PATCH 16/21] Scripts: the host-name tables list ExternalObject and its members script_host_vs_scriptcheck failed on this branch because the host now adds the global ExternalObject. It goes in the table of names that reach outside the document, with the nativeCode id that script.check gives it; its length, prototype, search, constructor and terminate members stay inside. --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..fc1d5f9bf9 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -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. @@ -47,6 +48,8 @@ const INSIDE: &[(&str, &str)] = &[ ("Object.prototype.", "toSource"), ("localize.", "length"), ("toSource.", "length"), + ("ExternalObject.", "length prototype search"), + ("ExternalObject.prototype.", "constructor terminate"), ( "$.", "about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \ From 74ca9fb769f48a2c4f2a9422888726c88315f218 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:01:23 -0800 Subject: [PATCH 17/21] Scripts: XMP array items with xml:lang report the qualifier and language options getProperty with an item path and getArrayItem gave an item with an xml:lang qualifier the options 0. They now give PROP_HAS_QUALIFIERS and PROP_HAS_LANG, as a property with xml:lang has, and docs/mcp.md says so. --- crates/js/src/xmp.rs | 6 ++++++ crates/js/src/xmp_classes.rs | 4 ++-- crates/js/src/xmp_tests.rs | 11 +++++++++++ docs/mcp.md | 3 ++- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 2d4be10caf..fd1bff54f5 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -159,6 +159,12 @@ impl Item { pub(crate) fn has_lang(&self) -> bool { self.lang.as_deref().is_some_and(|l| !l.is_empty()) } + + /// The options `XMPProperty.options` gives for the item: an `xml:lang` qualifier, also an empty + /// one, is a qualifier and a language, as on a property. + pub(crate) fn options(&self) -> u32 { + if self.lang.is_some() { PROP_HAS_QUALIFIERS | PROP_HAS_LANG } else { 0 } + } } /// A property's value. diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 974be6b645..4587570ebe 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -422,7 +422,7 @@ fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul Step::Whole => property(i, &ns, &path, value.text(), value.options(), ""), Step::Item(index) => match value { xmp::Value::Array { items, .. } => match position(index, items.len()).and_then(|p| items.get(p)) { - Some(item) => property(i, &ns, &path, Some(&item.text), 0, item.lang.as_deref().unwrap_or("")), + Some(item) => property(i, &ns, &path, Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")), None => Ok(Value::Undefined), }, _ => Err(not_array(i, what, &name)), @@ -567,7 +567,7 @@ fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes }; let Some(item) = item else { return Ok(Value::Undefined) }; let path = format!("{path}[{}]", p + 1); - property(i, &ns, &path, Some(&item.text), 0, item.lang.as_deref().unwrap_or("")) + property(i, &ns, &path, Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")) } fn does_array_item_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 039d111a8b..391d09696f 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -76,6 +76,17 @@ fn a_packet_reads_into_properties() { assert_eq!(string(&with_packet("XMPMeta.getNamespacePrefix('http://example.com/ns/')")), "ex:"); } +/// An array item with an `xml:lang` qualifier has the qualifier and language options, read by path +/// or by index; an item without one has none. +#[test] +fn array_items_report_their_language_qualifier() { + let qualified = f64::from(0x10 | 0x40); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'title[2]').options")), JsValue::Number(qualified)); + assert_eq!(run(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'title', 1).options")), JsValue::Number(qualified)); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'subject[1]').options")), JsValue::Number(0.0)); + assert_eq!(run(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'subject', 2).options")), JsValue::Number(0.0)); +} + #[test] fn properties_arrays_and_namespaces_round_trip() { let src = "var ns = 'http://example.com/rt/'; diff --git a/docs/mcp.md b/docs/mcp.md index 5fd06c6901..f453f92b2b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3062,7 +3062,8 @@ rules for these objects: `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. 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. A + 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`. 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 From 758a62317b17724f85c95652d1b31a099e742cd8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:01:22 -0800 Subject: [PATCH 18/21] Correct XMP array insertion and empty item values --- crates/js/src/xmp_classes.rs | 13 ++++++++++--- crates/js/src/xmp_tests.rs | 18 ++++++++++++++++++ docs/mcp.md | 4 +++- docs/target-app-parity.md | 2 ++ 4 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 2588485114..40a3769fb3 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -16,6 +16,8 @@ //! name, `prefix:name`, and either with `[n]` (from 1) or `[last()]` for an array item. An array //! property holds simple items; any other value a packet holds is kept as it was written and //! `getProperty` gives its text, when it has one, and its options. +//! `insertArrayItem` inserts before the last existing item when its index is `ARRAY_LAST_ITEM`. +//! `insertArrayItem` and `setArrayItem` store `null` as an empty item value. //! //! `XMPFile` reads a file through the host functions `xmpOpen` and `xmpWrite` of `File` and //! `Folder` ([`crate::Realm::define_file_classes`]), so it reads and writes only where they may. A @@ -626,7 +628,10 @@ fn insert_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: Option len, - Some(-1) => len, + Some(-1) => match len.checked_sub(1) { + Some(p) => p, + None => return Err(out_of_range(i, what, -1)), + }, Some(n) => match usize::try_from(n) { Ok(n) if (1..=len + 1).contains(&n) => n - 1, _ => return Err(out_of_range(i, what, n)), @@ -717,7 +722,8 @@ fn insert_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> Js let o = this_meta(i, &this, what)?; let Target { ns, name, .. } = array_target(i, args, what)?; let index = item_index(i, &arg(args, 2), what)?; - let value = xml_text(i, &arg(args, 3), what)?; + let value = arg(args, 3); + let value = if matches!(value, Value::Null | Value::Undefined) { String::new() } else { xml_text(i, &value, what)? }; item_options(i, &arg(args, 4), what)?; insert_item(i, o, &ns, &name, Some(index), value, None, what) } @@ -727,7 +733,8 @@ fn set_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes let o = this_meta(i, &this, what)?; let Target { ns, name, .. } = array_target(i, args, what)?; let index = item_index(i, &arg(args, 2), what)?; - let value = xml_text(i, &arg(args, 3), what)?; + let value = arg(args, 3); + let value = if matches!(value, Value::Null | Value::Undefined) { String::new() } else { xml_text(i, &value, what)? }; item_options(i, &arg(args, 4), what)?; set_item(i, o, &ns, &name, index, value, true, what) } diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index b8c1f7274c..edd70e3fe1 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -119,6 +119,24 @@ fn properties_arrays_and_namespaces_round_trip() { assert_eq!(string("XMPMeta.getNamespaceURI('dc:')"), "http://purl.org/dc/elements/1.1/"); } +#[test] +fn array_last_insertion_precedes_the_last_existing_item() { + assert_eq!( + string(&with_packet( + "m.insertArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM, 'middle'); [1,2,3].map(function(n) { return m.getArrayItem(XMPConst.NS_DC, 'subject', n).value; }).join('|')" + )), + "one|middle|two" + ); + assert!(thrown(&with_packet("m.deleteArrayItem(XMPConst.NS_DC, 'subject', 2); m.deleteArrayItem(XMPConst.NS_DC, 'subject', 1); m.insertArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM, 'x')")).starts_with("RangeError:")); +} + +#[test] +fn null_array_values_are_empty_items() { + truth(&with_packet( + "m.insertArrayItem(XMPConst.NS_DC, 'subject', 1, null); m.setArrayItem(XMPConst.NS_DC, 'subject', 2, null); m.getArrayItem(XMPConst.NS_DC, 'subject', 1).value === '' && m.getArrayItem(XMPConst.NS_DC, 'subject', 2).value === ''", + )); +} + /// The prefix `xmlns` and the namespace of `xmlns` attributes are refused, so no packet declares /// them. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 4ac7e7b6bb..628d27699e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3388,7 +3388,9 @@ rules for these objects: `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. Arrays hold simple items; a structure + `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`. A value with qualifiers in the `rdf:value` form also gives the text of its `rdf:value`, and an empty property element diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8fedb40187..d15873b281 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -34,6 +34,8 @@ Native saves on Unix flush the destination directory after writing or replacing ## Feature submission evidence +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. + `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. History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. From cc2c5c770f0158c1c1a936f22cbdc9d24de51b74 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 19:15:16 -0800 Subject: [PATCH 19/21] Bound XMP metadata work and preserve packet boundaries --- crates/engine/src/script/files.rs | 39 ++- crates/engine/src/tests/script_xmp.rs | 41 +++ crates/js/src/host.rs | 46 ++- crates/js/src/xmp.rs | 262 ++++++++++++++- crates/js/src/xmp_classes.rs | 443 ++++++++++++++++++++++++-- crates/js/src/xmp_tests.rs | 210 ++++++++++++ docs/mcp.md | 11 +- docs/target-app-parity.md | 4 +- 8 files changed, 1004 insertions(+), 52 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 2502422398..a457b4374a 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1684,8 +1684,12 @@ fn millis(t: Option) -> 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) -> HostItem { + HostItem::Function(call_function(link, f)) +} + +fn call_function(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> 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) -> 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. @@ -1950,15 +1954,33 @@ fn xmp_open(host: &Host, a: &[Data]) -> Result { ])) } +fn xmp_utf8_packet(text: &str) -> Result, &'static str> { + let body = text.strip_prefix('\u{feff}').unwrap_or(text); + if body.starts_with(" 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 { let path = arg_text(a, 0); - let packet = arg_text(a, 1).into_bytes(); + 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)); @@ -2685,7 +2707,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("createAlias".into(), call(link, create_alias)), ("pick".into(), call(link, pick)), ("xmpOpen".into(), call(link, xmp_open)), - ("xmpWrite".into(), call(link, xmp_write)), + ( + "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_external_object() diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index 693f539206..3a4f8952f4 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -15,6 +15,26 @@ const PACKET: &str = "\ image/svg+xmlab\ "; +#[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, @@ -492,6 +512,27 @@ fn an_open_utf16_file_reads_the_written_packet() { 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!("\n{PACKET}\n"); + let packet = format!("{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] { diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 276895e782..81d8411530 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -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, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult> { 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) + ); + } +} diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 32eb37b924..758b027bdd 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -20,7 +20,9 @@ //! elements nest at most 64 deep, and each holds at most 1,024 attributes and has at most 1,024 //! namespace declarations in scope, both as read and as written; a //! child of `rdf:RDF` other than `rdf:Description` and text beside the descriptions or their -//! properties make the packet malformed, a property given twice keeps its first value, and +//! properties make the packet malformed, and a property given twice keeps its first value. +//! Explicit `rdf:about` values must agree, including empty values. Qualified names have valid prefix and local parts; +//! only spaces, tabs, carriage returns and line feeds count as indentation. //! [`find_packet`] finds only a UTF-8 packet. A realm registers at most [`MAX_NAMESPACES`] namespaces holding at most //! [`MAX_REGISTRY_BYTES`] bytes, each URI at most [`MAX_URI_BYTES`] bytes and each prefix at most //! [`MAX_PREFIX_BYTES`] bytes. @@ -30,6 +32,12 @@ use std::rc::Rc; use craft_xml::{Doctype, El, Limits, Names, Node, Options, UnknownEntity, XML_NS}; +#[cfg(test)] +thread_local! { + pub(crate) static ACCOUNTING_ITEM_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static ITEM_COPIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The RDF namespace. pub(crate) const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; /// The namespace of the `x:xmpmeta` element around a packet's `rdf:RDF`. @@ -148,12 +156,20 @@ impl Form { } /// An item of an array of simple values. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] pub(crate) struct Item { pub(crate) text: String, pub(crate) lang: Option, } +impl Clone for Item { + fn clone(&self) -> Self { + #[cfg(test)] + ITEM_COPIES.with(|copies| copies.set(copies.get() + 1)); + Self { text: self.text.clone(), lang: self.lang.clone() } + } +} + impl Item { /// Does the item name a language? `xml:lang=""` names none. pub(crate) fn has_lang(&self) -> bool { @@ -234,7 +250,11 @@ impl Prop { pub(crate) fn heap_bytes(&self) -> usize { let value = match &self.value { Value::Simple { text, .. } => text.len(), - Value::Array { items, .. } => items.iter().map(|i| 48 + i.text.len() + i.lang.as_ref().map_or(0, String::len)).sum(), + Value::Array { items, .. } => { + #[cfg(test)] + ACCOUNTING_ITEM_VISITS.with(|visits| visits.set(visits.get() + items.len())); + items.iter().map(|i| 48 + i.text.len() + i.lang.as_ref().map_or(0, String::len)).sum() + } Value::Other { expanded_bytes, text, .. } => expanded_bytes + text.as_ref().map_or(0, String::len), }; 96 + self.ns.len() + self.name.len() + value @@ -422,10 +442,27 @@ fn is_decl(name: &str) -> bool { name == "xmlns" || name.starts_with("xmlns:") } +fn valid_qualified_name(name: &str) -> bool { + name.split_once(':').map_or_else(|| is_ncname(name), |(prefix, local)| is_ncname(prefix) && is_ncname(local)) +} + +fn valid_packet_names(element: &El) -> bool { + valid_qualified_name(&element.name) + && element.attrs.iter().all(|(name, _)| valid_qualified_name(name)) + && element.elements().all(valid_packet_names) +} + /// The namespace and local name of the qualified name `name`: an unprefixed element is in the /// default namespace, an unprefixed attribute (`element` false) in none. `None` for a prefix /// nothing declares. fn resolve<'n>(name: &'n str, scope: &Scope, element: bool) -> Option<(String, &'n str)> { + if let Some((prefix, local)) = name.split_once(':') { + if !is_ncname(prefix) || !is_ncname(local) { + return None; + } + } else if !is_ncname(name) { + return None; + } let (prefix, local) = match name.split_once(':') { Some((p, l)) => (p, l), None if element => ("", name), @@ -554,14 +591,18 @@ fn parse_into(text: &str, registry: &mut Registry, budget: usize, retain_fragmen names: Names::AsWritten, doctype: Doctype::Reject, unknown_entity: UnknownEntity::Error, - drop_blank_text: true, + drop_blank_text: false, limits, ..Options::default() } .strict(); let root = opts.parse(text.as_bytes()).map_err(|e| if e.is_limit() { XmpError::TooLarge } else { XmpError::Malformed })?; + if !valid_packet_names(&root) { + return Err(XmpError::Malformed); + } let mut scope = Scope::new(); let rdf = find_rdf(&root, &mut scope).ok_or(XmpError::Malformed)?; + let mut explicit_subject = None; // Text beside the descriptions or their properties is not RDF. if rdf.children.iter().any(is_stray_text) { return Err(XmpError::Malformed); @@ -576,6 +617,12 @@ fn parse_into(text: &str, registry: &mut Registry, budget: usize, retain_fragmen for (k, v) in attrs(d) { let Some((ns, local)) = resolve(k, &scope, false) else { return Err(XmpError::Malformed) }; if ns == RDF { + if local == "about" { + if explicit_subject.is_some_and(|subject| subject != v) { + return Err(XmpError::Malformed); + } + explicit_subject = Some(v); + } if local == "about" && reading.meta.about.is_empty() { reading.meta.about = v.to_string(); reading.bytes = reading.bytes.saturating_add(v.len()); @@ -619,10 +666,10 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry, reading: &m Value::Simple { text: text_of(p), uri: false } } else if let ([], [(k, v)]) = (children.as_slice(), own.as_slice()) && is_named(k, scope, false, RDF, "resource") - && text_of(p).trim().is_empty() + && text_of(p).trim_matches([' ', '\t', '\r', '\n']).is_empty() { Value::Simple { text: (*v).to_string(), uri: true } - } else if let (Some(array), true) = (array_of(&children, scope), own.is_empty() && text_of(p).trim().is_empty()) { + } else if let (Some(array), true) = (array_of(&children, scope), own.is_empty() && text_of(p).trim_matches([' ', '\t', '\r', '\n']).is_empty()) { array } else { // A written packet puts a property 3 elements deep (`x:xmpmeta`, `rdf:RDF`, @@ -680,7 +727,7 @@ fn array_of(children: &[&El], scope: &mut Scope) -> Option { push_decls(container, scope); let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&container.name, scope, true, RDF, &f.element()[4..])); let mut items = Vec::new(); - let ok = form.is_some() && attrs(container).is_empty() && text_of(container).trim().is_empty() && { + let ok = form.is_some() && attrs(container).is_empty() && text_of(container).trim_matches([' ', '\t', '\r', '\n']).is_empty() && { container.elements().all(|li| { let inner = scope.len(); push_decls(li, scope); @@ -1058,10 +1105,37 @@ pub struct PacketSpan { /// The characters of whitespace padding just before the ` usize { - packet.rfind(" Ok(event), + Ok(None) => break, + Err(error) => Err(error), + }; + match event { + Ok(craft_xml::Event::Start { .. }) => depth += 1, + Ok(craft_xml::Event::End { .. }) => { + depth = depth.saturating_sub(1); + rooted |= depth == 0; + } + Ok(craft_xml::Event::Pi { target, data }) if depth == 0 && target == "xpacket" => { + if !rooted && data.starts_with("begin=") { + begun = [format!("id=\"{WRAPPER_ID}\""), format!("id='{WRAPPER_ID}'")].iter().any(|id| data.contains(id)); + } else if rooted + && begun + && matches!(data.trim_end_matches([' ', '\t', '\r', '\n']), "end=\"r\"" | "end=\"w\"" | "end='r'" | "end='w'") + { + let before = &packet[..events.span().start]; + return before.len() - before.trim_end_matches([' ', '\t', '\r', '\n']).len(); + } + } + Err(_) => return 0, + _ => {} + } + } + 0 } /// The first UTF-8 packet in `bytes` that has both ends of its wrapper (XMP Specification Part 1, @@ -1093,11 +1167,41 @@ pub fn find_packet(bytes: &[u8]) -> Option { let mut closes = Later::new(b"?>"); let mut section_ends = SECTIONS.map(|(_, close)| Later::new(close)); let mut start = None; + let mut skipped_headers = Vec::new(); + let mut ignored_sections = std::collections::BTreeMap::new(); + let mut xml_trailer = None; let mut pos = 0; while let Some(at) = rest(pos).iter().position(|&b| b == b'<').map(|i| i + pos) { pos = at + 1; + let here = rest(at); + if here.starts_with(b" close)) { + if start.is_some() + && let Some(close) = close + { + let first = starts.partition_point(|&begin| begin < at + 2); + let end = starts.partition_point(|&begin| begin < close); + skipped_headers.extend_from_slice(&starts[first..end]); + } + pos = close.map_or(len, |close| close + 2); + continue; + } + } if starts.binary_search(&at).is_ok() { + if let Some(from) = start { + if xml_trailer.as_ref().is_none_or(|(checked, _)| *checked != from) { + xml_trailer = Some((from, packet_trailer(&bytes[from..]))); + } + if let Some((_, Ok((_, end, _)))) = xml_trailer + && at < from + end + { + pos = at + BEGIN.len(); + continue; + } + } start = Some(at); + skipped_headers.clear(); pos = at + BEGIN.len(); continue; } @@ -1106,7 +1210,6 @@ pub fn find_packet(bytes: &[u8]) -> Option { pos = start_after(pos)?; continue; }; - let here = rest(at); if let Some(kind) = SECTIONS.iter().position(|(open, _)| here.starts_with(open)) { let (open, close) = SECTIONS[kind]; let inside = at + open.len(); @@ -1115,6 +1218,7 @@ pub fn find_packet(bytes: &[u8]) -> Option { let hides_packet = end.is_some_and(|end| ends.find(bytes, inside).is_some_and(|e| e < end && start_after(e).is_some_and(|s| s < end))); if let (Some(end), false) = (end, hides_packet) { pos = end + close.len(); + ignored_sections.insert(at, pos); } continue; } @@ -1125,12 +1229,70 @@ pub fn find_packet(bytes: &[u8]) -> Option { let close = closes.find(bytes, after)?; if let Some(next) = start_after(after).filter(|&next| next < close) { start = Some(next); + skipped_headers.clear(); pos = next + BEGIN.len(); continue; } + let trailer_value = std::str::from_utf8(&bytes[after..close]).ok().map(|value| value.trim_end_matches([' ', '\t', '\r', '\n'])); + if !matches!(trailer_value, Some("\"r\"" | "\"w\"" | "'r'" | "'w'")) { + pos = close + 2; + continue; + } + if xml_trailer.as_ref().is_none_or(|(checked, _)| *checked != from) { + xml_trailer = Some((from, packet_trailer(&bytes[from..]))); + } + if let Some((_, Err(Some(next)))) = xml_trailer { + start = Some(from + next); + skipped_headers.clear(); + pos = from + next + BEGIN.len(); + continue; + } + if let Some((_, Ok((trailer, _, _)))) = xml_trailer + && from + trailer > at + { + pos = from + trailer; + continue; + } let span = PacketSpan { start: from, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }; - if bytes.get(span.start..span.end).is_some_and(|p| std::str::from_utf8(p).is_ok()) { - return Some(span); + let packet = bytes.get(span.start..span.end)?; + if std::str::from_utf8(packet).is_ok() { + let mut selected = span.start; + if !skipped_headers.is_empty() { + while let Some(restart) = packet_xml_restart(&bytes[selected..span.end]) { + let threshold = selected.saturating_add(restart); + let index = skipped_headers.partition_point(|&header| header <= selected || header < threshold); + let Some(next) = skipped_headers.get(index).copied().filter(|&header| header < span.end) else { break }; + selected = next; + } + } + let trailer = if selected == from { xml_trailer.map_or(Err(None), |(_, trailer)| trailer) } else { packet_trailer(&bytes[selected..]) }; + if let Ok((_, end, writeable)) = trailer { + return Some(PacketSpan { start: selected, end: selected + end, writeable }); + } + if let Err(Some(next)) = trailer { + start = Some(selected + next); + skipped_headers.clear(); + pos = selected + next + BEGIN.len(); + continue; + } + return Some(PacketSpan { start: selected, ..span }); + } + let mut checked = span.start; + let mut last_invalid = span.start; + while let Err(error) = std::str::from_utf8(&bytes[checked..span.end]) { + checked += error.valid_up_to() + error.error_len().unwrap_or(1); + last_invalid = checked; + } + let next = starts[starts.partition_point(|&header| header < last_invalid)..] + .iter() + .copied() + .take_while(|&header| header < span.end) + .find(|&header| ignored_sections.range(..=header).next_back().is_none_or(|(_, &end)| header >= end)); + if let Some(next) = next { + start = Some(next); + skipped_headers.clear(); + pos = next + BEGIN.len(); + continue; } start = None; pos = span.end; @@ -1138,6 +1300,78 @@ pub fn find_packet(bytes: &[u8]) -> Option { None } +fn packet_trailer(packet: &[u8]) -> Result<(usize, usize, bool), Option> { + let options = Options { names: Names::AsWritten, doctype: Doctype::Reject, unknown_entity: UnknownEntity::Literal, ..Options::default() }; + let mut events = options.events(packet); + let mut depth = 0usize; + let ids = [format!("id=\"{WRAPPER_ID}\""), format!("id='{WRAPPER_ID}'")]; + while let Some(event) = events.next().map_err(|_| None)? { + let span = events.span(); + #[cfg(test)] + PACKET_XML_READ_BYTES.with(|bytes| bytes.set(bytes.get() + span.len())); + match event { + craft_xml::Event::Start { .. } => depth += 1, + craft_xml::Event::End { .. } => { + depth = depth.saturating_sub(1); + } + craft_xml::Event::Pi { target, data } if depth == 0 && target == "xpacket" => { + if span.start != 0 && span.len() <= MAX_HEADER && data.starts_with("begin=") && ids.iter().any(|id| data.contains(id)) { + return Err(Some(span.start)); + } + match data.trim_end_matches([' ', '\t', '\r', '\n']) { + "end=\"r\"" | "end='r'" => return Ok((span.start, span.end, false)), + "end=\"w\"" | "end='w'" => return Ok((span.start, span.end, true)), + _ => {} + } + } + _ => {} + } + } + Err(None) +} + +#[cfg(test)] +std::thread_local! { + pub(crate) static PACKET_XML_READ_BYTES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn packet_xml_restart(packet: &[u8]) -> Option { + let options = Options { names: Names::AsWritten, doctype: Doctype::Reject, unknown_entity: UnknownEntity::Error, ..Options::default() }.strict(); + let mut events = options.events(packet); + let mut open = Vec::new(); + let mut complete = None; + loop { + let event = match events.next() { + Ok(Some(event)) => Ok(event), + Ok(None) => break, + Err(error) => Err(error), + }; + let span = events.span(); + #[cfg(test)] + PACKET_XML_READ_BYTES.with(|bytes| bytes.set(bytes.get() + span.len())); + match event { + Ok(craft_xml::Event::Start { .. }) => open.push(span.start), + Ok(craft_xml::Event::End { .. }) => { + open.pop(); + if open.is_empty() { + complete = Some(span.end); + } + } + Err(_) => { + return Some(if span.start == packet.len() { + open.last().map_or(span.end, |start| start + 1) + } else if open.is_empty() { + complete.unwrap_or(span.end) + } else { + span.end + }); + } + _ => {} + } + } + None +} + /// The next place of a marker at or after a given point. While the points do not go back, each /// search starts past the last one, so the searches together read the bytes about once. struct Later { diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 40a3769fb3..e8b733a864 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -18,6 +18,7 @@ //! `getProperty` gives its text, when it has one, and its options. //! `insertArrayItem` inserts before the last existing item when its index is `ARRAY_LAST_ITEM`. //! `insertArrayItem` and `setArrayItem` store `null` as an empty item value. +//! Metadata edits charge fuel for size accounting. //! //! `XMPFile` reads a file through the host functions `xmpOpen` and `xmpWrite` of `File` and //! `Folder` ([`crate::Realm::define_file_classes`]), so it reads and writes only where they may. A @@ -33,7 +34,7 @@ //! reference lists that is not built yet, and a flag, format or option not handled yet, throws an //! error that says so. -use crate::builtins::{arg, data, method, native}; +use crate::builtins::arg; use crate::heap::{Class, ENUMERABLE, HIDDEN, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, PropMap, key, string_bytes}; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; use crate::value::Value; @@ -216,10 +217,20 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { } fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + set_slot_with_charge(i, o, name, value, true) +} + +fn set_slot_with_charge(i: &mut Interp, o: ObjId, name: &str, value: Value, charged: bool) -> JsResult<()> { if let Some(Class::XmpFile(fields)) = i.heap.object(o).map(|object| &object.class) { let name = key(name); let added = if fields.contains(&name) { 0 } else { PROP_BYTES + string_bytes(name.len()) }; - let strings = if let Value::String(s) = &value { string_bytes(s.len()) } else { 0 }; + let strings = if charged { + 0 + } else if let Value::String(s) = &value { + string_bytes(s.len()) + } else { + 0 + }; return i.rooted(&[Value::Object(o), value.clone()], |i| { i.reserve_heap(added + strings)?; if let Some(Class::XmpFile(fields)) = i.heap.object_mut(o).map(|object| &mut object.class) { @@ -255,7 +266,8 @@ fn string(i: &mut Interp, s: &str) -> JsResult { /// A new ordinary object with the prototype `proto` and the read-only data properties `fields`. fn record(i: &mut Interp, proto: Option, fields: Vec<(&'static str, Value)>) -> JsResult { i.rooted(&fields.iter().map(|(_, v)| v.clone()).collect::>(), |i| { - i.reserve_heap(OBJECT_BYTES + PROP_BYTES * fields.len())?; + let keys: usize = fields.iter().map(|(name, _)| string_bytes(name.encode_utf16().count())).sum(); + i.reserve_heap(OBJECT_BYTES + PROP_BYTES * fields.len() + keys)?; let o = i.heap.alloc_object(Object::new(Class::Ordinary, proto.or(Some(i.intrinsics.object_proto)))); for (name, value) in &fields { i.define(o, key(name), Prop::Data { value: value.clone(), flags: ENUMERABLE })?; @@ -275,12 +287,24 @@ fn external_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult< } let ids = ids(i)?; let global = i.global; - data(i, global, "XMPMeta", Value::Object(ids.meta), HIDDEN)?; - data(i, global, "XMPFile", Value::Object(ids.file), HIDDEN)?; - data(i, global, "XMPConst", Value::Object(ids.constants), HIDDEN)?; i.reserve_heap(OBJECT_BYTES + PROP_BYTES)?; let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(ids.external_proto))); - i.rooted(&[Value::Object(o)], |i| set_slot(i, o, LIBRARY_SLOT, Value::str(LIBRARY)))?; + i.rooted(&[Value::Object(o)], |i| { + let library = string(i, LIBRARY)?; + data(i, o, LIBRARY_SLOT, library, 0)?; + let members = [("XMPMeta", ids.meta), ("XMPFile", ids.file), ("XMPConst", ids.constants)]; + let mut added = 0; + for (name, _) in members { + if i.get_own_property(global, &key(name))?.is_none() { + added += PROP_BYTES + string_bytes(name.len()); + } + } + i.reserve_heap(added)?; + for (name, value) in members { + crate::builtins::data(i, global, name, Value::Object(value), HIDDEN)?; + } + Ok(()) + })?; Ok(Value::Object(o)) } @@ -318,14 +342,20 @@ fn meta_of(i: &Interp, o: ObjId) -> JsResult<&Meta> { /// Changes the metadata of `o` with `f`, given `grow`, the most bytes the change adds, and charges /// the heap for what it added or frees what it took out. fn change(i: &mut Interp, o: ObjId, grow: usize, f: impl FnOnce(&mut Meta, &Registry) -> T) -> JsResult { + let accounting = meta_of(i, o)?.heap_bytes().saturating_mul(3).saturating_add(grow); + spend(i, accounting)?; + change_counted(i, o, grow, None, f) +} + +fn change_counted(i: &mut Interp, o: ObjId, grow: usize, delta: Option<(usize, usize)>, f: impl FnOnce(&mut Meta, &Registry) -> T) -> JsResult { i.reserve_heap(grow)?; let Some(c) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; let Some(Class::Xmp(m)) = i.heap.object_mut(o).map(|ob| &mut ob.class) else { return Err(Abrupt::Internal("an XMPMeta lost its metadata".into())); }; - let before = m.heap_bytes(); + let before = delta.map_or_else(|| m.heap_bytes(), |(removed, _)| removed); let r = f(m, &c.registry); - let after = m.heap_bytes(); + let after = delta.map_or_else(|| m.heap_bytes(), |(_, added)| added); i.heap.bytes = if after >= before { i.heap.bytes.saturating_add(after - before) } else { i.heap.bytes.saturating_sub(before - after) }; Ok(r) } @@ -450,19 +480,22 @@ fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul } let found = { let m = meta_of(i, o)?; - m.find(&ns, &name).map(|at| m.props[at].value.clone()) - }; - let Some(value) = found else { return Ok(Value::Undefined) }; - match step { - Step::Whole => property(i, &ns, &path, value.text(), value.options(), ""), - Step::Item(index) => match value { - xmp::Value::Array { items, .. } => match position(index, items.len()).and_then(|p| items.get(p)) { - Some(item) => property(i, &ns, &path, Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")), - None => Ok(Value::Undefined), + match m.find(&ns, &name).map(|at| &m.props[at].value) { + None => Ok(None), + Some(value) => match step { + Step::Whole => Ok(Some((value.text().map(str::to_string), value.options(), String::new()))), + Step::Item(index) => match value { + xmp::Value::Array { items, .. } => Ok(position(index, items.len()) + .and_then(|p| items.get(p)) + .map(|item| (Some(item.text.clone()), item.options(), item.lang.clone().unwrap_or_default()))), + _ => Err(()), + }, }, - _ => Err(not_array(i, what, &name)), - }, - } + } + }; + let found = found.map_err(|()| not_array(i, what, &name))?; + let Some((text, options, locale)) = found else { return Ok(Value::Undefined) }; + property(i, &ns, &path, text.as_deref(), options, &locale) } fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -638,8 +671,9 @@ fn insert_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: Option()))?; match found { - Some((at, _, _)) => change(i, o, grow, |m, _| { + Some((at, _, _)) => change_counted(i, o, grow, Some((0, grow)), |m, _| { if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) { items.insert(p.min(items.len()), Item { text: value, lang: None }); } @@ -909,12 +943,22 @@ fn set_lang(items: &mut Vec, generic: &str, specific: &str, value: String) fn serialized(i: &mut Interp, o: ObjId, v: &Value, what: &str) -> JsResult { let options = flags(i, v, what)?; only(i, options, SERIALIZE_OMIT_PACKET_WRAPPER, what)?; + let work = { + let Some(classes) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; + let meta = meta_of(i, o)?; + let prefixes = meta + .props + .iter() + .filter(|property| !matches!(property.value, xmp::Value::Other { .. })) + .fold(0usize, |bytes, property| bytes.saturating_add(classes.registry.prefix_of(&property.ns).map_or(0, str::len))); + meta.heap_bytes().saturating_mul(6).saturating_add(prefixes.saturating_mul(3)) + }; + spend(i, work)?; let r = { let Some(c) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; xmp::serialize(meta_of(i, o)?, &c.registry, options & SERIALIZE_OMIT_PACKET_WRAPPER == 0) }; let s = r.map_err(|e| xmp_error(i, what, e, ""))?; - spend(i, s.len())?; Ok(s) } @@ -1090,7 +1134,7 @@ fn get_xmp(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult return Ok(Value::Null); } let text = text(i, &packet)?; - let meta = if text.trim().is_empty() { Meta::default() } else { parse_packet(i, what, &text)? }; + let meta = if text.trim_matches([' ', '\t', '\r', '\n']).is_empty() { Meta::default() } else { parse_packet(i, what, &text)? }; new_meta(i, meta) } @@ -1104,7 +1148,9 @@ fn get_packet_info(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResul let char_form = slot(i, o, CHAR_FORM)?; // The padding is counted in bytes: two for each character of a UTF-16 packet. let unit = if matches!(char_form, Value::Number(n) if n == 2.0 || n == 3.0) { 2 } else { 1 }; - let pad = crate::xmp::pad_size(&text(i, &packet)?) * unit; + let packet_text = text(i, &packet)?; + spend(i, packet_text.len())?; + let pad = crate::xmp::pad_size(&packet_text) * unit; let fields = vec![ ("charForm", char_form), ("length", slot(i, o, LENGTH)?), @@ -1191,7 +1237,7 @@ fn put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult< // ---- install ---- +fn native(i: &mut Interp, name: &'static str, f: crate::heap::NativeFn, length: u32, kind: NativeKind, constructor: bool) -> JsResult { + i.reserve_heap(OBJECT_BYTES + PROP_BYTES + string_bytes("length".len()))?; + crate::builtins::native(i, name, f, length, kind, constructor) +} + +fn data(i: &mut Interp, on: ObjId, name: &str, value: Value, flags: u8) -> JsResult<()> { + let added = if i.get_own_property(on, &key(name))?.is_some() { 0 } else { PROP_BYTES + string_bytes(name.encode_utf16().count()) }; + i.rooted(&[Value::Object(on), value.clone()], |i| { + i.reserve_heap(added)?; + crate::builtins::data(i, on, name, value, flags) + }) +} + +fn method(i: &mut Interp, on: ObjId, name: &'static str, f: crate::heap::NativeFn, length: u32) -> JsResult<()> { + i.rooted(&[Value::Object(on)], |i| { + let method = native(i, name, f, length, NativeKind::Plain, false)?; + data(i, on, name, Value::Object(method), HIDDEN) + }) +} + /// A data property of `XMPConst`: read-only, enumerable. fn constant(i: &mut Interp, on: ObjId, name: &str, value: Value) -> JsResult<()> { data(i, on, name, value, ENUMERABLE) } fn constants(i: &mut Interp) -> JsResult { + i.reserve_heap(OBJECT_BYTES)?; let o = i.new_object(); i.rooted(&[Value::Object(o)], |i| { let namespaces = [ @@ -1240,7 +1307,8 @@ fn constants(i: &mut Interp) -> JsResult { ("NS_PHOTOSHOP", xmp::PHOTOSHOP), // brand-ok: the constant's name in the reference ]; for (name, uri) in namespaces { - constant(i, o, name, Value::str(uri))?; + let value = string(i, uri)?; + constant(i, o, name, value)?; } let numbers: [(&str, f64); 14] = [ ("FILE_UNKNOWN", f64::from(FILE_UNKNOWN)), @@ -1353,7 +1421,8 @@ pub(crate) fn install(i: &mut Interp) -> JsResult<()> { i.rooted(&[Value::Object(external)], |i| { method(i, external, "search", external_search, 1)?; method(i, external_proto, "terminate", external_terminate, 0)?; - crate::builtins::constructor(i, "ExternalObject", external, external_proto) + link(i, external, external_proto)?; + data(i, i.global, "ExternalObject", Value::Object(external), HIDDEN) }) }) }) @@ -1368,6 +1437,324 @@ pub(crate) fn install(i: &mut Interp) -> JsResult<()> { mod namespace_heap_tests { use super::*; + #[test] + fn non_xml_whitespace_sidecars_are_not_empty_metadata() { + for text in ["\u{a0}", "\u{2003}", "\u{85}", " \t\r\n"] { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + crate::file_classes::install( + &mut interp, + vec![("current".into(), crate::HostItem::Function(std::rc::Rc::new(|_| Ok(crate::Data::String(String::new())))))], + ) + .unwrap(); + install(&mut interp).unwrap(); + let mut fields = PropMap::default(); + fields.insert(key(PATH), Value::str("packet.xmp")); + fields.insert(key(OPEN), Value::Bool(true)); + fields.insert(key(RUN), Value::Number(crate::file_classes::run_count(&interp).unwrap())); + fields.insert(key(PACKET), Value::str(text)); + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), Some(ids(&interp).unwrap().file_proto))); + let value = Value::Object(object); + interp + .rooted(std::slice::from_ref(&value), |interp| { + let result = get_xmp(interp, value.clone(), &[], false); + if text == " \t\r\n" { + assert!(result.is_ok()); + } else { + assert!(matches!(result, Err(Abrupt::Throw(_))), "{text:?}: {result:?}"); + } + Ok(()) + }) + .unwrap(); + } + } + + #[test] + fn inserting_array_items_charges_for_shifted_items() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Bag, items: vec![Item { text: "text".into(), lang: None }; 1000] }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + interp.fuel = 100; + let result = insert_item(interp, object, xmp::DC, "items", Some(1), "insert".into(), None, "insert"); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn result_records_reserve_their_retained_property_keys() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + interp.collect_garbage(); + let name = "a_property_name_with_retained_key_storage"; + interp.limits.heap_bytes = interp.heap.bytes + OBJECT_BYTES + PROP_BYTES + string_bytes(name.len()) - 1; + let result = record(&mut interp, None, vec![(name, Value::Number(1.0))]); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Heap))), "{result:?}"); + } + + #[test] + fn replacing_array_items_charges_metadata_accounting_work() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Bag, items: vec![Item { text: "text".into(), lang: None }; 1000] }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + interp.fuel = 100; + let result = + set_array_item(interp, value.clone(), &[Value::str(xmp::DC), Value::str("items"), Value::Number(1.0), Value::str("edit")], false); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn unrelated_namespaces_do_not_spend_serialization_fuel() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + for index in 0..400 { + registry(&mut interp).unwrap().register(&format!("urn:unused:{index}:{}", "x".repeat(990)), &format!("unused_{index}")).unwrap(); + } + let value = new_meta(&mut interp, Meta::default()).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + interp.fuel = 10_000; + assert!(serialized(interp, object, &Value::Undefined, "serialize").is_ok()); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn repeated_library_handles_fit_their_retained_size() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + external_ctor(&mut interp, Value::Undefined, &[Value::str(LIBRARY)], true).unwrap(); + for room in 0..2048 { + interp.collect_garbage(); + let baseline = interp.heap.bytes; + interp.limits.heap_bytes = baseline + room; + if let Ok(value) = external_ctor(&mut interp, Value::Undefined, &[Value::str(LIBRARY)], true) { + interp + .rooted(&[value], |interp| { + interp.collect_garbage(); + assert_eq!(room, interp.heap.bytes - baseline, "extra heap reservation for a retained handle"); + Ok(()) + }) + .unwrap(); + return; + } + } + panic!("no library handle fit"); + } + + #[test] + fn a_failed_external_constructor_publishes_no_partial_globals() { + let mut failures = 0; + let mut successes = 0; + for room in (0..4096).step_by(16) { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + room; + let result = external_ctor(&mut interp, Value::Undefined, &[Value::str(LIBRARY)], true); + if result.is_err() { + failures += 1; + for name in ["XMPMeta", "XMPFile", "XMPConst"] { + assert!(interp.get_own_property(interp.global, &key(name)).unwrap().is_none(), "partial global {name}, room={room}"); + } + } else if let Ok(value) = result { + successes += 1; + interp + .rooted(&[value], |interp| { + interp.collect_garbage(); + assert!( + interp.heap.bytes <= interp.limits.heap_bytes, + "constructor retained {} bytes with limit {}", + interp.heap.bytes, + interp.limits.heap_bytes + ); + Ok(()) + }) + .unwrap(); + } + } + assert!(failures > 0 && successes > 0); + } + + #[test] + fn packet_info_charges_fuel_for_scanning_the_packet() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + crate::file_classes::install( + &mut interp, + vec![("current".into(), crate::HostItem::Function(std::rc::Rc::new(|_| Ok(crate::Data::String(String::new())))))], + ) + .unwrap(); + install(&mut interp).unwrap(); + let mut fields = PropMap::default(); + fields.insert(key(PATH), Value::str("packet.xmp")); + fields.insert(key(OPEN), Value::Bool(true)); + fields.insert(key(RUN), Value::Number(crate::file_classes::run_count(&interp).unwrap())); + fields.insert(key(PACKET), Value::str(&" ".repeat(4096))); + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), Some(ids(&interp).unwrap().file_proto))); + let this = Value::Object(object); + interp + .rooted(std::slice::from_ref(&this), |interp| { + interp.fuel = 1000; + get_packet_info(interp, this.clone(), &[], false)?; + assert!(interp.fuel <= 983, "packet scan used only {} fuel", 1000 - interp.fuel); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn staging_a_packet_charges_its_string_only_once() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + crate::file_classes::install( + &mut interp, + vec![("current".into(), crate::HostItem::Function(std::rc::Rc::new(|_| Ok(crate::Data::String(String::new())))))], + ) + .unwrap(); + install(&mut interp).unwrap(); + let mut fields = PropMap::default(); + for (name, value) in [ + (PATH, Value::str("packet.xmp")), + (RUN, Value::Number(crate::file_classes::run_count(&interp).unwrap())), + (OPEN, Value::Bool(true)), + (FLAGS, Value::Number(f64::from(OPEN_FOR_UPDATE))), + (SIDECAR, Value::Bool(true)), + (PENDING, Value::Undefined), + ] { + fields.insert(key(name), value); + } + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), Some(ids(&interp).unwrap().file_proto))); + let this = Value::Object(object); + interp + .rooted(std::slice::from_ref(&this), |interp| { + let packet = format!( + "{}", + xmp::RDF, + "x".repeat(4096) + ); + let argument = string(interp, &packet)?; + interp.rooted(std::slice::from_ref(&argument), |interp| { + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + string_bytes(packet.encode_utf16().count()) + 512; + let result = put_xmp(interp, this.clone(), std::slice::from_ref(&argument), false); + assert!(result.is_ok(), "a single pending packet charge fits: {result:?}"); + Ok(()) + }) + }) + .unwrap(); + } + + #[test] + fn storing_an_open_packet_reuses_its_charged_string() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let packet = string(&mut interp, &"x".repeat(4096)).unwrap(); + interp + .rooted(std::slice::from_ref(&packet), |interp| { + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::default()), Some(ids(interp)?.file_proto))); + interp.rooted(&[Value::Object(object)], |interp| { + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + 512; + set_slot(interp, object, PACKET, packet.clone()) + }) + }) + .unwrap(); + } + + #[test] + fn a_failed_serialization_charges_its_escaping_work() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "value".into(), + value: xmp::Value::Simple { text: "&".repeat(xmp::MAX_BYTES / 4), uri: false }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + interp.fuel = 100_000; + let result = serialized(interp, object, &Value::Undefined, "serialize"); + assert!(matches!(result, Err(Abrupt::Throw(_))), "{result:?}"); + assert!(interp.fuel < 100_000, "failed escaping left its work unpaid"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn indexed_property_reads_copy_only_the_selected_item() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Bag, items: vec![Item { text: "text".into(), lang: None }; 1000] }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + xmp::ITEM_COPIES.with(|copies| copies.set(0)); + for index in 1..=1000 { + get_property(interp, value.clone(), &[Value::str(xmp::DC), Value::str(&format!("items[{index}]"))], false).unwrap(); + } + let copies = xmp::ITEM_COPIES.with(|copies| copies.get()); + assert!(copies <= 1000, "copied {copies} items for 1000 indexed reads"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn appending_array_items_has_linear_accounting_work() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let value = new_meta(&mut interp, Meta::default()).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + xmp::ACCOUNTING_ITEM_VISITS.with(|visits| visits.set(0)); + for _ in 0..1000 { + insert_item(interp, object, xmp::DC, "items", None, "text".into(), Some(Form::Bag), "append").unwrap(); + } + let visits = xmp::ACCOUNTING_ITEM_VISITS.with(|visits| visits.get()); + assert!(visits <= 2000, "accounting visited {visits} items for 1000 appends"); + Ok(()) + }) + .unwrap(); + } + #[test] fn parsed_namespaces_fit_with_the_metadata_before_registration() { let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index edd70e3fe1..af5b090b31 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -47,6 +47,189 @@ const PACKET: &str = r#" "#; +#[test] +fn rdf_qualified_names_validate_both_parts() { + let packet = PACKET.replace("ex:a>", "ex:a:b>"); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + assert!(xmp::parse(PACKET, &mut Registry::default()).is_ok()); +} + +#[test] +fn rdf_non_xml_whitespace_is_not_indentation() { + let packet = PACKET.replace("", "\u{a0}"); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + assert!(xmp::parse(&PACKET.replace("", " \t\r\n"), &mut Registry::default()).is_ok()); +} + +#[test] +fn rdf_descriptions_reject_conflicting_nonempty_subjects() { + let packet = PACKET + .replace("rdf:about=\"\"", "rdf:about=\"urn:a\"") + .replace("", ""); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + assert!(xmp::parse(&packet.replace("urn:b", "urn:a"), &mut Registry::default()).is_ok()); +} + +#[test] +fn explicit_empty_and_named_rdf_subjects_cannot_be_merged() { + for (first, second) in [("", "urn:a"), ("urn:a", "")] { + let packet = PACKET + .replace("rdf:about=\"\"", &format!("rdf:about=\"{first}\"")) + .replace("", &format!("")); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + } +} + +#[test] +fn packet_padding_requires_an_actual_wrapper_trailer() { + let packet = r#""#; + assert_eq!(xmp::pad_size(packet), 0); + assert!(xmp::pad_size(PACKET) > 0); + let prefixed = format!("\n\n{PACKET}"); + assert_eq!(xmp::pad_size(&prefixed), xmp::pad_size(PACKET)); + assert_eq!(xmp::pad_size(&format!("{PACKET}")), xmp::pad_size(PACKET)); + assert_eq!(xmp::pad_size(&format!("{PACKET}")), xmp::pad_size(PACKET)); + let comment = ""; + assert_eq!(xmp::pad_size(&PACKET.replace("", &format!("{comment}"))), xmp::pad_size(PACKET)); +} + +#[test] +fn packet_padding_ignores_invalid_trailer_values() { + for value in ["note", "", "ww", "W"] { + let packet = PACKET.replace("", &format!(" \n ")); + assert_eq!(xmp::pad_size(&packet), 6, "{value:?}"); + } +} + +#[test] +fn packet_scans_ignore_trailers_inside_the_xml_root() { + let packet = PACKET.replace("", ""); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); + let packet = PACKET.replace("", ""); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); +} + +#[test] +fn malformed_wrapped_xml_is_not_reported_as_absent() { + let packet = PACKET.replace("image/svg+xml", "&undefined;"); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); + assert!(xmp::parse(&packet[span.start..span.end], &mut Registry::default()).is_err()); +} + +#[test] +fn wrapper_lookahead_stops_before_unrelated_later_packets() { + let header = ""; + let incomplete = format!("{header}"); + let packet = format!("{}{PACKET}", incomplete.repeat(1000)); + xmp::PACKET_XML_READ_BYTES.with(|bytes| bytes.set(0)); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, incomplete.len())); + let read = xmp::PACKET_XML_READ_BYTES.with(|bytes| bytes.get()); + assert!(read <= incomplete.len() * 4, "lookahead read {read} bytes for {} byte candidate", incomplete.len()); +} + +#[test] +fn an_inner_trailer_does_not_pair_an_orphan_with_the_next_packet() { + let orphan = PACKET.replace("", "").replace("", ""); + let packet = format!("{orphan}{PACKET}"); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (orphan.len(), packet.len())); +} + +#[test] +fn packet_headers_inside_application_instructions_are_text() { + let packet = PACKET.replace("", ""); + assert_eq!(xmp::find_packet(packet.as_bytes()).map(|span| (span.start, span.end)), Some((0, packet.len()))); + assert!(xmp::parse(&packet, &mut Registry::default()).is_ok()); +} + +#[test] +fn packet_headers_inside_the_xml_root_are_instructions() { + let header = ""; + let packet = PACKET.replace("", &format!("{header}")); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); + assert!(xmp::parse(&packet, &mut Registry::default()).is_ok()); +} + +#[test] +fn binary_prefix_with_an_unclosed_instruction_does_not_hide_a_packet() { + let packet = format!("binary\0\xff"), ("")] { + let mut packet = b"\xff".to_vec(); + packet.extend_from_slice(open.as_bytes()); + packet.extend_from_slice(PACKET.as_bytes()); + packet.extend_from_slice(close.as_bytes()); + packet.extend_from_slice(b""); + let offset = packet.len(); + packet.extend_from_slice(PACKET.as_bytes()); + let span = xmp::find_packet(&packet).unwrap(); + assert_eq!((span.start, span.end), (offset, packet.len()), "{open}"); + } +} + +#[test] +fn an_abandoned_xml_root_does_not_hide_the_next_packet() { + let header = ""; + for root in ["", "", ""] { + let prefix = format!("{header}{root}{}", "") + .replace("", ""); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); +} + +#[test] +fn non_xml_whitespace_before_an_array_is_preserved() { + let packet = PACKET.replace("image/svg+xml", "\u{a0}value"); + let mut registry = Registry::default(); + let meta = xmp::parse(&packet, &mut registry).unwrap(); + assert!(xmp::serialize(&meta, ®istry, true).unwrap().contains('\u{a0}')); +} + fn with_packet(src: &str) -> String { format!("var m = new XMPMeta({:?});\n{src}", PACKET) } @@ -533,6 +716,33 @@ fn an_external_object_install_can_retry_after_a_heap_limit() { assert!(failures > 0 && successes > 0, "failures {failures}, successes {successes}"); } +#[test] +fn es5_external_install_reserves_every_published_member() { + let mut successes = 0; + let mut failures = 0; + for kib in 0..=128 { + let mut realm = Realm::with_options(crate::Options { es2015: false, ..crate::Options::default() }, Limits::default()); + realm.run("0").unwrap(); + let baseline = realm.interp().settled_heap_bytes(); + let limit = baseline + (kib << 10); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + match realm.define_external_object() { + Ok(()) => { + successes += 1; + let retained = realm.interp().settled_heap_bytes(); + assert!(retained <= limit, "installation retained {retained} bytes with a {limit}-byte limit"); + } + Err(error) => { + failures += 1; + assert_eq!(error.kind, RunErrorKind::Limit(LimitKind::Heap)); + realm.set_limits(Limits::default()); + realm.define_external_object().unwrap(); + } + } + } + assert!(successes > 0 && failures > 0); +} + #[test] fn retained_xmp_namespaces_count_toward_the_heap_limit() { let mut realm = realm(); diff --git a/docs/mcp.md b/docs/mcp.md index 109e02ffa9..32bbb20a81 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3432,7 +3432,8 @@ rules for these objects: 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. On Unix the replacement keeps the file's permission bits, group + 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 @@ -3449,9 +3450,15 @@ rules for these objects: 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; a value is counted as deep as `serialize()` would write it, under `x:xmpmeta`, `rdf:RDF` and + 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 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, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e31f0ec30c..d79b3bbd44 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -38,6 +38,8 @@ When startup scripts precede a chosen script, its source must compile before sta 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`. @@ -93,7 +95,7 @@ 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. 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. +`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. 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. ### Feature revisions From c6f59b3594c2f6f391a54937ba29c3723b4167c5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 19:28:52 -0800 Subject: [PATCH 20/21] Reject unsupported inherited RDF language without losing qualifiers --- crates/js/src/xmp.rs | 18 +++++++++++++----- crates/js/src/xmp_tests.rs | 14 ++++++++++++++ docs/mcp.md | 2 ++ docs/target-app-parity.md | 2 +- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 758b027bdd..a97418ccbd 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -110,7 +110,7 @@ pub(crate) enum XmpError { BadName, /// Text with a character XML does not allow. BadText, - /// A path form not read yet: a structure field, a qualifier or a selector. + /// An unsupported packet language, structure field, qualifier or selector form. NotYet, /// The metadata a packet gives is larger than the budget [`parse_within`] was given. Heap, @@ -500,14 +500,15 @@ fn attrs(el: &El) -> Vec<(&str, &str)> { } /// The `rdf:RDF` element at or below `el`, with `scope` holding the bindings in scope there. -fn find_rdf<'a>(el: &'a El, scope: &mut Scope) -> Option<&'a El> { +fn find_rdf<'a>(el: &'a El, scope: &mut Scope, language: Option<&'a str>) -> Option<(&'a El, Option<&'a str>)> { let mark = scope.len(); push_decls(el, scope); + let language = inherited_language(el, scope, language); if is_named(&el.name, scope, true, RDF, "RDF") { - return Some(el); + return Some((el, language)); } for c in el.elements() { - if let Some(found) = find_rdf(c, scope) { + if let Some(found) = find_rdf(c, scope, language) { return Some(found); } } @@ -515,6 +516,10 @@ fn find_rdf<'a>(el: &'a El, scope: &mut Scope) -> Option<&'a El> { None } +fn inherited_language<'a>(el: &'a El, scope: &Scope, language: Option<&'a str>) -> Option<&'a str> { + attrs(el).into_iter().find(|(name, _)| is_named(name, scope, false, XML, "lang")).map(|(_, value)| value).or(language) +} + /// Tests: reads the packet `text` with no budget ([`parse_within`]). #[cfg(test)] pub(crate) fn parse(text: &str, registry: &mut Registry) -> Result { @@ -601,7 +606,7 @@ fn parse_into(text: &str, registry: &mut Registry, budget: usize, retain_fragmen return Err(XmpError::Malformed); } let mut scope = Scope::new(); - let rdf = find_rdf(&root, &mut scope).ok_or(XmpError::Malformed)?; + let (rdf, language) = find_rdf(&root, &mut scope, None).ok_or(XmpError::Malformed)?; let mut explicit_subject = None; // Text beside the descriptions or their properties is not RDF. if rdf.children.iter().any(is_stray_text) { @@ -614,6 +619,9 @@ fn parse_into(text: &str, registry: &mut Registry, budget: usize, retain_fragmen if !is_named(&d.name, &scope, true, RDF, "Description") || d.children.iter().any(is_stray_text) { return Err(XmpError::Malformed); } + if inherited_language(d, &scope, language).is_some_and(|language| !language.is_empty()) { + return Err(XmpError::NotYet); + } for (k, v) in attrs(d) { let Some((ns, local)) = resolve(k, &scope, false) else { return Err(XmpError::Malformed) }; if ns == RDF { diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index af5b090b31..97b04deb60 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -47,6 +47,20 @@ const PACKET: &str = r#" "#; +#[test] +fn inherited_description_language_is_not_silently_discarded() { + let packet = r#"Hello"#; + assert!(matches!(xmp::parse(packet, &mut Registry::default()), Err(XmpError::NotYet))); + let outer = packet.replace("xml:lang=\"en\"", "").replace("", ""); + let mut registry = Registry::default(); + let meta = xmp::parse(&explicit, &mut registry).unwrap(); + assert!(xmp::serialize(&meta, ®istry, false).unwrap().contains("xml:lang=\"en\"")); +} + #[test] fn rdf_qualified_names_validate_both_parts() { let packet = PACKET.replace("ex:a>", "ex:a:b>"); diff --git a/docs/mcp.md b/docs/mcp.md index 32bbb20a81..bd98f6d194 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3458,6 +3458,8 @@ rules for these objects: 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d79b3bbd44..64a976529d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -95,7 +95,7 @@ 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. 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. +`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. ### Feature revisions From 47dcb19bca3662f1e963c9bd9a7f3830da2c7d63 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 20:43:11 -0800 Subject: [PATCH 21/21] Preserve localized XMP properties and optional argument positions --- crates/js/src/xmp_classes.rs | 58 +++++++++++++++++++++++++++++------- crates/js/src/xmp_tests.rs | 39 ++++++++++++++++++++++-- docs/mcp.md | 6 +++- docs/target-app-parity.md | 2 ++ 4 files changed, 92 insertions(+), 13 deletions(-) diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index e8b733a864..da42e28832 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -736,13 +736,16 @@ fn append_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> Js let what = "XMPMeta.appendArrayItem"; let o = this_meta(i, &this, what)?; let Target { ns, name, .. } = array_target(i, args, what)?; - // `itemOptions` may be left out: a string or `null` third argument is the item's value. - let (value, array_options) = match arg(args, 2) { - Value::Number(_) => { - item_options(i, &arg(args, 2), what)?; - (arg(args, 3), arg(args, 4)) - } - v => (v, arg(args, 3)), + // Full calls keep their argument positions. Short calls can omit `itemOptions`. + let third = arg(args, 2); + let positional = args.len() >= 5 + || matches!(&third, Value::Number(_) | Value::Undefined) + || (matches!(&third, Value::Null) && matches!(arg(args, 3), Value::String(_))); + let (value, array_options) = if positional { + item_options(i, &third, what)?; + (arg(args, 3), arg(args, 4)) + } else { + (third, arg(args, 3)) }; let array_options = flags(i, &array_options, what)?; only(i, array_options, xmp::PROP_IS_ARRAY | xmp::ARRAY_IS_ORDERED | xmp::ARRAY_IS_ALTERNATIVE, what)?; @@ -829,16 +832,22 @@ fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let Target { ns, name, .. } = array_target(i, args, what)?; let generic = lang(i, &arg(args, 2), what)?; let specific = lang(i, &arg(args, 3), what)?; - let Some((at, _, _)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + let Some((at, _, len)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + spend(i, len.saturating_mul(std::mem::size_of::()).saturating_mul(6))?; + let language_bytes = match &meta_of(i, o)?.props[at].value { + xmp::Value::Array { items, .. } => items.iter().fold(0usize, |bytes, item| bytes.saturating_add(item.lang.as_ref().map_or(0, String::len))), + _ => 0, + }; + spend(i, language_bytes.saturating_mul(3))?; if !is_alt_text(i, o, at)? { return Err(not_alt_text(i, what, &name)); } let found = match &meta_of(i, o)?.props[at].value { - xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific).map(|i| i.text.clone()), + xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific).cloned(), _ => None, }; match found { - Some(t) => string(i, &t), + Some(item) => property(i, "", "", Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")), None => Ok(Value::Undefined), } } @@ -1468,6 +1477,35 @@ mod namespace_heap_tests { } } + #[test] + fn localized_text_lookup_charges_for_language_scans() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let value = new_meta( + &mut interp, + Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Alt, items: vec![Item { text: "text".into(), lang: Some("en-US".into()) }; 10_000] }, + }], + ..Meta::default() + }, + ) + .unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + let args = [Value::str(xmp::DC), Value::str("items"), Value::str("fr"), Value::str("fr-FR")]; + interp.fuel = 1_000; + let result = get_localized_text(interp, value.clone(), &args, false); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}"); + interp.fuel = 1_000_000; + assert!(get_localized_text(interp, value.clone(), &args, false).is_ok()); + Ok(()) + }) + .unwrap(); + } + #[test] fn inserting_array_items_charges_for_shifted_items() { let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 97b04deb60..5aee375abd 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -61,6 +61,21 @@ fn inherited_description_language_is_not_silently_discarded() { assert!(xmp::serialize(&meta, ®istry, false).unwrap().contains("xml:lang=\"en\"")); } +#[test] +fn localized_text_returns_the_selected_property_and_language() { + let specific = with_packet( + "var value = m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'fr-FR'); [typeof value, value.value, value.locale, value.options, value.namespace, value.path, String(value)].join('|')", + ); + assert_eq!(string(&specific), "object|Bonjour|fr-FR|80|||Bonjour"); + let fallback = with_packet("var value = m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'de-DE'); [value.value, value.locale].join('|')"); + assert_eq!(string(&fallback), "Hello|x-default"); + truth(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'missing', null, 'fr-FR') === undefined")); + truth(&with_packet( + "m.appendArrayItem(XMPConst.NS_DC, 'emptyAlt', 0, 'value', XMPConst.PROP_IS_ARRAY | XMPConst.ARRAY_IS_ORDERED | XMPConst.ARRAY_IS_ALTERNATIVE); + m.deleteArrayItem(XMPConst.NS_DC, 'emptyAlt', 1); m.doesPropertyExist(XMPConst.NS_DC, 'emptyAlt') && m.getLocalizedText(XMPConst.NS_DC, 'emptyAlt', null, 'fr-FR') === undefined", + )); +} + #[test] fn rdf_qualified_names_validate_both_parts() { let packet = PACKET.replace("ex:a>", "ex:a:b>"); @@ -262,8 +277,8 @@ fn only_the_xmp_library_loads() { fn a_packet_reads_into_properties() { assert_eq!(string(&with_packet("m.getProperty(XMPConst.NS_DC, 'format').value")), "image/svg+xml"); assert_eq!(string(&with_packet("String(m.getProperty(XMPConst.NS_XMP, 'xmp:CreatorTool'))")), "Tool & Co"); - assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'fr-FR')")), "Bonjour"); - assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'de-DE')")), "Hello"); + assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'fr-FR').value")), "Bonjour"); + assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'de-DE').value")), "Hello"); assert_eq!(string(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM).value")), "two"); assert_eq!(run(&with_packet("m.countArrayItems(XMPConst.NS_DC, 'subject')")), JsValue::Number(2.0)); assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'title').options")), JsValue::Number(f64::from(0x200 | 0x400 | 0x800 | 0x1000))); @@ -316,6 +331,26 @@ fn properties_arrays_and_namespaces_round_trip() { assert_eq!(string("XMPMeta.getNamespaceURI('dc:')"), "http://purl.org/dc/elements/1.1/"); } +#[test] +fn append_array_item_preserves_explicit_optional_slots() { + assert_eq!( + string( + "var out = []; var ns = XMPConst.NS_DC; + function append(option, full) { var m = new XMPMeta(); try { + if (full) m.appendArrayItem(ns, 'items', option, 'value', XMPConst.PROP_IS_ARRAY); + else { m.appendArrayItem(ns, 'items', 'first', XMPConst.PROP_IS_ARRAY); + m.appendArrayItem(ns, 'items', option, 'value'); m.deleteArrayItem(ns, 'items', 1); } + out.push(m.getArrayItem(ns, 'items', 1).value); + } catch (e) { out.push('error'); } } + append(undefined, true); append(null, true); append(undefined, false); append(null, false); + var m = new XMPMeta(); m.appendArrayItem(ns, 'empty', null, XMPConst.PROP_IS_ARRAY); + m.appendArrayItem(ns, 'short', 'short', XMPConst.PROP_IS_ARRAY); + out.push(m.getArrayItem(ns, 'empty', 1).value, m.getArrayItem(ns, 'short', 1).value); out.join('|')" + ), + "value|value|value|value||short" + ); +} + #[test] fn array_last_insertion_precedes_the_last_existing_item() { assert_eq!( diff --git a/docs/mcp.md b/docs/mcp.md index bd98f6d194..3531e40e35 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3410,7 +3410,11 @@ rules for these objects: `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`. A + 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 64a976529d..08f3b777cb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -97,6 +97,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard `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 |