diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index b66c15070f..4711232643 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,11 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 69f807f615..8a892a381a 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -535,6 +535,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + // File Info's metadata templates live in their own folder next to the preferences. + prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 11afcfe121..1a33352ffc 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template +/// makes. +pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Metadata Templates") { + session.attach_metadata_templates_dir(dir); + } +} + /// Have File › New start each category's documents from its profile in the `New Document /// Profiles` folder, which `file.newProfiles.edit` makes. pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 3b1e8a7666..9404dcc0c7 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -270,6 +270,33 @@ pub fn specs() -> Vec { has_doc, super::fileinfo::file_info ), + cmd!( + "file.info.saveTemplate", + "Save Metadata Template…", + [], + None, + "{name?: save into the metadata templates folder as .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 + ), ] } diff --git a/crates/engine/src/cmd/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index 6219ebb8f6..b6b1643ea4 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -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::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>) -> 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 { 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,290 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result { 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>> { + 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 { + 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 { + 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 { + 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> { + 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(); + } else if std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy()).as_deref() != Some(name) { + // A name that is not a file name as it is never opens another template. + return Err(bad(APPLY, "the template name isn't usable as a file name")); + } + 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 = 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 { + 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 { + 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 = 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 +385,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)), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index aeb723c963..4f7532108d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -179,6 +179,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, + /// The folder of File Info's metadata templates; `None`: no folder + /// ([`Session::attach_metadata_templates_dir`]). + metadata_templates_dir: Option, /// 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, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index b2836d159c..26403cbbef 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -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, diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index 8a152cd44e..54482826b3 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -582,3 +582,233 @@ 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(¬_xmp, "not metadata").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 = 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"); + // A name that is not a file name never opens the template its safe form names. + let grace = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() }); + std::fs::write(folder.join("a-b.xmp"), grace).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "a-b", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + for name in ["a/b", "a\\b", "a:b"] { + let e = s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "replace", "apply": false})).unwrap_err(); + assert!(e.to_string().contains("isn't usable as a file name"), "{name}: {e}"); + } +} + +#[test] +fn the_largest_file_info_saves_a_template_that_imports() { + let mut s = session(); + let text = "\"&".repeat(32_768); + let keywords: Vec = (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)); +} diff --git a/crates/pdf/src/file_info.rs b/crates/pdf/src/file_info.rs index 930f7e4013..36a4f0ed8e 100644 --- a/crates/pdf/src/file_info.rs +++ b/crates/pdf/src/file_info.rs @@ -2,6 +2,9 @@ //! dictionary (ISO 32000-1 §14.3.3) and the XMP packet of the catalog's metadata stream (§14.3.2, //! ISO 16684-1). Where both give a field, the XMP packet's value is taken; a packet that can't be //! read leaves the information dictionary's values. +//! +//! File › File Info's metadata templates are XMP packets of the same properties: [`metadata_template`] +//! writes one and [`read_template`] reads one back. use craft_pdf::syntax::Pdf; use craft_pdf::syntax::object::{DateTime, Dict, Stream}; @@ -19,8 +22,14 @@ pub(crate) const DC: &str = "http://purl.org/dc/elements/1.1/"; const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace the files use pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use +const PHOTOSHOP: &str = "http://ns.adobe.com/photoshop/1.0/"; // brand-ok: the XMP namespace the files use +const X: &str = "adobe:ns:meta/"; // brand-ok: the XMP namespace the files use -const XMP_NAMESPACES: Canonical<'static> = Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF)]); +/// The longest metadata template [`read_template`] reads, in bytes. +pub const MAX_TEMPLATE_BYTES: usize = MAX_XMP; + +const XMP_NAMESPACES: Canonical<'static> = + Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF), ("photoshop", PHOTOSHOP)]); // brand-ok: the XMP namespace prefix the files use /// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text). #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -29,10 +38,15 @@ pub struct FileInfo { pub title: Option, /// XMP `dc:creator` (its names joined with ", "), else Info `Author`. pub author: Option, + /// XMP `photoshop:AuthorsPosition`. + pub author_title: Option, /// XMP `dc:description` (its `x-default` item, else its first), else Info `Subject`. pub description: Option, /// XMP `dc:subject`, else XMP `pdf:Keywords` or Info `Keywords` split at commas and semicolons. pub keywords: Option>, + /// XMP `xmp:Rating`, a whole number from 0 to 5 (a rejected file's -1 and other values are + /// left out). + pub rating: Option, /// XMP `dc:rights` (its `x-default` item, else its first). pub copyright_notice: Option, /// XMP `xmpRights:WebStatement`. @@ -77,6 +91,21 @@ fn packet(pdf: &Pdf) -> Option> { /// [`xmp`] of `packet`; `None` when it isn't XML in UTF-8 or UTF-16, or when its elements nest /// more than [`MAX_NESTING`] deep. fn xmp(packet: &[u8]) -> Option { + read_xmp(packet, false) +} + +/// The File Info fields of the metadata template `bytes`, an XMP packet as [`metadata_template`] +/// writes one (or any XMP file); `None` when it is longer than [`MAX_TEMPLATE_BYTES`], isn't XML in +/// UTF-8 or UTF-16, has no `rdf:RDF` element, or nests more than [`MAX_NESTING`] deep. +pub fn read_template(bytes: &[u8]) -> Option { + if bytes.len() > MAX_TEMPLATE_BYTES { + return None; + } + read_xmp(bytes, true) +} + +/// [`xmp`]; with `need_rdf`, `None` for XML that has no `rdf:RDF` element. +fn read_xmp(packet: &[u8], need_rdf: bool) -> Option { let text = xml_text(packet)?; let opts = Options { names: Names::Canonical(&XMP_NAMESPACES), @@ -86,9 +115,12 @@ fn xmp(packet: &[u8]) -> Option { } .strict(); let root = opts.parse(text.as_bytes()).ok()?; + let rdfs: Vec<&El> = std::iter::once(&root).chain(root.descendants()).filter(|n| n.is("rdf:RDF")).collect(); + if need_rdf && rdfs.is_empty() { + return None; + } // The resource's own descriptions: those right under `rdf:RDF`, not the ones inside a value. - let descriptions: Vec<&El> = - std::iter::once(&root).chain(root.descendants()).filter(|n| n.is("rdf:RDF")).flat_map(|rdf| rdf.children("rdf:Description")).collect(); + let descriptions: Vec<&El> = rdfs.iter().flat_map(|rdf| rdf.children("rdf:Description")).collect(); let get = |name: &str| property(&descriptions, name); let first = |name: &str| get(name).into_iter().next(); let creators = get("dc:creator"); @@ -96,8 +128,10 @@ fn xmp(packet: &[u8]) -> Option { Some(FileInfo { title: first("dc:title"), author: (!creators.is_empty()).then(|| creators.join(", ")), + author_title: first("photoshop:AuthorsPosition"), // brand-ok: the XMP property name the files use description: first("dc:description"), keywords: if subjects.is_empty() { first("pdf:Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) }, + rating: first("xmp:Rating").and_then(|r| rating(&r)), copyright_notice: first("dc:rights"), copyright_url: first("xmpRights:WebStatement"), copyrighted: first("xmpRights:Marked").and_then(|m| match m.to_ascii_lowercase().as_str() { @@ -110,6 +144,59 @@ fn xmp(packet: &[u8]) -> Option { }) } +/// An `xmp:Rating` value as File Info takes one: a whole number from 0 to 5, written as an integer +/// or as a real with no fraction (`3`, `3.0`). The rejected rating -1, fractions and other values +/// give `None`. +fn rating(s: &str) -> Option { + let r: f64 = s.trim().parse().ok()?; + (r.fract() == 0.0 && (0.0..=5.0).contains(&r)).then_some(r as u8) +} + +/// The metadata template of `f`: an XMP packet (ISO 16684-1) holding its title (`dc:title`), author +/// (`dc:creator`), author title (`photoshop:AuthorsPosition`), description (`dc:description`), +/// keywords (`dc:subject`), rating (`xmp:Rating`), copyright status (`xmpRights:Marked`), notice +/// (`dc:rights`) and URL (`xmpRights:WebStatement`), each where `f` gives it, which +/// [`read_template`] reads back. The dates are left out. +pub fn metadata_template(f: &FileInfo) -> String { + use crate::post::xml_text as esc; + let alt = |name: &str, v: &str| format!(" <{name}>{}\n", esc(v)); + let simple = |name: &str, v: &str| format!(" <{name}>{}\n", esc(v)); + let blank = |v: &Option| v.as_deref().map(str::trim).filter(|v| !v.is_empty()).map(str::to_string); + let mut props = String::new(); + if let Some(v) = blank(&f.title) { + props.push_str(&alt("dc:title", &v)); + } + if let Some(v) = blank(&f.author) { + props.push_str(&format!(" {}\n", esc(&v))); + } + if let Some(v) = blank(&f.author_title) { + props.push_str(&simple("photoshop:AuthorsPosition", &v)); // brand-ok: the XMP property name the files use + } + if let Some(v) = blank(&f.description) { + props.push_str(&alt("dc:description", &v)); + } + let keywords: Vec<&str> = f.keywords.iter().flatten().map(|k| k.trim()).filter(|k| !k.is_empty()).collect(); + if !keywords.is_empty() { + let items: String = keywords.iter().map(|k| format!("{}", esc(k))).collect(); + props.push_str(&format!(" {items}\n")); + } + if let Some(r) = f.rating { + props.push_str(&simple("xmp:Rating", &r.to_string())); + } + if let Some(c) = f.copyrighted { + props.push_str(&simple("xmpRights:Marked", if c { "True" } else { "False" })); + } + if let Some(v) = blank(&f.copyright_notice) { + props.push_str(&alt("dc:rights", &v)); + } + if let Some(v) = blank(&f.copyright_url) { + props.push_str(&simple("xmpRights:WebStatement", &v)); + } + format!( + "\n\n \n \n{props} \n \n\n\n" // brand-ok: the XMP namespace prefix the files use + ) +} + /// A packet's text: UTF-8 (with or without a byte order mark), or UTF-16 told by its byte order /// mark or by a zero byte beside the `<` it starts with. fn xml_text(b: &[u8]) -> Option { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 0658624452..9cef615783 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -76,7 +76,7 @@ mod syntax; pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with}; pub use encrypt::Encryption; pub use export::{check_page_sizes, export, export_with_report, page_areas}; -pub use file_info::{FileInfo, file_info}; +pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template}; #[cfg(any(test, feature = "read-count"))] pub use import::imports_of; pub use import::{ diff --git a/crates/pdf/src/post.rs b/crates/pdf/src/post.rs index c6fdd8048d..79e872e59b 100644 --- a/crates/pdf/src/post.rs +++ b/crates/pdf/src/post.rs @@ -180,7 +180,7 @@ fn rights_properties(info: &DocMetadata) -> String { /// `s` as XML character data: `&`, `<`, `>` and `"` escaped, a carriage return written as the /// character reference ` `, and the characters XML 1.0 doesn't allow left out. -fn xml_text(s: &str) -> String { +pub(crate) fn xml_text(s: &str) -> String { let mut out = String::with_capacity(s.len()); for c in s.chars() { match c { diff --git a/crates/pdf/src/tests/file_info.rs b/crates/pdf/src/tests/file_info.rs index 4c837ba67f..57bbdcd58c 100644 --- a/crates/pdf/src/tests/file_info.rs +++ b/crates/pdf/src/tests/file_info.rs @@ -94,8 +94,10 @@ fn the_xmp_packet_gives_file_info() { FileInfo { title: Some("Poster".into()), author: Some("Ada Lovelace, Charles Babbage".into()), + author_title: None, description: Some("A poster\nfor the fair".into()), keywords: Some(vec!["fair".into(), "print".into()]), + rating: None, copyright_notice: Some("(c) 2026 Ada".into()), copyright_url: Some("https://example.com/rights".into()), copyrighted: Some(false), @@ -270,3 +272,48 @@ fn a_written_pdf_gives_its_copyright_back() { let f = file_info(&export(&d, &PdfOptions::uncompressed()).unwrap(), None).unwrap(); assert_eq!((f.author.as_deref(), f.copyright_notice.as_deref()), (Some("Ada"), Some("(c) Ada"))); } + +#[test] +fn a_metadata_template_gives_its_file_info_back() { + let f = FileInfo { + title: Some("Fair poster".into()), + author: Some("Ada & ".into()), + author_title: Some("Designer, \"lead\"".into()), + description: Some("A poster\r\nfor the fair".into()), + keywords: Some(vec!["fair".into(), "print, large".into()]), + rating: Some(4), + copyright_notice: Some("(c) 2026 Ada".into()), + copyright_url: Some("https://example.com/rights?a=1&b=2".into()), + copyrighted: Some(true), + ..Default::default() + }; + let xmp = metadata_template(&f); + assert!(xmp.starts_with(""), "{xmp}"); + assert_eq!(read_template(xmp.as_bytes()), Some(f)); + // A public-domain status writes Marked False; fields without a value and the dates are left out. + let f = FileInfo { copyrighted: Some(false), author: Some(" ".into()), created: Some(CREATED), ..Default::default() }; + let xmp = metadata_template(&f); + assert!(!xmp.contains("dc:creator") && !xmp.contains("CreateDate") && xmp.contains("False"), "{xmp}"); + assert_eq!(read_template(xmp.as_bytes()), Some(FileInfo { copyrighted: Some(false), ..Default::default() })); + // The template is the PDF packet's format: a PDF whose metadata stream holds one reads the same. + let f = FileInfo { author: Some("Ada".into()), author_title: Some("Editor".into()), rating: Some(2), ..Default::default() }; + let read = file_info(&pdf(None, Some(&metadata_template(&f))), None).unwrap(); + assert_eq!((read.author, read.author_title, read.rating), (f.author, f.author_title, f.rating)); +} + +#[test] +fn a_metadata_template_reads_ratings_and_refuses_what_is_not_xmp() { + let rated = |r: &str| read_template(packet(&description(&format!("xmp:Rating=\"{r}\""), "")).as_bytes()).unwrap().rating; + assert_eq!([rated("0"), rated("5"), rated("3.0"), rated(" 2 ")], [Some(0), Some(5), Some(3), Some(2)]); + // A rejected file's -1, fractions, ratings past 5 and words are left out. + assert_eq!([rated("-1"), rated("2.5"), rated("6"), rated("high")], [None; 4]); + // XML without `rdf:RDF`, text and a packet that isn't well-formed are not templates. + assert_eq!(read_template(b"Poster"), None); + assert_eq!(read_template(b"Ada Lovelace"), None); + assert_eq!(read_template(packet("").as_bytes()), None); + // An XMP packet with no File Info is a template with no fields. + assert_eq!(read_template(packet("").as_bytes()), Some(FileInfo::default())); + // Longer than the longest template read, it is refused without being parsed. + let long = packet(&description("", &" ".repeat(MAX_TEMPLATE_BYTES))); + assert_eq!(read_template(long.as_bytes()), None); +} diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index 3f3cbae3f2..77f3218da6 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -4,6 +4,10 @@ //! Fields: what `file.info` reports (and takes back) plus `__keyword`, the keyword being typed //! (Enter or Add turns it into chips; OK keeps it too). OK runs `file.info` with them: one undo //! step. On an error the dialog stays open. +//! +//! The ≡ menu at the top saves the fields as a metadata template (`file.info.saveTemplate`), imports +//! one (`file.info.applyTemplate`, after a choice of how to merge it into the fields), lists the +//! templates of the metadata templates folder and shows that folder. use serde_json::{Value, json}; use vectorcraft_doc::CopyrightStatus; @@ -11,18 +15,38 @@ use vectorcraft_doc::metadata::MAX_RATING; use super::document_setup::{LABEL, choice}; use super::{DialogSpec, form}; +use crate::picks::PickRequest; use crate::state::Dialog; use crate::theme::Tokens; -use crate::{VectorcraftApp, icons, widgets}; +use crate::{FilePick, VectorcraftApp, icons, widgets}; pub(super) const KIND: &str = "fileInfo"; /// The keyword being typed. const PENDING: &str = "__keyword"; +/// The template waiting for a merge choice: `{path}` or `{name}`. +const IMPORT: &str = "__import"; +/// The merge choice for [`IMPORT`]: `file.info.applyTemplate`'s `mode`. +const IMPORT_MODE: &str = "__importMode"; +/// The templates in the metadata templates folder, listed when the menu opens: `[label, file]` +/// pairs, the label being the name, or the file name where two templates share a name. +const TEMPLATES: &str = "__templates"; +/// The merge choices, as `file.info.applyTemplate` names them. +const MODES: [&str; 3] = ["replace", "keep", "append"]; +/// The extension of a metadata template file. +const XMP_EXT: &str = "xmp"; /// Width of the text fields. const FIELD: f32 = 320.0; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("File Info").into(), body, confirm, min_width: 500.0, max_width: Some(500.0), ..DialogSpec::FORM }; +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("File Info").into(), + body, + confirm, + // OK and Enter wait while a template being imported waits for its merge choice. + ok_enabled: Some(|_, d| !d.fields.get(IMPORT).is_some_and(Value::is_object)), + min_width: 500.0, + max_width: Some(500.0), + ..DialogSpec::FORM +}; /// Open File Info on the active document's. pub fn open(app: &mut VectorcraftApp) -> Result { @@ -60,8 +84,193 @@ fn add_keywords(d: &mut Dialog) { d.fields.insert(PENDING.into(), json!("")); } -fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// What the templates menu asked for, done once the menu is drawn. +enum Act { + Save, + Import, + Template(String), + Folder, +} + +/// A file dialog for metadata templates. +fn xmp_pick() -> FilePick { + FilePick { filters: vec![FilePick::filter("XMP metadata templates", &[XMP_EXT])], ..Default::default() } +} + +/// Whether the session has a metadata templates folder for Templates Folder to show (the web build +/// has none). +fn has_templates_folder(app: &VectorcraftApp) -> bool { + app.session.metadata_templates_dir().is_some() +} + +/// The ≡ templates menu at the top right, and the merge choice for a template it picked. +fn templates_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); + let can_save = crate::picks::can(app, &PickRequest::Save(xmp_pick())); + let can_open = crate::picks::can(app, &PickRequest::Open(xmp_pick())); + let has_folder = has_templates_folder(app); + let mut act = None; + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let (rect, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); + let resp = ui.interact(rect, ui.scope_id().with("file-info-templates"), egui::Sense::click()); + icons::paint(ui, "menu", rect.shrink(1.0), if resp.hovered() { t.text_strong } else { t.text_dim }); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Templates"))); + let resp = resp.on_hover_text(tl!("Templates")); + if resp.clicked() { + // Listed once as the menu opens, not on every frame it shows. + let listed = app.session.execute("file.info.templates", &json!({})).map(|r| r["templates"].clone()).unwrap_or_default(); + let listed: Vec<(&str, &str)> = + listed.as_array().into_iter().flatten().filter_map(|t| Some((t.get("name")?.as_str()?, t.get("file")?.as_str()?))).collect(); + let entries: Vec = listed + .iter() + .map(|&(name, file)| { + let shared = listed.iter().filter(|(n, _)| *n == name).count() > 1; + json!([if shared { file } else { name }, file]) + }) + .collect(); + d.fields.insert(TEMPLATES.into(), json!(entries)); + } + egui::Popup::menu(&resp).show(|ui| { + ui.set_min_width(220.0); + if can_save && widgets::menu_item(ui, tl!("Save Metadata Template…"), true, false) { + act = Some(Act::Save); + } + if can_open && widgets::menu_item(ui, tl!("Import…"), true, false) { + act = Some(Act::Import); + } + let entries: Vec<(String, String)> = d + .fields + .get(TEMPLATES) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_str()?.to_string()))) + .collect(); + if !entries.is_empty() { + ui.separator(); + widgets::menu_scroll(ui, |ui| { + for (label, file) in entries { + if widgets::menu_item_name(ui, &label, true, false) { + act = Some(Act::Template(file)); + } + } + }); + } + if has_folder { + ui.separator(); + if widgets::menu_item(ui, tl!("Templates Folder"), true, false) { + act = Some(Act::Folder); + } + } + }); + }) + }); + let r = match act { + None => Ok(()), + // The file dialogs, shown off the UI thread, act on the dialog as it is then. + Some(Act::Save) => crate::picks::in_dialog(app, d, save_template), + Some(Act::Import) => crate::picks::in_dialog(app, d, pick_template), + // `file.info.applyTemplate` takes a listed template's file name as its `name`. + Some(Act::Template(file)) => { + d.fields.insert(IMPORT.into(), json!({ "name": file })); + Ok(()) + } + Some(Act::Folder) => show_folder(app), + }; + if let Err(e) = r { + app.status(e); + } + import_options(app, ui, d); +} + +/// Save Metadata Template…: the fields as they are in the dialog, to a file picked in a save +/// dialog that starts in the metadata templates folder. A name typed without `.xmp` takes it, so +/// the templates list shows the file; a file already there under that name is replaced only after +/// a question. +fn save_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let mut d2 = d.clone(); + add_keywords(&mut d2); + let folder = app.session.execute("file.info.templates", &json!({ "create": true })).ok().and_then(|r| r["folder"].as_str().map(str::to_string)); + let name = format!("{}.{XMP_EXT}", d2.str("title").trim()); + let pick = FilePick { name, folder, ..xmp_pick() }; + // None: canceled, or the dialog is still open off the UI thread and runs this again. + let Some(picked) = crate::picks::save(app, &pick) else { return Ok(()) }; + let path = if picked.to_ascii_lowercase().ends_with(&format!(".{XMP_EXT}")) { picked.clone() } else { format!("{picked}.{XMP_EXT}") }; + // The save dialog did not ask about the completed name: ask here, and the answer runs this again. + if path != picked && crate::picks::ask_to_replace(app, PickRequest::Save(pick), &picked, None, &path) { + return Ok(()); + } + app.run("file.info.saveTemplate", json!({ "path": path, "fields": form::params(&d2) })).map(|_| ()) +} + +/// Import…: a template picked in an open dialog waits for its merge choice. +fn pick_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + // None: canceled, or the dialog is still open off the UI thread and runs this again. + let Some(path) = crate::picks::open(app, &xmp_pick()) else { return Ok(()) }; + d.fields.insert(IMPORT.into(), json!({ "path": path })); + Ok(()) +} + +/// Templates Folder: the metadata templates folder (made when it is missing) in the file manager. +fn show_folder(app: &mut VectorcraftApp) -> Result<(), String> { + let r = app.session.execute("file.info.templates", &json!({ "create": true })).map_err(|e| e.to_string())?; + let folder = r["folder"].as_str().ok_or("no metadata templates folder here")?.to_string(); + crate::io::open_in_app(app, &folder) +} + +/// The merge choice for the template [`IMPORT`] names: OK merges it into the dialog's fields +/// (nothing changes in the document until the dialog's own OK), Cancel drops it. +fn import_options(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + let Some(source) = d.fields.get(IMPORT).and_then(Value::as_object).cloned() else { return }; + widgets::subheader(ui, tl!("Import Options")); + let mode = d.fields.get(IMPORT_MODE).and_then(Value::as_str).filter(|m| MODES.contains(m)).unwrap_or("keep").to_string(); + let labels = [ + tl!("Clear existing fields and use the template's"), + tl!("Keep existing fields, but replace those the template has"), + tl!("Keep existing fields, but append those the template has"), + ]; + for (value, label) in MODES.into_iter().zip(labels) { + if widgets::radio(ui, label, mode == value, true) { + d.fields.insert(IMPORT_MODE.into(), json!(value)); + } + } + let mut ok = false; + let mut cancel = false; + ui.horizontal(|ui| { + ok = widgets::flat_button(ui, tl!("OK"), 64.0).clicked(); + cancel = widgets::flat_button(ui, tl!("Cancel"), 64.0).clicked(); + }); + ui.add_space(10.0); + if ok { + if let Err(e) = import(app, d, source, &mode) { + app.status(e); + } + } else if cancel { + d.fields.remove(IMPORT); + } +} + +/// Merge the template `source` names into the dialog's fields as `mode` says. +fn import(app: &mut VectorcraftApp, d: &mut Dialog, source: serde_json::Map, mode: &str) -> Result<(), String> { + let mut p = Value::Object(source); + p["mode"] = json!(mode); + p["apply"] = json!(false); + let mut d2 = d.clone(); + add_keywords(&mut d2); + p["base"] = form::params(&d2); + let merged = app.session.execute("file.info.applyTemplate", &p).map_err(|e| e.to_string())?; + for (k, v) in merged.as_object().into_iter().flatten() { + d.fields.insert(k.clone(), v.clone()); + } + d.fields.insert(PENDING.into(), json!("")); + d.fields.remove(IMPORT); + Ok(()) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + templates_menu(app, ui, d); for (key, label) in [("title", tl!("Document Title:")), ("author", tl!("Author:")), ("authorTitle", tl!("Author Title:"))] { widgets::label_row(ui, label, LABEL, |ui| { form::text(ui, d, key, FIELD); @@ -233,4 +442,86 @@ mod tests { assert!(crate::dialogs::confirm(&mut app).is_err()); assert!(app.ui.dialog.is_some()); } + + #[test] + fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.attach_metadata_templates_dir(dir.join("Metadata Templates")); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info.saveTemplate", json!({"name": "Studio", "fields": {"author": "Grace", "keywords": ["print"], "rating": 3}})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("author".into(), json!("Ada")); + d.fields.insert(super::PENDING.into(), json!("fair")); + // A listed template waits for its merge choice; the choice draws. + d.fields.insert(super::IMPORT.into(), json!({"name": "Studio"})); + d.fields.insert(super::IMPORT_MODE.into(), json!("append")); + frame(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + super::import(&mut app, &mut d, json!({"name": "Studio"}).as_object().unwrap().clone(), "append").unwrap(); + assert!(!d.fields.contains_key(super::IMPORT)); + // Appended: the typed author stays, the typed keyword is kept and the template's added. + assert_eq!( + (d.fields["author"].clone(), d.fields["keywords"].clone(), d.fields["rating"].clone()), + (json!("Ada"), json!(["fair", "print"]), json!(3)) + ); + assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "nothing changes before OK"); + app.ui.dialog = Some(d); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.metadata.author.as_str(), st.doc.metadata.rating), ("Ada", 3)); + assert_eq!(st.history.undo.len(), 1); + } + + #[test] + fn templates_folder_is_offered_only_where_there_is_one() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-folder"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert!(!super::has_templates_folder(&app), "a session without a folder, as on the web, offers no Templates Folder"); + app.session.attach_metadata_templates_dir(dir.join("Metadata Templates")); + assert!(super::has_templates_folder(&app)); + } + + #[test] + fn ok_waits_for_the_merge_choice_of_a_template_being_imported() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let ok = |app: &VectorcraftApp, d: &crate::state::Dialog| super::SPEC.ok_enabled.is_none_or(|f| f(app, d)); + assert!(ok(&app, &d)); + d.fields.insert(super::IMPORT.into(), json!({"name": "Studio"})); + assert!(!ok(&app, &d), "OK and Enter wait while the merge choice is shown"); + d.fields.remove(super::IMPORT); + assert!(ok(&app, &d)); + } + + #[test] + fn a_template_saved_without_an_extension_gets_xmp_and_is_listed() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-save-ext"); + let folder = dir.join("Metadata Templates"); + let typed = folder.join("Studio").to_string_lossy().into_owned(); + let services = crate::Services { + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())), + pick_save: Some(Box::new(move |_: &crate::FilePick| Some(typed.clone()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.session.attach_metadata_templates_dir(folder.clone()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("author".into(), json!("Ada")); + crate::picks::in_dialog(&mut app, &mut d, super::save_template).unwrap(); + assert!(folder.join("Studio.xmp").is_file() && !folder.join("Studio").exists(), "the typed name takes .xmp"); + let listed = app.session.execute("file.info.templates", &json!({})).unwrap(); + assert!(listed.to_string().contains("Studio"), "{listed}"); + // A file already there under the completed name is not replaced without asking. + std::fs::write(folder.join("Studio.xmp"), b"kept").unwrap(); + crate::picks::in_dialog(&mut app, &mut d, super::save_template).unwrap(); + assert_eq!(std::fs::read(folder.join("Studio.xmp")).unwrap(), b"kept"); + assert_eq!(d.kind, crate::dialogs::confirm::REPLACE, "the dialog asks before replacing it"); + } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 61e90c789d..91f99cfa7e 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -639,6 +639,11 @@ font-technology Variable Променливи Copy Width Point Копиране на точка на ширина Copyright Авторско право Copyright Info URL: URL адрес с информация за авторското право: + Save Metadata Template… Запази шаблон за метаданни… + Import Options Опции за импортиране + Clear existing fields and use the template's Изчисти съществуващите полета и използвай тези от шаблона + Keep existing fields, but replace those the template has Запази съществуващите полета, но замени съдържащите се в шаблона + Keep existing fields, but append those the template has Запази съществуващите полета, но добави съдържащите се в шаблона Copyright Notice: Бележка за авторското право: Copyright Status: Статус на авторското право: Copyright Symbol Символ за авторско право diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index b3a4eefc2f..869bdddd59 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2573,6 +2573,11 @@ digits Malayalam Malajalam Author Title: Titula autora: Author: Autor: Copyright Info URL: URL informacija o autorskim pravima: + Save Metadata Template… Sačuvaj predložak metapodataka… + Import Options Opcije uvoza + Clear existing fields and use the template's Obriši postojeća polja i koristi polja iz predloška + Keep existing fields, but replace those the template has Zadrži postojeća polja, ali zamijeni ona koja predložak sadrži + Keep existing fields, but append those the template has Zadrži postojeća polja, ali dodaj ona koja predložak sadrži Copyright Notice: Obavještenje o autorskim pravima: Copyright Status: Status autorskih prava: Created: Kreirano: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2f9f1d8fdc..ea5b038ada 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -947,6 +947,18 @@ antiAlias Sharp Nítid Copyright Copyright Copyright and Contact Info Informació de copyright i de contacte Copyright Info URL: URL de la informació de copyright: + Save Metadata Template… Desa la plantilla de metadades… + Import Options Opcions d’importació + Clear existing fields and use the template's Esborra els camps existents i fes servir els de la plantilla + Keep existing fields, but replace those the template has Conserva els camps existents, però substitueix els que tingui la plantilla + Keep existing fields, but append those the template has Conserva els camps existents, però afegeix els que tingui la plantilla +@msg the template name can't be empty el nom de la plantilla no pot estar buit +@msg the template name isn't usable as a file name el nom de la plantilla no es pot fer servir com a nom de fitxer +@msg no metadata templates folder here aquí no hi ha cap carpeta de plantilles de metadades +@msg give `name` or `path`, not both indiqueu `name` o `path`, no tots dos +@msg give one of `path`, `name` and `data` indiqueu un de `path`, `name` i `data` +@msg mode must be replace, keep or append el mode ha de ser replace, keep o append +@msg the file is not an XMP metadata template el fitxer no és una plantilla de metadades XMP Copyright Notice: Avís de copyright: Copyright Status: Estat del copyright: Copyright Symbol Símbol de copyright diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4628b89a1d..7f5abdc4fa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2648,6 +2648,18 @@ digits Malayalam Malajálamské Author Title: Funkce autora: Author: Autor: Copyright Info URL: URL informací o autorských právech: + Save Metadata Template… Uložit šablonu metadat… + Import Options Možnosti importu + Clear existing fields and use the template's Vymazat stávající pole a použít pole ze šablony + Keep existing fields, but replace those the template has Zachovat stávající pole, ale nahradit ta, která šablona obsahuje + Keep existing fields, but append those the template has Zachovat stávající pole, ale připojit ta, která šablona obsahuje +@msg the template name can't be empty název šablony nesmí být prázdný +@msg the template name isn't usable as a file name název šablony nelze použít jako název souboru +@msg no metadata templates folder here zde není žádná složka šablon metadat +@msg give `name` or `path`, not both zadejte `name` nebo `path`, ne obojí +@msg give one of `path`, `name` and `data` zadejte jeden z parametrů `path`, `name` a `data` +@msg mode must be replace, keep or append režim musí být replace, keep nebo append +@msg the file is not an XMP metadata template soubor není šablona metadat XMP Copyright Notice: Upozornění o autorských právech: Copyright Status: Stav autorských práv: Created: Vytvořeno: diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8b822be042..ae3a24461a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3057,6 +3057,18 @@ digits Malayalam Malayalam Author Title: Forfattertitel: Author: Forfatter: Copyright Info URL: URL til ophavsretinfo: + Save Metadata Template… Gem metadataskabelon… + Import Options Importindstillinger + Clear existing fields and use the template's Ryd eksisterende felter, og brug skabelonens + Keep existing fields, but replace those the template has Behold eksisterende felter, men erstat dem, skabelonen har + Keep existing fields, but append those the template has Behold eksisterende felter, men tilføj dem, skabelonen har +@msg the template name can't be empty skabelonnavnet må ikke være tomt +@msg the template name isn't usable as a file name skabelonnavnet kan ikke bruges som filnavn +@msg no metadata templates folder here der er ingen mappe til metadataskabeloner her +@msg give `name` or `path`, not both angiv `name` eller `path`, ikke begge +@msg give one of `path`, `name` and `data` angiv én af `path`, `name` og `data` +@msg mode must be replace, keep or append tilstanden skal være replace, keep eller append +@msg the file is not an XMP metadata template filen er ikke en XMP-metadataskabelon Copyright Notice: Ophavsretserklæring: Copyright Status: Ophavsretstatus: Created: Oprettet: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 752a60accd..fda2fe9906 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -632,6 +632,18 @@ font-technology Variable Variabel Copy Width Point Breitenpunkt kopieren Copyright Copyright Copyright Info URL: URL für Copyright-Informationen: + Save Metadata Template… Metadatenvorlage speichern… + Import Options Importoptionen + Clear existing fields and use the template's Vorhandene Felder löschen und die der Vorlage verwenden + Keep existing fields, but replace those the template has Vorhandene Felder beibehalten, aber die in der Vorlage enthaltenen ersetzen + Keep existing fields, but append those the template has Vorhandene Felder beibehalten, aber die in der Vorlage enthaltenen anfügen +@msg the template name can't be empty der Vorlagenname darf nicht leer sein +@msg the template name isn't usable as a file name der Vorlagenname ist als Dateiname nicht verwendbar +@msg no metadata templates folder here hier gibt es keinen Ordner für Metadatenvorlagen +@msg give `name` or `path`, not both geben Sie `name` oder `path` an, nicht beides +@msg give one of `path`, `name` and `data` geben Sie einen der Parameter `path`, `name` und `data` an +@msg mode must be replace, keep or append der Modus muss replace, keep oder append sein +@msg the file is not an XMP metadata template die Datei ist keine XMP-Metadatenvorlage Copyright Notice: Copyright-Vermerk: Copyright Status: Copyright-Status: Copyright Symbol Copyright-Symbol diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9b32ea177c..dd7fac65af 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -613,6 +613,18 @@ font-technology Variable Μεταβλητές Copy Width Point Αντιγραφή σημείου πλάτους Copyright Πνευματικά δικαιώματα Copyright Info URL: URL πληροφοριών πνευματικών δικαιωμάτων: + Save Metadata Template… Αποθήκευση προτύπου μεταδεδομένων… + Import Options Επιλογές εισαγωγής + Clear existing fields and use the template's Απαλοιφή των υπαρχόντων πεδίων και χρήση εκείνων του προτύπου + Keep existing fields, but replace those the template has Διατήρηση των υπαρχόντων πεδίων, αλλά αντικατάσταση όσων έχει το πρότυπο + Keep existing fields, but append those the template has Διατήρηση των υπαρχόντων πεδίων, αλλά προσθήκη όσων έχει το πρότυπο +@msg the template name can't be empty το όνομα του προτύπου δεν μπορεί να είναι κενό +@msg the template name isn't usable as a file name το όνομα του προτύπου δεν μπορεί να χρησιμοποιηθεί ως όνομα αρχείου +@msg no metadata templates folder here δεν υπάρχει φάκελος προτύπων μεταδεδομένων εδώ +@msg give `name` or `path`, not both δώστε `name` ή `path`, όχι και τα δύο +@msg give one of `path`, `name` and `data` δώστε ένα από τα `path`, `name` και `data` +@msg mode must be replace, keep or append η λειτουργία πρέπει να είναι replace, keep ή append +@msg the file is not an XMP metadata template το αρχείο δεν είναι πρότυπο μεταδεδομένων XMP Copyright Notice: Σημείωση πνευματικών δικαιωμάτων: Copyright Status: Κατάσταση πνευματικών δικαιωμάτων: Copyright Symbol Σύμβολο πνευματικών δικαιωμάτων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9c81265e9d..00d4e3b3d3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -654,6 +654,18 @@ font-technology Variable Variables Copy Width Point Copiar punto de anchura Copyright Copyright Copyright Info URL: URL de información de copyright: + Save Metadata Template… Guardar plantilla de metadatos… + Import Options Opciones de importación + Clear existing fields and use the template's Borrar los campos existentes y usar los de la plantilla + Keep existing fields, but replace those the template has Conservar los campos existentes, pero reemplazar los que tenga la plantilla + Keep existing fields, but append those the template has Conservar los campos existentes, pero añadir los que tenga la plantilla +@msg the template name can't be empty el nombre de la plantilla no puede estar vacío +@msg the template name isn't usable as a file name el nombre de la plantilla no se puede usar como nombre de archivo +@msg no metadata templates folder here aquí no hay ninguna carpeta de plantillas de metadatos +@msg give `name` or `path`, not both indique `name` o `path`, no ambos +@msg give one of `path`, `name` and `data` indique uno de `path`, `name` y `data` +@msg mode must be replace, keep or append el modo debe ser replace, keep o append +@msg the file is not an XMP metadata template el archivo no es una plantilla de metadatos XMP Copyright Notice: Aviso de copyright: Copyright Status: Estado de copyright: Copyright Symbol Símbolo de copyright diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 67897bbe68..fdf4dbc246 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2603,6 +2603,18 @@ digits Malayalam Malajalam Author Title: Tekijän titteli: Author: Tekijä: Copyright Info URL: Tekijänoikeustietojen URL: + Save Metadata Template… Tallenna metatietomallipohja… + Import Options Tuontiasetukset + Clear existing fields and use the template's Tyhjennä nykyiset kentät ja käytä mallipohjan kenttiä + Keep existing fields, but replace those the template has Säilytä nykyiset kentät, mutta korvaa mallipohjassa olevat + Keep existing fields, but append those the template has Säilytä nykyiset kentät, mutta lisää mallipohjassa olevat +@msg the template name can't be empty mallipohjan nimi ei voi olla tyhjä +@msg the template name isn't usable as a file name mallipohjan nimeä ei voi käyttää tiedostonimenä +@msg no metadata templates folder here täällä ei ole metatietomallipohjien kansiota +@msg give `name` or `path`, not both anna `name` tai `path`, ei molempia +@msg give one of `path`, `name` and `data` anna yksi seuraavista: `path`, `name` ja `data` +@msg mode must be replace, keep or append tilan on oltava replace, keep tai append +@msg the file is not an XMP metadata template tiedosto ei ole XMP-metatietomallipohja Copyright Notice: Tekijänoikeusilmoitus: Copyright Status: Tekijänoikeuden tila: Created: Luotu: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9c04f43b1b..bc843d123a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -654,6 +654,18 @@ font-technology Variable Variables Copy to User Defined Copier dans Défini par l’utilisateur Copy Width Point Copier le point de largeur Copyright Copyright + Save Metadata Template… Enregistrer le modèle de métadonnées… + Import Options Options d’importation + Clear existing fields and use the template's Effacer les champs existants et utiliser ceux du modèle + Keep existing fields, but replace those the template has Conserver les champs existants, mais remplacer ceux que contient le modèle + Keep existing fields, but append those the template has Conserver les champs existants, mais ajouter ceux que contient le modèle +@msg the template name can't be empty le nom du modèle ne peut pas être vide +@msg the template name isn't usable as a file name le nom du modèle n'est pas utilisable comme nom de fichier +@msg no metadata templates folder here aucun dossier de modèles de métadonnées ici +@msg give `name` or `path`, not both indiquez `name` ou `path`, pas les deux +@msg give one of `path`, `name` and `data` indiquez un seul des paramètres `path`, `name` et `data` +@msg mode must be replace, keep or append le mode doit être replace, keep ou append +@msg the file is not an XMP metadata template le fichier n’est pas un modèle de métadonnées XMP Copyright Info URL: URL des informations de copyright : Copyright Notice: Mention de copyright : Copyright Status: État du copyright : diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4807c7ec25..7391818b84 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -762,6 +762,12 @@ Copy to User Defined વપરાશકર્તા-વ્યાખ્યાયિતમાં નકલ કરો Copyright કૉપીરાઇટ Copyright Info URL: કૉપીરાઇટ માહિતી URL: + Templates ટેમ્પલેટ + Save Metadata Template… મેટાડેટા ટેમ્પલેટ સાચવો… + Import Options આયાત વિકલ્પો + Clear existing fields and use the template's હાલના ફીલ્ડ સાફ કરો અને ટેમ્પલેટના ફીલ્ડ વાપરો + Keep existing fields, but replace those the template has હાલના ફીલ્ડ રાખો, પણ ટેમ્પલેટમાં હોય તે બદલો + Keep existing fields, but append those the template has હાલના ફીલ્ડ રાખો, પણ ટેમ્પલેટમાં હોય તે ઉમેરો Copyright Notice: કૉપીરાઇટ સૂચના: Copyright Status: કૉપીરાઇટ સ્થિતિ: Copyright Symbol કૉપીરાઇટ ચિહ્ન diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 15582a2dbd..1bde03a5f8 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1085,6 +1085,18 @@ antiAlias Sharp शार्प Copyright कॉपीराइट Copyright and Contact Info कॉपीराइट और संपर्क जानकारी Copyright Info URL: कॉपीराइट जानकारी URL: + Save Metadata Template… मेटाडेटा टेम्पलेट सेव करें… + Import Options इम्पोर्ट विकल्प + Clear existing fields and use the template's मौजूदा फ़ील्ड साफ़ करें और टेम्पलेट के फ़ील्ड उपयोग करें + Keep existing fields, but replace those the template has मौजूदा फ़ील्ड रखें, लेकिन टेम्पलेट में मौजूद फ़ील्ड बदलें + Keep existing fields, but append those the template has मौजूदा फ़ील्ड रखें, लेकिन टेम्पलेट में मौजूद फ़ील्ड जोड़ें +@msg the template name can't be empty टेम्पलेट का नाम खाली नहीं हो सकता +@msg the template name isn't usable as a file name टेम्पलेट का नाम फ़ाइल नाम के रूप में उपयोग नहीं किया जा सकता +@msg no metadata templates folder here यहाँ कोई मेटाडेटा टेम्पलेट फ़ोल्डर नहीं है +@msg give `name` or `path`, not both `name` या `path` दें, दोनों नहीं +@msg give one of `path`, `name` and `data` `path`, `name` और `data` में से एक दें +@msg mode must be replace, keep or append मोड replace, keep या append होना चाहिए +@msg the file is not an XMP metadata template फ़ाइल XMP मेटाडेटा टेम्पलेट नहीं है Copyright Notice: कॉपीराइट सूचना: Copyright Status: कॉपीराइट स्थिति: Copyright Symbol कॉपीराइट सिंबल diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8ddb1d34ca..fc8ad86fd7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -854,6 +854,18 @@ font-technology Variable Változó Copyright Szerzői jog Copyright and Contact Info Szerzői jogi és kapcsolati adatok Copyright Info URL: Szerzői jogi információ URL-je: + Save Metadata Template… Metaadatsablon mentése… + Import Options Importálási beállítások + Clear existing fields and use the template's Meglévő mezők törlése és a sablon mezőinek használata + Keep existing fields, but replace those the template has Meglévő mezők megtartása, de a sablonban szereplők cseréje + Keep existing fields, but append those the template has Meglévő mezők megtartása, de a sablonban szereplők hozzáfűzése +@msg the template name can't be empty a sablon neve nem lehet üres +@msg the template name isn't usable as a file name a sablon neve nem használható fájlnévként +@msg no metadata templates folder here itt nincs metaadatsablon-mappa +@msg give `name` or `path`, not both adja meg a `name` vagy a `path` paramétert, de ne mindkettőt +@msg give one of `path`, `name` and `data` adja meg a `path`, a `name` és a `data` paraméterek egyikét +@msg mode must be replace, keep or append a mód értéke replace, keep vagy append lehet +@msg the file is not an XMP metadata template a fájl nem XMP-metaadatsablon Copyright Notice: Szerzői jogi közlemény: Copyright Status: Szerzői jogi állapot: Copyright Symbol Szerzői jogi jel diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8d7639c430..643f4f0203 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2391,6 +2391,11 @@ digits Malayalam Malayalam Author Title: Judul penulis: Author: Penulis: Copyright Info URL: URL info hak cipta: + Save Metadata Template… Simpan templat metadata… + Import Options Opsi impor + Clear existing fields and use the template's Hapus bidang yang ada dan gunakan bidang templat + Keep existing fields, but replace those the template has Pertahankan bidang yang ada, tetapi ganti bidang yang dimiliki templat + Keep existing fields, but append those the template has Pertahankan bidang yang ada, tetapi tambahkan bidang yang dimiliki templat Copyright Notice: Pemberitahuan hak cipta: Copyright Status: Status hak cipta: Created: Dibuat: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1c0590ff98..939182f467 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -654,6 +654,18 @@ font-technology Variable Variabili Copy Width Point Copia punto di larghezza Copyright Copyright Copyright Info URL: URL informazioni copyright: + Save Metadata Template… Salva modello di metadati… + Import Options Opzioni di importazione + Clear existing fields and use the template's Cancella i campi esistenti e usa quelli del modello + Keep existing fields, but replace those the template has Mantieni i campi esistenti, ma sostituisci quelli presenti nel modello + Keep existing fields, but append those the template has Mantieni i campi esistenti, ma aggiungi quelli presenti nel modello +@msg the template name can't be empty il nome del modello non può essere vuoto +@msg the template name isn't usable as a file name il nome del modello non è utilizzabile come nome di file +@msg no metadata templates folder here qui non c'è una cartella dei modelli di metadati +@msg give `name` or `path`, not both indica `name` o `path`, non entrambi +@msg give one of `path`, `name` and `data` indica uno tra `path`, `name` e `data` +@msg mode must be replace, keep or append la modalità deve essere replace, keep o append +@msg the file is not an XMP metadata template il file non è un modello di metadati XMP Copyright Notice: Nota sul copyright: Copyright Status: Stato copyright: Copyright Symbol Simbolo di copyright diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index dedcdb328e..32ae0df5da 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1386,6 +1386,18 @@ antiAlias Sharp シャープ Copy Width Point 幅ポイントをコピー Copyright 著作権 Copyright Info URL: 著作権情報の URL: + Save Metadata Template… メタデータテンプレートを保存… + Import Options 読み込みオプション + Clear existing fields and use the template's 既存のフィールドを消去してテンプレートのフィールドを使用 + Keep existing fields, but replace those the template has 既存のフィールドを保持し、テンプレートにあるフィールドを置換 + Keep existing fields, but append those the template has 既存のフィールドを保持し、テンプレートにあるフィールドを追加 +@msg the template name can't be empty テンプレート名は空にできません +@msg the template name isn't usable as a file name テンプレート名はファイル名として使用できません +@msg no metadata templates folder here ここにはメタデータテンプレートのフォルダーがありません +@msg give `name` or `path`, not both `name` と `path` のどちらか一方を指定してください +@msg give one of `path`, `name` and `data` `path`、`name`、`data` のいずれか 1 つを指定してください +@msg mode must be replace, keep or append モードは replace、keep、append のいずれかにしてください +@msg the file is not an XMP metadata template このファイルは XMP メタデータテンプレートではありません Copyright Notice: 著作権表示: Copyright Status: 著作権の状態: Corner Point Angle Threshold: コーナーポイントの角度のしきい値: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d9d75dd737..7b5d439ed4 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4444,6 +4444,18 @@ digits Malayalam მალაიალამური Author Title: ავტორის თანამდებობა: Author: ავტორი: Copyright Info URL: საავტორო უფლების ინფორმაციის URL: + Save Metadata Template… მეტამონაცემების შაბლონის შენახვა… + Import Options იმპორტის პარამეტრები + Clear existing fields and use the template's არსებული ველების გასუფთავება და შაბლონის ველების გამოყენება + Keep existing fields, but replace those the template has არსებული ველების შენარჩუნება, მაგრამ შაბლონში არსებულების ჩანაცვლება + Keep existing fields, but append those the template has არსებული ველების შენარჩუნება, მაგრამ შაბლონში არსებულების დამატება +@msg the template name can't be empty შაბლონის სახელი ცარიელი ვერ იქნება +@msg the template name isn't usable as a file name შაბლონის სახელი ფაილის სახელად ვერ გამოდგება +@msg no metadata templates folder here აქ მეტამონაცემების შაბლონების საქაღალდე არ არის +@msg give `name` or `path`, not both მიუთითეთ `name` ან `path`, არა ორივე +@msg give one of `path`, `name` and `data` მიუთითეთ ერთ-ერთი: `path`, `name` და `data` +@msg mode must be replace, keep or append რეჟიმი უნდა იყოს replace, keep ან append +@msg the file is not an XMP metadata template ფაილი არ არის XMP მეტამონაცემების შაბლონი Copyright Notice: საავტორო უფლების შენიშვნა: Copyright Status: საავტორო უფლების სტატუსი: Created: შექმნილია: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 90f4e1f3fd..838eba9910 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1376,6 +1376,18 @@ antiAlias Sharp 날카롭게 Copy Width Point 너비 점 복사 Copyright 저작권 Copyright Info URL: 저작권 정보 URL: + Save Metadata Template… 메타데이터 템플릿 저장… + Import Options 가져오기 옵션 + Clear existing fields and use the template's 기존 필드를 지우고 템플릿의 필드 사용 + Keep existing fields, but replace those the template has 기존 필드를 유지하되 템플릿에 있는 필드 바꾸기 + Keep existing fields, but append those the template has 기존 필드를 유지하되 템플릿에 있는 필드 추가 +@msg the template name can't be empty 템플릿 이름은 비워 둘 수 없습니다 +@msg the template name isn't usable as a file name 템플릿 이름은 파일 이름으로 사용할 수 없습니다 +@msg no metadata templates folder here 여기에는 메타데이터 템플릿 폴더가 없습니다 +@msg give `name` or `path`, not both `name` 또는 `path` 중 하나만 지정하세요 +@msg give one of `path`, `name` and `data` `path`, `name`, `data` 중 하나를 지정하세요 +@msg mode must be replace, keep or append 모드는 replace, keep 또는 append여야 합니다 +@msg the file is not an XMP metadata template 파일이 XMP 메타데이터 템플릿이 아닙니다 Copyright Notice: 저작권 고지: Copyright Status: 저작권 상태: Corner Point Angle Threshold: 모퉁이 포인트 각도 임계값: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 990e369f0f..42418de7fc 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2953,6 +2953,18 @@ digits Malayalam Malayalam Author Title: Auteurstitel: Author: Auteur: Copyright Info URL: URL voor copyrightinfo: + Save Metadata Template… Metagegevenssjabloon opslaan… + Import Options Importopties + Clear existing fields and use the template's Bestaande velden wissen en die van het sjabloon gebruiken + Keep existing fields, but replace those the template has Bestaande velden behouden, maar die in het sjabloon vervangen + Keep existing fields, but append those the template has Bestaande velden behouden, maar die in het sjabloon toevoegen +@msg the template name can't be empty de sjabloonnaam mag niet leeg zijn +@msg the template name isn't usable as a file name de sjabloonnaam is niet bruikbaar als bestandsnaam +@msg no metadata templates folder here hier is geen map voor metagegevenssjablonen +@msg give `name` or `path`, not both geef `name` of `path` op, niet allebei +@msg give one of `path`, `name` and `data` geef één van `path`, `name` en `data` op +@msg mode must be replace, keep or append de modus moet replace, keep of append zijn +@msg the file is not an XMP metadata template het bestand is geen XMP-metagegevenssjabloon Copyright Notice: Copyrightvermelding: Copyright Status: Copyrightstatus: Created: Aangemaakt: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 647a0c62bd..fdc900822e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2563,6 +2563,18 @@ digits Malayalam Malajalam Author Title: Stanowisko autora: Author: Autor: Copyright Info URL: URL informacji o prawach autorskich: + Save Metadata Template… Zapisz szablon metadanych… + Import Options Opcje importu + Clear existing fields and use the template's Wyczyść istniejące pola i użyj pól z szablonu + Keep existing fields, but replace those the template has Zachowaj istniejące pola, ale zastąp te, które zawiera szablon + Keep existing fields, but append those the template has Zachowaj istniejące pola, ale dołącz te, które zawiera szablon +@msg the template name can't be empty nazwa szablonu nie może być pusta +@msg the template name isn't usable as a file name nazwy szablonu nie można użyć jako nazwy pliku +@msg no metadata templates folder here brak tu folderu szablonów metadanych +@msg give `name` or `path`, not both podaj `name` albo `path`, nie oba +@msg give one of `path`, `name` and `data` podaj jeden z parametrów `path`, `name` i `data` +@msg mode must be replace, keep or append tryb musi mieć wartość replace, keep lub append +@msg the file is not an XMP metadata template plik nie jest szablonem metadanych XMP Copyright Notice: Informacja o prawach autorskich: Copyright Status: Status praw autorskich: Created: Utworzono: diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2c0817772d..7185f6a620 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -590,6 +590,18 @@ antiAlias Sharp Nítido Copy to User Defined Copiar para Definido pelo Usuário Copyright Direitos Autorais Copyright Info URL: URL de Informações de Direitos Autorais: + Save Metadata Template… Salvar Modelo de Metadados… + Import Options Opções de Importação + Clear existing fields and use the template's Limpar os campos existentes e usar os do modelo + Keep existing fields, but replace those the template has Manter os campos existentes, mas substituir os que o modelo tiver + Keep existing fields, but append those the template has Manter os campos existentes, mas acrescentar os que o modelo tiver +@msg the template name can't be empty o nome do modelo não pode ficar vazio +@msg the template name isn't usable as a file name o nome do modelo não pode ser usado como nome de arquivo +@msg no metadata templates folder here não há pasta de modelos de metadados aqui +@msg give `name` or `path`, not both informe `name` ou `path`, não ambos +@msg give one of `path`, `name` and `data` informe um de `path`, `name` e `data` +@msg mode must be replace, keep or append o modo deve ser replace, keep ou append +@msg the file is not an XMP metadata template o arquivo não é um modelo de metadados XMP Copyright Notice: Aviso de Direitos Autorais: Copyright Status: Status de Direitos Autorais: Copyright Symbol Símbolo de Direitos Autorais diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 28db02bb34..51613c2520 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -652,6 +652,18 @@ font-technology Variable Вариативные Copy Width Point Копировать точку ширины Copyright Copyright Copyright Info URL: URL информации об авторских правах: + Save Metadata Template… Сохранить шаблон метаданных… + Import Options Параметры импорта + Clear existing fields and use the template's Очистить существующие поля и использовать поля шаблона + Keep existing fields, but replace those the template has Сохранить существующие поля, но заменить те, что есть в шаблоне + Keep existing fields, but append those the template has Сохранить существующие поля, но добавить те, что есть в шаблоне +@msg the template name can't be empty имя шаблона не может быть пустым +@msg the template name isn't usable as a file name имя шаблона нельзя использовать как имя файла +@msg no metadata templates folder here здесь нет папки шаблонов метаданных +@msg give `name` or `path`, not both укажите `name` или `path`, но не оба +@msg give one of `path`, `name` and `data` укажите один из параметров `path`, `name` и `data` +@msg mode must be replace, keep or append режим должен быть replace, keep или append +@msg the file is not an XMP metadata template файл не является шаблоном метаданных XMP Copyright Notice: Уведомление об авторских правах: Copyright Status: Статус авторских прав: Copyright Symbol Символ авторского права diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2f19e59397..4367f7a301 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -641,6 +641,18 @@ font-technology Variable Variabla Copy Width Point Kopiera breddpunkt Copyright Upphovsrätt Copyright Info URL: URL för upphovsrättsinformation: + Save Metadata Template… Spara metadatamall… + Import Options Importalternativ + Clear existing fields and use the template's Rensa befintliga fält och använd mallens + Keep existing fields, but replace those the template has Behåll befintliga fält, men ersätt dem som mallen har + Keep existing fields, but append those the template has Behåll befintliga fält, men lägg till dem som mallen har +@msg the template name can't be empty mallnamnet får inte vara tomt +@msg the template name isn't usable as a file name mallnamnet kan inte användas som filnamn +@msg no metadata templates folder here det finns ingen mapp för metadatamallar här +@msg give `name` or `path`, not both ange `name` eller `path`, inte båda +@msg give one of `path`, `name` and `data` ange en av `path`, `name` och `data` +@msg mode must be replace, keep or append läget måste vara replace, keep eller append +@msg the file is not an XMP metadata template filen är inte en XMP-metadatamall Copyright Notice: Upphovsrättsmeddelande: Copyright Status: Upphovsrättsstatus: Copyright Symbol Upphovsrättssymbol diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7639c326cb..fb1729e2a2 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -633,6 +633,18 @@ font-technology Variable Değişken Copy Width Point Genişlik Noktasını Kopyala Copyright Telif hakkı Copyright Info URL: Telif Hakkı Bilgisi URL'si: + Save Metadata Template… Meta Veri Şablonunu Kaydet… + Import Options İçe Aktarma Seçenekleri + Clear existing fields and use the template's Mevcut alanları temizle ve şablonunkileri kullan + Keep existing fields, but replace those the template has Mevcut alanları koru, ancak şablonda olanları değiştir + Keep existing fields, but append those the template has Mevcut alanları koru, ancak şablonda olanları ekle +@msg the template name can't be empty şablon adı boş olamaz +@msg the template name isn't usable as a file name şablon adı dosya adı olarak kullanılamaz +@msg no metadata templates folder here burada meta veri şablonları klasörü yok +@msg give `name` or `path`, not both `name` veya `path` verin, ikisini birden değil +@msg give one of `path`, `name` and `data` `path`, `name` ve `data` değerlerinden birini verin +@msg mode must be replace, keep or append mod replace, keep veya append olmalıdır +@msg the file is not an XMP metadata template dosya bir XMP meta veri şablonu değil Copyright Notice: Telif Hakkı Bildirimi: Copyright Status: Telif Hakkı Durumu: Copyright Symbol Telif Hakkı Sembolü diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b95631a14b..0552d08b33 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -648,6 +648,18 @@ font-technology Variable Варіативні Copy Width Point Копіювати точку ширини Copyright Авторські права Copyright Info URL: URL інформації про авторські права: + Save Metadata Template… Зберегти шаблон метаданих… + Import Options Параметри імпорту + Clear existing fields and use the template's Очистити наявні поля й використати поля шаблону + Keep existing fields, but replace those the template has Зберегти наявні поля, але замінити ті, що є в шаблоні + Keep existing fields, but append those the template has Зберегти наявні поля, але додати ті, що є в шаблоні +@msg the template name can't be empty назва шаблону не може бути порожньою +@msg the template name isn't usable as a file name назву шаблону не можна використати як назву файлу +@msg no metadata templates folder here тут немає папки шаблонів метаданих +@msg give `name` or `path`, not both укажіть `name` або `path`, але не обидва +@msg give one of `path`, `name` and `data` укажіть один із параметрів `path`, `name` і `data` +@msg mode must be replace, keep or append режим має бути replace, keep або append +@msg the file is not an XMP metadata template файл не є шаблоном метаданих XMP Copyright Notice: Повідомлення про авторські права: Copyright Status: Статус авторських прав: Copyright Symbol Символ авторського права diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3cc07d98cc..bfb9e27838 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -754,6 +754,18 @@ font-technology Variable Biến thiên Copy Width Point Sao chép điểm chiều rộng Copyright Bản quyền Copyright Info URL: URL thông tin bản quyền: + Save Metadata Template… Lưu mẫu siêu dữ liệu… + Import Options Tùy chọn nhập + Clear existing fields and use the template's Xóa các trường hiện có và dùng các trường của mẫu + Keep existing fields, but replace those the template has Giữ các trường hiện có, nhưng thay thế các trường mà mẫu có + Keep existing fields, but append those the template has Giữ các trường hiện có, nhưng nối thêm các trường mà mẫu có +@msg the template name can't be empty tên mẫu không được để trống +@msg the template name isn't usable as a file name không thể dùng tên mẫu làm tên tệp +@msg no metadata templates folder here không có thư mục mẫu siêu dữ liệu ở đây +@msg give `name` or `path`, not both hãy chỉ định `name` hoặc `path`, không phải cả hai +@msg give one of `path`, `name` and `data` hãy chỉ định một trong `path`, `name` và `data` +@msg mode must be replace, keep or append chế độ phải là replace, keep hoặc append +@msg the file is not an XMP metadata template tệp không phải là mẫu siêu dữ liệu XMP Copyright Notice: Thông báo bản quyền: Copyright Status: Trạng thái bản quyền: Copyright Symbol Ký hiệu bản quyền diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f96d93d9ea..61ef1410f1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -599,6 +599,18 @@ antiAlias Sharp 锐利 Copy Width Point 复制宽度点 Copyright 版权 Copyright Info URL: 版权信息 URL: + Save Metadata Template… 存储元数据模板… + Import Options 导入选项 + Clear existing fields and use the template's 清除现有字段并使用模板中的字段 + Keep existing fields, but replace those the template has 保留现有字段,但替换模板中包含的字段 + Keep existing fields, but append those the template has 保留现有字段,但追加模板中包含的字段 +@msg the template name can't be empty 模板名称不能为空 +@msg the template name isn't usable as a file name 模板名称不能用作文件名 +@msg no metadata templates folder here 此处没有元数据模板文件夹 +@msg give `name` or `path`, not both 请提供 `name` 或 `path`,不能同时提供 +@msg give one of `path`, `name` and `data` 请提供 `path`、`name` 和 `data` 中的一个 +@msg mode must be replace, keep or append 模式必须为 replace、keep 或 append +@msg the file is not an XMP metadata template 该文件不是 XMP 元数据模板 Copyright Notice: 版权声明: Copyright Status: 版权状态: Copyright Symbol 著作权符号 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6a962013ca..c3f2a0b650 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -616,6 +616,18 @@ font-technology Variable 可變 Copy Width Point 複製寬度點 Copyright 版權 Copyright Info URL: 著作權資訊網址: + Save Metadata Template… 儲存中繼資料範本… + Import Options 匯入選項 + Clear existing fields and use the template's 清除現有欄位並使用範本的欄位 + Keep existing fields, but replace those the template has 保留現有欄位,但取代範本中包含的欄位 + Keep existing fields, but append those the template has 保留現有欄位,但附加範本中包含的欄位 +@msg the template name can't be empty 範本名稱不能空白 +@msg the template name isn't usable as a file name 範本名稱無法用作檔案名稱 +@msg no metadata templates folder here 這裡沒有中繼資料範本資料夾 +@msg give `name` or `path`, not both 請提供 `name` 或 `path`,不可同時提供 +@msg give one of `path`, `name` and `data` 請提供 `path`、`name` 和 `data` 其中之一 +@msg mode must be replace, keep or append 模式必須是 replace、keep 或 append +@msg the file is not an XMP metadata template 這個檔案不是 XMP 中繼資料範本 Copyright Notice: 著作權聲明: Copyright Status: 著作權狀態: Copyright Symbol 著作權符號 diff --git a/docs/mcp.md b/docs/mcp.md index 2077793ba9..52a1982dc5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7658,6 +7658,34 @@ written unless the whole batch succeeds puts the saves and exports last, or runs {"name":"run_command","arguments":{"command":"file.info","params":{"author":"Ada","keywords":"poster, fair","rating":4,"copyrightStatus":"copyrighted","copyrightNotice":"© 2026 Ada"}}} ``` +A PDF, `.ai` or `.ait` also opens with the `authorTitle` and `rating` its XMP packet gives (`photoshop:AuthorsPosition`, +`xmp:Rating`, a whole number from 0 to 5). + +Metadata templates (the menu at the top of File Info: Save Metadata Template…, Import…, the saved templates and +Templates Folder; https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=278) keep File +Info fields in an XMP file. `file.info.saveTemplate {name?, path?, fields?}` writes the `title` (when it is not blank +or the `Untitled-N` name a new document gets), `author`, `authorTitle`, `description`, `keywords`, `rating` (from 1), `copyrightStatus`, +`copyrightNotice` and `copyrightUrl` that have a value as an XMP packet, using the properties listed above; the dates +are left out. `fields` takes `file.info`'s editable keys in place of the document's values. `name` saves into the +metadata templates folder as `.xmp` (the folder is made when it is missing; a name with characters file systems reject, a dot at either end, or a +device name such as `CON` is refused, and a template of the same name is replaced), `path` writes that file, and with +neither the reply's `data` is the packet; `name` and `path` together are refused. In the app the folder is +`Metadata Templates` in VectorCraft's settings folder; the web build has none. +`file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}` reads one template (a file, a template in the +folder, or the packet as text; at most 8 MB, more than any saved template holds) and merges it in one undo step, recording nothing when no field changes. +`mode` is VectorCraft's own name for the three ways: `replace` clears the fields a template can hold (not the title) +and takes the template's, `keep` keeps the fields and takes each one the template gives, and `append` keeps the fields, +adds the template's keywords and takes its other fields only where the field is empty. A value `file.info` would +refuse is left out. With `apply: false` nothing changes and the reply is the merged File Info, merged into `base` (the +fields as `file.info` takes them) when given; the File Info dialog uses this for Import. A missing or bad `mode`, a +file that is not XMP and a file over 8 MB are refused. `file.info.templates {create?}` lists the folder's `.xmp` files +(the first 1,000 by name) as `{name, file, path}`, with the `folder` where the caller's file access shows full +paths; `create: true` makes the folder first. `applyTemplate`'s `name` takes either a listed `name` or its `file`. + +```json +{"name":"run_command","arguments":{"command":"file.info.applyTemplate","params":{"name":"Studio","mode":"append"}}} +``` + ## Document Raster Effects Settings `document.rasterEffectsSettings` holds how raster effects (shadows, glows, blurs, feathers) become images when PDF diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 02b9f98f6e..5827336bdd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1939,6 +1939,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`). - PDF export and PDF-compatible `.ai` and `.ait` saves write File Info's copyright notice, URL and status to the XMP packet (`dc:rights`, `xmpRights:WebStatement`, `xmpRights:Marked`), so a PDF or `.ai` opened from its pages keeps them (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). - Opening a PDF or PDF-compatible `.ai` whose XMP packet nests elements more than 256 deep no longer overflows the stack: File Info leaves the packet out and takes the document information dictionary's values (`crates/pdf/src/tests/file_info.rs`). + - File Info has metadata templates: its menu saves the fields as an XMP file (Save Metadata Template…, into the Metadata Templates folder in the settings folder or anywhere), imports one with a choice of clearing the fields first, replacing the ones the template has, or appending to them (VectorCraft's own names for the three ways), lists the saved templates and opens Templates Folder; the import is one undo step (`file.info.saveTemplate`, `file.info.applyTemplate`, `file.info.templates`; `crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests/file_info.rs`, `crates/ui-egui/src/dialogs/file_info.rs`). A PDF or `.ai` also opens with the rating and author title its XMP packet gives. - `file.print`, `print.preview` and `print.setup` take a print preset by name (`preset`: `[Default]` or a saved preset, in any case): its settings are used instead of the document's, with `settings` over them, `print.setup` saves them with the document, and an unknown name is refused with the list of presets. - Print's Copies per Sheet (`copiesPerSheet`, `gutter`; off by default) prints as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, as one grid placed like a single copy; the preview shows them, and an artboard that does not fit prints one copy per sheet with a warning (#1283). - Place and the Links panel, Package (placed `.vectorcraft` documents packaged with their own linked files and fonts, relinked to the copies: #777), File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).