Import browser-picked File Info metadata templates

This commit is contained in:
dotCooCoo committed 2026-11-26 15:03:24 -08:00
1 parent 86d00a6b04
commit 630165a489
4 files changed
+81 -11

No files matched your search

+1 -1
View File
@@ -284,7 +284,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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)",
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text, dataBase64?: XMP bytes (exactly one source; 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
),
+14 -9
View File
@@ -213,7 +213,7 @@ enum Merge {
Append,
}
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?|dataBase64?, mode, apply?, base?}`.
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
let mode = match text_param(p, "mode", APPLY)? {
Some("replace") => Merge::Replace,
@@ -236,15 +236,14 @@ pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
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.
/// Reads one template source from `p` up to [`MAX_TEMPLATE_FILE`] bytes.
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?, text_param(p, "dataBase64", 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] => {
[Some(path), None, None, None] => read(path)?,
[None, Some(name), None, 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
@@ -268,9 +267,15 @@ fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
// 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`")),
[None, None, Some(data), None] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
[None, None, Some(data), None] => data.as_bytes().to_vec(),
[None, None, None, Some(data)] => {
if data.len() > MAX_TEMPLATE_FILE.div_ceil(3) * 4 {
return Err(too_big(APPLY));
}
vectorcraft_format::base64_decode(data).ok_or_else(|| bad(APPLY, "dataBase64 is not base64"))?
}
_ => return Err(bad(APPLY, "give one of `path`, `name`, `data` or `dataBase64`")),
};
if bytes.len() > MAX_TEMPLATE_FILE {
return Err(too_big(APPLY));
+5
View File
@@ -708,12 +708,17 @@ fn metadata_template_errors() {
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}");
let encoded = "A".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES.div_ceil(3) * 4 + 1);
let e = s.execute("file.info.applyTemplate", &json!({"dataBase64": encoded, "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!({"data": xmp, "dataBase64": "SGVsbG8=", "mode": "keep"}),
json!({"dataBase64": "!", "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"}),
+61 -1
View File
@@ -13,7 +13,7 @@
use std::path::PathBuf;
use craft::behavior::IconId;
use craft::host::{Host, PickId, PickKind, PickRequest};
use craft::host::{Host, PickId, PickKind, PickRequest, Picked};
use craft::theme::variant::Tone;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::choice::{Radio, RadioGroup, Rating};
@@ -111,6 +111,8 @@ enum Request {
Folder,
/// Save the fields as a template at the path the save pick answered.
SaveTo(PathBuf),
/// A browser picker returned a template larger than the import limit.
TemplateTooLarge,
/// Merge the template `source` into the fields as `mode` says.
Import { source: Info, mode: &'static str },
}
@@ -151,6 +153,15 @@ impl Templates {
&& let Some(answer) = cx.take_pick_answer(id)
{
self.ticket = None;
if let (Pick::Open, Picked::Contents(files)) = (kind, &answer) {
let Some((_, bytes)) = files.first() else { return };
if bytes.len() > vectorcraft_pdf::MAX_TEMPLATE_BYTES {
self.requests.push(Request::TemplateTooLarge);
} else {
*import = Some(source("dataBase64", vectorcraft_format::base64_encode(bytes)));
}
return;
}
let Some(path) = answer.first_path() else { return };
match kind {
Pick::Open => *import = Some(source("path", path.to_string_lossy().into_owned())),
@@ -602,6 +613,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Some(fields) => save_template(app, path, fields),
None => Ok(()),
},
Request::TemplateTooLarge => Err(tl!("The metadata template is larger than 8 MB.").to_owned()),
Request::Import { source, mode } => {
dialogs.with(|host| host.get_mut_by_id::<FileInfoDialog>(id).map(|d| import(app, d, source, mode))).unwrap_or(Ok(()))
}
@@ -767,6 +779,54 @@ mod tests {
assert_eq!(st.history.undo.len(), 1);
}
#[test]
fn browser_picked_templates_enter_the_merge_choice_and_edit_only_the_draft() {
use std::sync::Arc;
use craft::host::{Files, PickRequest, Picked, ScriptedFiles};
let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo {
description: Some("À l’affiche 版".into()),
rating: Some(3),
..Default::default()
});
let utf16 = std::iter::once(0xfeff).chain(template.encode_utf16()).flat_map(u16::to_le_bytes).collect::<Vec<_>>();
for bytes in [template.into_bytes(), utf16] {
let mut app = windowed();
let files = Arc::new(ScriptedFiles::held());
crate::tests::picks::install_files(&mut app, files.clone());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("ui.fileInfoDialog", json!({})).unwrap();
set(&app, "author", json!("Ada")).unwrap();
let ticket = files.pick(PickRequest::open(super::PURPOSE));
with_dialog(&app, |d| d.templates.ticket = Some((ticket, super::Pick::Open))).unwrap();
assert!(files.answer(Picked::Contents(vec![("Studio.xmp".into(), bytes)])).is_some());
let ctx = app.ui_ctx.clone().unwrap();
for _ in 0..3 {
crate::tests::synthetic::key_frame(&mut app, &ctx, Vec::new());
}
with_dialog(&app, |d| {
assert!(d.templates.ticket.is_none(), "the File Info form consumed the picker answer");
assert!(d.import.is_some(), "a browser-selected template reaches the merge choice");
assert!(super::choose_mode(&mut d.import_mode, "append"));
super::ask_import(&mut d.templates, &d.import, d.import_mode);
})
.unwrap();
super::pump(&mut app, &ctx);
let fields = with_dialog(&app, |d| d.filed_fields()).unwrap();
assert_eq!(
(fields["author"].clone(), fields["description"].clone(), fields["rating"].clone()),
(json!("Ada"), json!("À l’affiche 版"), json!(3))
);
assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "the template updates the draft before OK");
assert!(press_ok(&mut app));
let st = app.session.active().unwrap();
assert_eq!(st.doc.metadata.description, "À l’affiche 版");
assert_eq!(st.history.undo.len(), 1);
}
}
#[test]
fn ok_waits_for_the_merge_choice_of_a_template_being_imported() {
let mut app = windowed();