File Info: metadata templates save, import and list from the File Info menu

File Info's menu saves the fields as an XMP metadata template (into the
Metadata Templates folder next to the preferences, or any file), imports
one with a choice of three merges, lists the saved templates and opens
the folder. The import is one undo step and records nothing when no
field changes.

- file.info.saveTemplate writes the title (when it is not the
  document's name), author, author title, description, keywords,
  rating, copyright status, notice and URL that have a value.
- file.info.applyTemplate reads a file, a saved template or XMP text
  (at most 8 MB) and merges it: replace clears the fields first, keep
  takes each field the template has, append adds keywords and fills
  only empty fields. apply: false returns the merged fields without
  changing the document.
- file.info.templates lists the folder's .xmp files.
- A PDF or .ai also opens with the rating and author title its XMP
  packet gives.

Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo
2026-11-15 11:05:55 -08:00
parent 0c1ac3bdc5
commit a670cd1102
43 changed files with 1273 additions and 18 deletions
+27
View File
@@ -269,6 +269,33 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
super::fileinfo::file_info
),
cmd!(
"file.info.saveTemplate",
"Save Metadata Template…",
[],
None,
"{name?: save into the metadata templates folder as <name>.xmp (a name with characters file systems reject, a dot at either end, or a device name is an error (spaces at either end are dropped); the same name replaces that template), path?: save to this file instead (not both), fields?: {File Info fields as file.info takes them} save these instead of the document's (default: the document's File Info)} write the File Info as an XMP metadata template: title (only one of its own, not Untitled-N), author, authorTitle, description, keywords, rating (1–5), copyrightStatus, copyrightNotice and copyrightUrl, each where it has a value; the dates are left out → {name, path} (with name), {path} (with path), or {data: the XMP text} with neither",
has_doc,
super::fileinfo::save_template
),
cmd!(
"file.info.applyTemplate",
"Import Metadata Template…",
[],
None,
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
has_doc,
super::fileinfo::apply_template
),
cmd!(
query "file.info.templates",
"Metadata Templates",
[],
None,
"{create?: false (true: make the folder when it is missing)} the metadata templates in the metadata templates folder next to the preferences, sorted by name, at most 1,000 → {templates: [{name, file: the file name, path}], folder?: the folder (left out for a request that may not read it, in runs without preferences and on the web, where the list is empty)}",
super::always,
super::fileinfo::templates
),
]
}
+318 -13
View File
@@ -3,14 +3,28 @@
//! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]),
//! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or
//! `.ai` opens with the File Info it gives ([`read_pdf`]).
//!
//! Metadata templates: `file.info.saveTemplate` writes the File Info as an XMP file
//! ([`vectorcraft_pdf::metadata_template`]), `file.info.applyTemplate` merges one into the File
//! Info, and `file.info.templates` lists those in the metadata templates folder.
use serde_json::{Map, Value, json};
use vectorcraft_doc::metadata::{MAX_RATING, iso8601};
use vectorcraft_doc::{ColorMode, CopyrightStatus, DocMetadata, Document};
use super::{Result, Session, bad};
use super::{Result, Session, bad, switch_or, text_param};
const C: &str = "file.info";
const SAVE: &str = "file.info.saveTemplate";
const APPLY: &str = "file.info.applyTemplate";
const LIST: &str = "file.info.templates";
/// The extension of a metadata template file.
const TEMPLATE_EXT: &str = "xmp";
/// The most templates `file.info.templates` lists.
const MAX_LISTED: usize = 1000;
/// The largest metadata template `file.info.saveTemplate` writes and `file.info.applyTemplate`
/// reads, in bytes (8 MB). The largest template File Info's fields can give is under 4 MB.
const MAX_TEMPLATE_FILE: usize = vectorcraft_pdf::MAX_TEMPLATE_BYTES;
/// Longest text field, in characters.
const MAX_TEXT: usize = 65_536;
/// Longest keyword, in characters.
@@ -21,9 +35,13 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb
/// What `file.info` reports (and takes back).
pub(crate) fn info_json(d: &Document) -> Value {
let m = &d.metadata;
info_json_with(d, d.info_title(), &d.metadata)
}
/// [`info_json`] with the title `title` and the metadata `m` in place of the document's.
fn info_json_with(d: &Document, title: &str, m: &DocMetadata) -> Value {
json!({
"title": d.info_title(),
"title": title,
"author": m.author,
"authorTitle": m.author_title,
"description": m.description,
@@ -48,11 +66,25 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
Value::Object(o) => o,
_ => return Err(bad(C, "params must be an object")),
};
let (title, m) = edited(s, Some(o))?;
commit(s, title, m)?;
Ok(info_json(&s.doc()?.doc))
}
/// The active document's File Info title and metadata with `fields` (as `file.info` takes them)
/// applied.
fn edited(s: &Session, fields: Option<&Map<String, Value>>) -> Result<(String, DocMetadata)> {
let d = &s.doc()?.doc;
let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone());
for (k, v) in o {
for (k, v) in fields.into_iter().flatten() {
apply(&mut title, &mut m, k, v)?;
}
Ok((title, m))
}
/// Make `title` and `m` the active document's File Info in one undo step; nothing is recorded when
/// they are what it has. Whether anything changed.
fn commit(s: &mut Session, title: String, mut m: DocMetadata) -> Result<bool> {
let d = &s.doc()?.doc;
// A title File Info changes becomes the document's own, as it always has (the tab and Save As
// offer it where the document has no file), and replaces the one its file gave.
@@ -60,16 +92,287 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
if retitled {
m.title = None;
}
if retitled || m != d.metadata {
s.edit("File Info", |d, _| {
if retitled {
d.title = title;
}
d.metadata = m;
Ok(())
})?;
if !retitled && m == d.metadata {
return Ok(false);
}
Ok(info_json(&s.doc()?.doc))
s.edit("File Info", |d, _| {
if retitled {
d.title = title;
}
d.metadata = m;
Ok(())
})?;
Ok(true)
}
/// The optional object `p` gives for `key`.
fn fields_param<'a>(p: &'a Value, key: &str, c: &str) -> Result<Option<&'a Map<String, Value>>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::Object(o)) => Ok(Some(o)),
Some(_) => Err(bad(c, format!("`{key}` must be an object"))),
}
}
impl Session {
/// Have `file.info.saveTemplate`, `file.info.applyTemplate` and `file.info.templates` keep the
/// metadata templates in the folder `dir`, which a save makes when it is missing.
pub fn attach_metadata_templates_dir(&mut self, dir: std::path::PathBuf) {
self.metadata_templates_dir = Some(dir);
}
/// The metadata templates folder ([`Session::attach_metadata_templates_dir`]); none on the web,
/// which has no folders.
pub fn metadata_templates_dir(&self) -> Option<&std::path::Path> {
self.metadata_templates_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
}
}
/// The metadata template of the File Info `title` and `m`: each field that has a value, the title
/// only where it is one of its own ([`super::fileio::is_own_title`]), the rating only from 1 up.
fn template_of(title: &str, m: &DocMetadata) -> vectorcraft_pdf::FileInfo {
let text = |s: &str| (!s.trim().is_empty()).then(|| s.to_string());
vectorcraft_pdf::FileInfo {
title: super::fileio::is_own_title(title).then(|| title.to_string()),
author: text(&m.author),
author_title: text(&m.author_title),
description: text(&m.description),
keywords: (!m.keywords.is_empty()).then(|| m.keywords.clone()),
rating: (m.rating > 0).then_some(m.rating),
copyright_notice: text(&m.copyright_notice),
copyright_url: text(&m.copyright_url),
copyrighted: match m.copyright_status {
CopyrightStatus::Copyrighted => Some(true),
CopyrightStatus::PublicDomain => Some(false),
CopyrightStatus::Unknown => None,
},
..Default::default()
}
}
/// The path of the template `name` in the folder `dir`: `name` made a safe file name, with
/// [`TEMPLATE_EXT`].
fn template_path(dir: &std::path::Path, name: &str, c: &str) -> Result<String> {
let name = name.trim();
if name.is_empty() {
return Err(bad(c, "the template name can't be empty"));
}
Ok(dir.join(super::swatchlib::library_file_name(name, TEMPLATE_EXT)).to_string_lossy().into_owned())
}
/// The error for a template over [`MAX_TEMPLATE_FILE`].
fn too_big(c: &str) -> crate::EngineError {
bad(c, format!("the file is larger than {} MB", MAX_TEMPLATE_FILE >> 20))
}
/// File Info › Save Metadata Template: `file.info.saveTemplate {name?, path?, fields?}`.
pub(crate) fn save_template(s: &mut Session, p: &Value) -> Result<Value> {
let name = text_param(p, "name", SAVE)?;
let path = text_param(p, "path", SAVE)?;
let (title, m) = edited(s, fields_param(p, "fields", SAVE)?)?;
let xmp = vectorcraft_pdf::metadata_template(&template_of(&title, &m));
if xmp.len() > MAX_TEMPLATE_FILE {
return Err(too_big(SAVE));
}
match (name, path) {
(Some(_), Some(_)) => Err(bad(SAVE, "give `name` or `path`, not both")),
(Some(name), None) => {
let dir = s.metadata_templates_dir().ok_or_else(|| bad(SAVE, "no metadata templates folder here"))?.to_path_buf();
let path = template_path(&dir, name, SAVE)?;
// The name is the file name as it is, so two names never share a file.
let listed = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned());
if listed.as_deref() != Some(name.trim()) {
return Err(bad(SAVE, "the template name isn't usable as a file name"));
}
// Only a file in the folder itself is replaced: a link there is not followed.
if std::fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file()) {
return Err(crate::EngineError::Other(format!("{path}: not a file")));
}
let dir = dir.to_string_lossy().into_owned();
// The app's own folder, under a name checked above: no root applies.
crate::file_access::unconfined(|| super::fileio::create_dir(&dir).and_then(|()| super::fileio::write_file(&path, xmp.as_bytes())))?;
Ok(json!({ "name": listed, "path": super::fileio::shown_path(&path) }))
}
(None, Some(path)) => {
super::fileio::write_file(path, xmp.as_bytes())?;
Ok(json!({ "path": path }))
}
(None, None) => Ok(json!({ "data": xmp })),
}
}
/// How `file.info.applyTemplate` merges a template's fields into the File Info.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Merge {
/// Clear the fields a template can hold, then take the template's.
Replace,
/// Keep the fields, and take each one the template gives.
Keep,
/// Keep the fields: add the template's keywords, and take its other fields only where the File
/// Info has none.
Append,
}
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
let mode = match text_param(p, "mode", APPLY)? {
Some("replace") => Merge::Replace,
Some("keep") => Merge::Keep,
Some("append") => Merge::Append,
_ => return Err(bad(APPLY, "mode must be replace, keep or append")),
};
let apply = switch_or(p, "apply", true, APPLY)?;
let base = fields_param(p, "base", APPLY)?;
let bytes = template_bytes(s, p)?;
let t = vectorcraft_pdf::read_template(&bytes).ok_or_else(|| bad(APPLY, "the file is not an XMP metadata template"))?;
let (mut title, mut m) = edited(s, base)?;
merge(&mut title, &mut m, t, mode);
if !apply {
return Ok(info_json_with(&s.doc()?.doc, &title, &m));
}
let changed = commit(s, title, m)?;
let mut out = info_json(&s.doc()?.doc);
out["changed"] = json!(changed);
Ok(out)
}
/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or
/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long.
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
// At most one byte past the limit is read, so a huge file is never read whole.
let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1);
let bytes = match given {
[Some(path), None, None] => read(path)?,
[None, Some(name), None] => {
let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?;
let mut path = template_path(dir, name, APPLY)?;
// A template `file.info.templates` lists: by its `file` first, then by its `name` with
// the extension in lowercase, then in other letter case. Only files in the folder itself
// are listed: a link there is not followed.
let name = name.trim();
let own = format!("{name}.{TEMPLATE_EXT}");
let listed = template_files(dir)
.filter(|f| f == name || f.rsplit_once('.').is_some_and(|(stem, _)| stem == name))
.min_by_key(|f| (f != name, *f != own));
if let Some(file) = listed {
path = dir.join(file).to_string_lossy().into_owned();
}
let plain_file = |path: &str| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file());
if std::fs::symlink_metadata(&path).is_ok() && !plain_file(&path) {
return Err(crate::EngineError::Other(format!("{path}: not a file")));
}
// The app's own folder: no root applies.
crate::file_access::unconfined(|| read(&path))?
}
[None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
[None, None, Some(data)] => data.as_bytes().to_vec(),
_ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")),
};
if bytes.len() > MAX_TEMPLATE_FILE {
return Err(too_big(APPLY));
}
Ok(bytes)
}
/// Merge the template `t` into the File Info `title` and `m` as `mode` says. Each field goes in as
/// `file.info` would take it; a value it would refuse is left out.
fn merge(title: &mut String, m: &mut DocMetadata, t: vectorcraft_pdf::FileInfo, mode: Merge) {
if mode == Merge::Replace {
// The title is never cleared: a document always has one.
m.author.clear();
m.author_title.clear();
m.description.clear();
m.keywords.clear();
m.rating = 0;
m.copyright_status = CopyrightStatus::Unknown;
m.copyright_notice.clear();
m.copyright_url.clear();
}
let status = t.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
let fields = [
("title", t.title.map(Value::from)),
("author", t.author.map(Value::from)),
("authorTitle", t.author_title.map(Value::from)),
("description", t.description.map(Value::from)),
("keywords", t.keywords.map(Value::from)),
("rating", t.rating.map(Value::from)),
("copyrightStatus", status.map(|s| Value::from(s.id()))),
("copyrightNotice", t.copyright_notice.map(Value::from)),
("copyrightUrl", t.copyright_url.map(Value::from)),
];
for (k, v) in fields {
let Some(mut v) = v else { continue };
if mode == Merge::Append {
let empty = match k {
"title" => !super::fileio::is_own_title(title),
"author" => m.author.is_empty(),
"authorTitle" => m.author_title.is_empty(),
"description" => m.description.is_empty(),
"rating" => m.rating == 0,
"copyrightStatus" => m.copyright_status == CopyrightStatus::Unknown,
"copyrightNotice" => m.copyright_notice.is_empty(),
"copyrightUrl" => m.copyright_url.is_empty(),
_ => true,
};
if !empty {
continue;
}
if k == "keywords" {
let mut all: Vec<Value> = m.keywords.iter().cloned().map(Value::from).collect();
all.extend(v.as_array().cloned().unwrap_or_default());
v = Value::from(all);
}
}
// `apply` changes the field only when it takes the value.
let _ = apply(title, m, k, &v);
}
}
/// The file names of the templates in the folder `dir`: its files with a name before the
/// [`TEMPLATE_EXT`] extension, in any case. The app's own folder, read directly; a folder not made
/// yet holds none.
fn template_files(dir: &std::path::Path) -> impl Iterator<Item = String> {
std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|file| file.rsplit_once('.').is_some_and(|(stem, ext)| ext.eq_ignore_ascii_case(TEMPLATE_EXT) && !stem.is_empty()))
}
/// `file.info.templates {create?}`: the metadata templates in the folder, by name.
pub(crate) fn templates(s: &mut Session, p: &Value) -> Result<Value> {
let create = switch_or(p, "create", false, LIST)?;
let Some(dir) = s.metadata_templates_dir().map(|d| d.to_string_lossy().into_owned()) else {
return Ok(json!({ "templates": [] }));
};
if create {
// The app's own folder: no root applies.
crate::file_access::unconfined(|| super::fileio::create_dir(&dir))?;
}
// The first [`MAX_LISTED`] by name, with no more than that many held at once.
let mut files = std::collections::BTreeSet::new();
for file in template_files(std::path::Path::new(&dir)) {
files.insert(file);
if files.len() > MAX_LISTED {
files.pop_last();
}
}
let list: Vec<Value> = files
.iter()
.filter_map(|file| {
let (stem, _) = file.rsplit_once('.')?;
let path = std::path::Path::new(&dir).join(file).to_string_lossy().into_owned();
Some(json!({ "name": stem, "file": file, "path": super::fileio::shown_path(&path) }))
})
.collect();
let mut out = json!({ "templates": list });
if super::fileio::shown_path(&dir) == dir.as_str() {
out["folder"] = json!(dir);
}
Ok(out)
}
/// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each
@@ -79,8 +382,10 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
let fields = [
("author", f.author.map(Value::from)),
("authorTitle", f.author_title.map(Value::from)),
("description", f.description.map(Value::from)),
("keywords", f.keywords.map(Value::from)),
("rating", f.rating.map(Value::from)),
("copyrightStatus", status.map(|s| Value::from(s.id()))),
("copyrightNotice", f.copyright_notice.map(Value::from)),
("copyrightUrl", f.copyright_url.map(Value::from)),
+3
View File
@@ -178,6 +178,9 @@ pub struct Session {
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
/// ([`Session::attach_scripts_dir`]).
scripts_dir: Option<std::path::PathBuf>,
/// The folder of File Info's metadata templates; `None`: no folder
/// ([`Session::attach_metadata_templates_dir`]).
metadata_templates_dir: Option<std::path::PathBuf>,
/// The folder of the New Document profiles `file.new` starts documents from; `None`: none,
/// every document starts with the defaults ([`Session::attach_new_doc_profiles`]).
new_doc_profile_dir: Option<std::path::PathBuf>,
+1
View File
@@ -93,6 +93,7 @@ impl Session {
color_settings_file: None,
plugin_dir: None,
scripts_dir: None,
metadata_templates_dir: None,
new_doc_profile_dir: None,
plugin_output: None,
plugin_install_approval: None,
+221
View File
@@ -559,3 +559,224 @@ fn an_untitled_document_saved_to_a_file_exports_titled_after_it() {
}
let _ = std::fs::remove_dir_all(dir);
}
/// A session whose metadata templates folder is `dir/Metadata Templates`, with a document titled
/// Poster.
fn template_session(dir: &std::path::Path) -> Session {
let mut s = session();
s.attach_metadata_templates_dir(dir.join("Metadata Templates"));
s
}
#[test]
fn a_saved_metadata_template_is_listed_and_applies_to_another_document() {
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template");
let mut s = template_session(&dir);
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]), "no folder yet");
s.execute("file.info", &info()).unwrap();
let r = s.execute("file.info.saveTemplate", &json!({"name": " Studio "})).unwrap();
assert_eq!(r["name"], "Studio");
let path = dir.join("Metadata Templates").join("Studio.xmp");
assert!(path.is_file(), "saved into the folder: {r}");
let listed = s.execute("file.info.templates", &json!({})).unwrap();
assert_eq!(listed["templates"][0]["name"], "Studio");
assert_eq!(listed["templates"].as_array().map(Vec::len), Some(1));
// A name that isn't a usable file name as it is is refused, so `a/b` and `a?b` never share a file.
for name in ["a/b", "a?b", "CON", "Studio.", "x\u{1}"] {
assert!(s.execute("file.info.saveTemplate", &json!({"name": name})).is_err(), "{name}");
}
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"].as_array().map(Vec::len), Some(1));
// Saving is not an edit of the document.
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
// Into a new document, by name, in one undo step.
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "Studio", "mode": "keep"})).unwrap();
assert_eq!(r["changed"], true);
let m = &s.doc().unwrap().doc.metadata;
assert_eq!((m.author.as_str(), m.author_title.as_str(), m.rating), ("Ada Lovelace", "Designer", 4));
assert_eq!(m.keywords, ["fair", "Poster", "print"]);
assert_eq!((m.copyright_status, m.copyright_notice.as_str()), (CopyrightStatus::Copyrighted, "(c) 2026 Ada"));
assert_eq!(m.description, "A poster\nfor the fair");
assert_eq!(r["title"], "Poster", "the template carries the title of its own");
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
// Applied again, nothing changes and nothing is recorded.
let r = s.execute("file.info.applyTemplate", &json!({"path": path.to_str().unwrap(), "mode": "keep"})).unwrap();
assert_eq!(r["changed"], false);
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.metadata.author, "");
// The same name replaces the template.
s.execute("file.info.saveTemplate", &json!({"name": "Studio", "fields": {"author": "Grace"}})).unwrap();
let back = vectorcraft_pdf::read_template(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(back.author.as_deref(), Some("Grace"));
assert_eq!(back.title, None, "an Untitled-N title is not written");
}
#[test]
fn a_metadata_template_merges_in_three_modes() {
let mut s = session();
s.execute("file.info", &json!({"author": "Ada", "keywords": ["fair"], "rating": 2, "copyrightUrl": "https://example.com/a"})).unwrap();
let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo {
author: Some("Grace".into()),
description: Some("From the template".into()),
keywords: Some(vec!["print".into(), "Fair".into()]),
rating: Some(5),
copyrighted: Some(false),
..Default::default()
});
let merged =
|s: &mut Session, mode: &str| s.execute("file.info.applyTemplate", &json!({"data": template, "mode": mode, "apply": false})).unwrap();
// Clear and replace: the fields the template lacks are cleared; the title stays.
let r = merged(&mut s, "replace");
assert_eq!((r["author"].as_str(), r["description"].as_str(), r["rating"].as_u64()), (Some("Grace"), Some("From the template"), Some(5)));
assert_eq!(
(r["keywords"].clone(), r["copyrightUrl"].as_str(), r["copyrightStatus"].as_str()),
(json!(["print", "Fair"]), Some(""), Some("publicDomain"))
);
assert_eq!(r["title"], "Poster");
// Keep and replace: the template's fields replace those it has; the others stay.
let r = merged(&mut s, "keep");
assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["copyrightUrl"].as_str()), (Some("Grace"), Some(5), Some("https://example.com/a")));
assert_eq!(r["keywords"], json!(["print", "Fair"]));
// Keep and append: keywords are added (each once), and only empty fields are filled.
let r = merged(&mut s, "append");
assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["description"].as_str()), (Some("Ada"), Some(2), Some("From the template")));
assert_eq!((r["keywords"].clone(), r["copyrightStatus"].as_str()), (json!(["fair", "print"]), Some("publicDomain")));
// `apply: false` changed nothing; `base` merges into the given fields instead.
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
assert_eq!(s.doc().unwrap().doc.metadata.author, "Ada");
let r = s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "append", "apply": false, "base": {"author": ""}})).unwrap();
assert_eq!(r["author"], "Grace");
// Applied: one undo step.
s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "replace"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), 2);
assert_eq!(s.doc().unwrap().doc.metadata.copyright_url, "");
}
#[test]
fn metadata_template_errors() {
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-errors");
let mut s = template_session(&dir);
let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() });
let not_xmp = dir.join("note.xmp");
std::fs::write(&not_xmp, "<note>not metadata</note>").unwrap();
let big = dir.join("big.xmp");
std::fs::write(&big, vec![b' '; vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1]).unwrap();
let e = s.execute("file.info.applyTemplate", &json!({"path": big.to_str().unwrap(), "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
for bad in [
json!({"data": xmp, "mode": "merge"}),
json!({"data": xmp}),
json!({"data": xmp, "mode": 3}),
json!({"mode": "keep"}),
json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}),
json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"path": big.to_str().unwrap(), "mode": "keep"}),
json!({"name": "missing", "mode": "keep"}),
json!({"data": "Ada Lovelace", "mode": "keep"}),
json!({"data": xmp, "mode": "keep", "apply": "yes"}),
json!({"data": xmp, "mode": "keep", "base": [1]}),
json!({"data": xmp, "mode": "keep", "base": {"rating": 9}}),
] {
assert!(s.execute("file.info.applyTemplate", &bad).is_err(), "{bad}");
}
for bad in [json!({"name": "a", "path": "b.xmp"}), json!({"name": " "}), json!({"fields": {"rating": 9}}), json!({"fields": "x"})] {
assert!(s.execute("file.info.saveTemplate", &bad).is_err(), "{bad}");
}
assert_eq!(s.doc().unwrap().history.undo.len(), 0);
assert!(!dir.join("Metadata Templates").exists(), "no failed save made the folder");
// A link in the folder is not followed, by its name or its file name.
#[cfg(unix)]
{
let outside = dir.join("outside.xmp");
std::fs::write(&outside, &xmp).unwrap();
std::fs::create_dir_all(dir.join("Metadata Templates")).unwrap();
std::os::unix::fs::symlink(&outside, dir.join("Metadata Templates").join("Linked.xmp")).unwrap();
for name in ["Linked", "Linked.xmp"] {
assert!(s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "keep"})).is_err(), "{name}");
}
let e = s.execute("file.info.applyTemplate", &json!({"name": "Linked", "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("not a file"), "{e}");
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]));
// A save by that name leaves the linked file as it was.
let e = s.execute("file.info.saveTemplate", &json!({"name": "Linked", "fields": {"author": "Grace"}})).unwrap_err();
assert!(e.to_string().contains("not a file"), "{e}");
assert_eq!(std::fs::read_to_string(&outside).unwrap(), xmp);
std::fs::remove_dir_all(dir.join("Metadata Templates")).unwrap();
}
// Without a folder (runs without preferences), a name is an error, the data comes back, and
// the list is empty.
let mut s = session();
assert!(s.execute("file.info.saveTemplate", &json!({"name": "Studio"})).is_err());
let data = s.execute("file.info.saveTemplate", &json!({"fields": {"author": "Ada"}})).unwrap()["data"].as_str().unwrap().to_string();
assert_eq!(vectorcraft_pdf::read_template(data.as_bytes()).unwrap().author.as_deref(), Some("Ada"));
assert_eq!(s.execute("file.info.templates", &json!({"create": true})).unwrap(), json!({"templates": []}));
}
#[test]
fn the_templates_folder_lists_only_xmp_files_and_can_be_made() {
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-list");
let mut s = template_session(&dir);
let r = s.execute("file.info.templates", &json!({"create": true})).unwrap();
let folder = dir.join("Metadata Templates");
assert!(folder.is_dir());
assert_eq!(r["folder"], folder.to_str().unwrap());
for f in ["b.XMP", "a.xmp", "notes.txt", ".xmp"] {
std::fs::write(folder.join(f), "x").unwrap();
}
std::fs::create_dir(folder.join("c.xmp")).unwrap();
// Other files, however many, leave the templates listed.
for i in 0..1000 {
std::fs::write(folder.join(format!("{i:04}.txt")), "").unwrap();
}
let names: Vec<String> = s.execute("file.info.templates", &json!({})).unwrap()["templates"]
.as_array()
.unwrap()
.iter()
.map(|t| t["name"].as_str().unwrap().to_string())
.collect();
assert_eq!(names, ["a", "b"]);
// A listed name opens whatever the case of its extension.
let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() });
std::fs::write(folder.join("b.XMP"), xmp).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "b", "mode": "keep"})).unwrap();
assert_eq!(r["author"], "Grace");
// Its listed file name opens it too.
let listed = s.execute("file.info.templates", &json!({})).unwrap();
assert_eq!(listed["templates"][1]["file"], "b.XMP");
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Grace");
// A listed file name is taken before the name with `.xmp` added.
let ada = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() });
std::fs::write(folder.join("b.XMP.xmp"), ada).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Grace");
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP.xmp", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Ada");
}
#[test]
fn the_largest_file_info_saves_a_template_that_imports() {
let mut s = session();
let text = "\"&".repeat(32_768);
let keywords: Vec<String> = (0..1000).map(|i| format!("{i:04}{}", "\"".repeat(252))).collect();
let fields = json!({
"author": text, "authorTitle": text, "description": text, "copyrightNotice": text,
"copyrightUrl": format!("https://example.com/{}", "&".repeat(2000)), "keywords": keywords, "rating": 5, "copyrightStatus": "copyrighted",
});
let data = s.execute("file.info.saveTemplate", &json!({"fields": fields})).unwrap()["data"].as_str().unwrap().to_string();
assert!(data.len() > 1 << 20, "{} bytes", data.len());
let r = s.execute("file.info.applyTemplate", &json!({"data": data, "mode": "replace"})).unwrap();
assert_eq!((r["author"].as_str(), r["keywords"].as_array().map(Vec::len)), (Some(text.as_str()), Some(1000)));
}
#[test]
fn a_pdf_opens_with_the_rating_and_author_title_its_packet_gives() {
let mut m = DocMetadata::default();
let f = vectorcraft_pdf::FileInfo { author_title: Some("Editor".into()), rating: Some(3), ..Default::default() };
crate::cmd::fileinfo::read_pdf(&mut m, f);
assert_eq!((m.author_title.as_str(), m.rating), ("Editor", 3));
}