From 660be841ca718be7d8b748ffae3e6ceddebb313f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:30:04 -0700 Subject: [PATCH] LRC-PRINT-TEMPLATES: the Template Browser has folders, and a template can be dragged into one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Print dialog's templates are listed in folders: User Templates, which always exists, and folders made with New Folder… (a button beside Save, or a folder's context menu). Each folder opens and closes. Save and Import… put a template in the folder chosen beside them, and a template dragged onto a folder, or moved with its Move to Folder menu, moves there with its name and settings unchanged. Rename Folder… and Delete Folder work on every folder but User Templates. Deleting a folder asks first and moves its templates to User Templates. New commands: print.template.move and print.template.folder.create, rename and delete. print.template.list gives the folders and each template's folder; print.template.save and print.template.import take an optional folder. A save over an existing name keeps its folder unless one is given. Folders, empty ones included, are kept in the library's prefs.json; templates saved before are in User Templates, and .lcprint files stay version 1 without the folder. --- crates/engine/src/cmd/print.rs | 188 ++++++++++++-- crates/engine/src/lib.rs | 4 + crates/engine/src/library.rs | 5 + crates/engine/src/print/template.rs | 61 ++++- crates/engine/src/tests/print.rs | 183 +++++++++++++- crates/ui-egui/locales/cs-formats.json | 1 + crates/ui-egui/locales/cs.json | 6 +- crates/ui-egui/locales/de-formats.json | 1 + crates/ui-egui/locales/de.json | 6 +- crates/ui-egui/locales/es-formats.json | 1 + crates/ui-egui/locales/es.json | 6 +- crates/ui-egui/locales/fi-formats.json | 1 + crates/ui-egui/locales/fi.json | 6 +- crates/ui-egui/locales/fr-formats.json | 1 + crates/ui-egui/locales/fr.json | 6 +- crates/ui-egui/locales/id-formats.json | 1 + crates/ui-egui/locales/id.json | 6 +- crates/ui-egui/locales/it-formats.json | 1 + crates/ui-egui/locales/it.json | 6 +- crates/ui-egui/locales/ja-formats.json | 1 + crates/ui-egui/locales/ja.json | 6 +- crates/ui-egui/locales/ka-formats.json | 1 + crates/ui-egui/locales/ka.json | 6 +- crates/ui-egui/locales/pl-formats.json | 1 + crates/ui-egui/locales/pl.json | 6 +- crates/ui-egui/locales/pt-br-formats.json | 1 + crates/ui-egui/locales/pt-br.json | 6 +- crates/ui-egui/locales/ru-formats.json | 1 + crates/ui-egui/locales/ru.json | 6 +- crates/ui-egui/locales/sv-formats.json | 1 + crates/ui-egui/locales/sv.json | 6 +- crates/ui-egui/locales/uk-formats.json | 1 + crates/ui-egui/locales/uk.json | 6 +- crates/ui-egui/locales/vi-formats.json | 1 + crates/ui-egui/locales/vi.json | 6 +- crates/ui-egui/locales/zh-hans-formats.json | 1 + crates/ui-egui/locales/zh-hans.json | 6 +- crates/ui-egui/locales/zh-hant-formats.json | 1 + crates/ui-egui/locales/zh-hant.json | 6 +- crates/ui-egui/src/dialogs/print_view.rs | 263 +++++++++++++++++++- crates/ui-egui/src/tests/print.rs | 121 +++++++++ docs/parity-checklist.md | 3 +- 42 files changed, 902 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 1390ca1677..e9e8a9cbff 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -8,12 +8,15 @@ //! * `print.get`, `print.set {layout?, image?, page?, guides?, job?}`, `print.reset` //! * `print.cell.add|move|resize|delete|stack|photo|page`, `print.layout.autoLayout|newPage|clear` //! * `print.exportPdf {path, ids?}` -//! * `print.template.list|save|apply|delete`, `print.template.export|import` (`.lcprint` files) +//! * `print.template.list|save|apply|delete|move`, `print.template.export|import` (`.lcprint` files) +//! * `print.template.folder.create|rename|delete`: the Template Browser's folders use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, f64_req}; use crate::print::layout::{Layout, MAX_PAGES, Rect, Snap, Stack, paper_names, paper_size}; -use crate::print::template::{FILE_EXT, MAX_FILE, MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_name, unique_name}; +use crate::print::template::{ + DEFAULT_FOLDER, FILE_EXT, MAX_FILE, MAX_FOLDERS, MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_folder, clean_name, sort_folders, unique_name, +}; use crate::{Result, Session}; fn rect_json(r: &Rect) -> Value { @@ -270,18 +273,65 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { // ---- templates ------------------------------------------------------------------------------ fn template_list(s: &Session) -> Value { - json!({"templates": s.print_templates.iter().map(|t| json!({"name": t.name, "style": t.settings.pointer("/layout/style"), "settings": t.settings})).collect::>()}) + let count = |f: Option<&str>| s.print_templates.iter().filter(|t| t.folder.as_deref() == f).count(); + let folders = std::iter::once(json!({"name": DEFAULT_FOLDER, "default": true, "templates": count(None)})) + .chain(s.print_template_folders.iter().map(|f| json!({"name": f, "default": false, "templates": count(Some(f))}))); + json!({ + "folders": folders.collect::>(), + "templates": s.print_templates.iter().map(|t| json!({ + "name": t.name, + "folder": t.folder.as_deref().unwrap_or(DEFAULT_FOLDER), + "style": t.settings.pointer("/layout/style"), + "settings": t.settings, + })).collect::>(), + }) } fn template_name(p: &Value, id: &str) -> Result { clean_name(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(id, "missing `name`"))?).map_err(|e| bad(id, e)) } -/// Save the preferences after a change to the templates; if that fails, the templates go back to -/// `before`, so the list matches what is saved and a retry does the same thing. -fn save_templates(s: &mut Session, before: Vec) -> Result<()> { +/// The folder `name` names: `None` for [`DEFAULT_FOLDER`], else the listed folder's spelling. +fn find_folder(s: &Session, name: &str, id: &str) -> Result> { + let name = name.trim(); + if name.eq_ignore_ascii_case(DEFAULT_FOLDER) { + return Ok(None); + } + s.print_template_folders + .iter() + .find(|f| f.eq_ignore_ascii_case(name)) + .cloned() + .map(Some) + .ok_or_else(|| bad(id, format!("no print template folder `{name}` (see print.template.list)"))) +} + +/// The `folder` parameter: not given (`None`), or the folder it names (see [`find_folder`]). +fn folder_param(s: &Session, p: &Value, id: &str) -> Result>> { + match p.get("folder") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(f)) => find_folder(s, f, id).map(Some), + Some(_) => Err(bad(id, "`folder` must be a folder name")), + } +} + +/// A user folder named by `key`: the listed folder's spelling. [`DEFAULT_FOLDER`] is refused. +fn user_folder(s: &Session, p: &Value, key: &str, id: &str) -> Result { + let name = p.get(key).and_then(Value::as_str).ok_or_else(|| bad(id, format!("missing `{key}`")))?; + find_folder(s, name, id)?.ok_or_else(|| bad(id, format!("“{DEFAULT_FOLDER}” can't be renamed or deleted"))) +} + +/// The templates and folders before a change, put back by [`save_templates`] when it fails. +type Before = (Vec, Vec); + +fn before(s: &Session) -> Before { + (s.print_templates.clone(), s.print_template_folders.clone()) +} + +/// Save the preferences after a change to the templates or folders; if that fails, both go back +/// to `before`, so the list matches what is saved and a retry does the same thing. +fn save_templates(s: &mut Session, before: Before) -> Result<()> { if let Err(e) = s.save_prefs() { - s.print_templates = before; + (s.print_templates, s.print_template_folders) = before; return Err(e); } Ok(()) @@ -290,14 +340,20 @@ fn save_templates(s: &mut Session, before: Vec) -> Result<()> { fn template_save(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.save"; let name = template_name(p, ID)?; - let t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?; - let before = s.print_templates.clone(); + let folder = folder_param(s, p, ID)?; + let mut t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?; + let before = before(s); match s.print_templates.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) { - Some(x) => *x = t, + Some(x) => { + // a replaced template stays in its folder unless the call names another + t.folder = folder.unwrap_or_else(|| x.folder.clone()); + *x = t; + } None => { if s.print_templates.len() >= MAX_TEMPLATES { return Err(bad(ID, format!("at most {MAX_TEMPLATES} templates; delete one first"))); } + t.folder = folder.flatten(); s.print_templates.push(t); } } @@ -305,6 +361,90 @@ fn template_save(s: &mut Session, p: &Value) -> Result { Ok(template_list(s)) } +fn template_move(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.move"; + let name = template_name(p, ID)?; + let folder = folder_param(s, p, ID)?.ok_or_else(|| bad(ID, "missing `folder`"))?; + let i = s + .print_templates + .iter() + .position(|x| x.name.eq_ignore_ascii_case(&name)) + .ok_or_else(|| bad(ID, format!("no print template `{name}` (see print.template.list)")))?; + let moved = s.print_templates.get(i).is_some_and(|t| t.folder != folder); + if moved { + let before = before(s); + if let Some(t) = s.print_templates.get_mut(i) { + t.folder = folder; + } + save_templates(s, before)?; + } + let mut out = template_list(s); + out["moved"] = json!(moved); + Ok(out) +} + +fn folder_create(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.folder.create"; + let name = clean_folder(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(ID, "missing `name`"))?).map_err(|e| bad(ID, e))?; + if s.print_template_folders.iter().any(|f| f.eq_ignore_ascii_case(&name)) { + return Err(bad(ID, format!("there is already a folder named “{name}”"))); + } + if s.print_template_folders.len() >= MAX_FOLDERS { + return Err(bad(ID, format!("at most {MAX_FOLDERS} folders; delete one first"))); + } + let before = before(s); + s.print_template_folders.push(name.clone()); + sort_folders(&mut s.print_template_folders); + save_templates(s, before)?; + let mut out = template_list(s); + out["name"] = json!(name); + Ok(out) +} + +fn folder_rename(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.folder.rename"; + let from = user_folder(s, p, "name", ID)?; + let to = clean_folder(p.get("to").and_then(Value::as_str).ok_or_else(|| bad(ID, "missing `to`"))?).map_err(|e| bad(ID, e))?; + if s.print_template_folders.iter().any(|f| f.eq_ignore_ascii_case(&to) && *f != from) { + return Err(bad(ID, format!("there is already a folder named “{to}”"))); + } + let before = before(s); + for f in &mut s.print_template_folders { + if *f == from { + f.clone_from(&to); + } + } + for t in &mut s.print_templates { + if t.folder.as_deref() == Some(from.as_str()) { + t.folder = Some(to.clone()); + } + } + sort_folders(&mut s.print_template_folders); + save_templates(s, before)?; + let mut out = template_list(s); + out["name"] = json!(to); + Ok(out) +} + +fn folder_delete(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.folder.delete"; + let name = user_folder(s, p, "name", ID)?; + let before = before(s); + s.print_template_folders.retain(|f| *f != name); + let mut moved = 0usize; + for t in &mut s.print_templates { + if t.folder.as_deref() == Some(name.as_str()) { + t.folder = None; + moved += 1; + } + } + save_templates(s, before)?; + let mut out = template_list(s); + out["deleted"] = json!(name); + out["moved"] = json!(moved); + Ok(out) +} + fn template_apply(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.apply"; let name = template_name(p, ID)?; @@ -320,9 +460,9 @@ fn template_apply(s: &mut Session, p: &Value) -> Result { fn template_delete(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.delete"; let name = template_name(p, ID)?; - let before = s.print_templates.clone(); + let before = before(s); s.print_templates.retain(|x| !x.name.eq_ignore_ascii_case(&name)); - if s.print_templates.len() == before.len() { + if s.print_templates.len() == before.0.len() { return Err(bad(ID, format!("no print template `{name}`"))); } save_templates(s, before)?; @@ -356,6 +496,7 @@ fn template_export(s: &mut Session, p: &Value) -> Result { fn template_import(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.import"; let path = std::path::Path::new(template_path(p, ID)?); + let folder = folder_param(s, p, ID)?.flatten(); let meta = std::fs::metadata(path).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?; if !meta.is_file() { return Err(bad(ID, format!("{}: not a file", path.display()))); @@ -371,7 +512,8 @@ fn template_import(s: &mut Session, p: &Value) -> Result { let name = unique_name(&t.name, &s.print_templates); let renamed = name != t.name; t.name = name.clone(); - let before = s.print_templates.clone(); + t.folder = folder; + let before = before(s); s.print_templates.push(t); save_templates(s, before)?; let mut out = template_list(s); @@ -405,17 +547,31 @@ pub fn specs() -> Vec { cmd!(query "print.exportPdf", "Print to PDF", [], None, "{path, ids?: photo ids (default selection)} → {path, pages, photos, bytes}; prints the current print.get settings; replaces an existing output, never an original", always, export_pdf), - cmd!(query "print.template.list", "Print Templates", [], None, "{} → {templates: [{name, style, settings}]}", always, |s, _| Ok(template_list(s))), + cmd!(query "print.template.list", "Print Templates", [], None, + "{} → {folders: [{name, default, templates: count}] (\"User Templates\" first, then the others by name), templates: [{name, folder, style, settings}]}", + always, |s, _| Ok(template_list(s))), cmd!(query "print.template.save", "Save Print Template", [], None, - "{name} — saves the layout, image settings, page and job (not the cells' photos or the guides); an existing name (any case) is replaced → print.template.list", + "{name, folder?} — saves the layout, image settings, page and job (not the cells' photos or the guides) in `folder` (default \"User Templates\"); an existing name (any case) is replaced and stays in its folder unless `folder` is given → print.template.list", always, template_save), cmd!(query "print.template.apply", "Apply Print Template", [], None, "{name} → print.get", always, template_apply), cmd!(query "print.template.delete", "Delete Print Template", [], None, "{name} → print.template.list", always, template_delete), + cmd!(query "print.template.move", "Move Print Template to Folder", [], None, + "{name, folder} — lists the template in another Template Browser folder (\"User Templates\" or one made with print.template.folder.create); its name and settings stay → print.template.list + {moved: false when it was already there}", + always, template_move), + cmd!(query "print.template.folder.create", "New Print Template Folder", [], None, + "{name} — a Template Browser folder (1 to 80 characters, not \"User Templates\", unique in any case, at most 100); kept while empty → print.template.list + {name}", + always, folder_create), + cmd!(query "print.template.folder.rename", "Rename Print Template Folder", [], None, + "{name, to} — renames a folder and keeps its templates in it; \"User Templates\" can't be renamed → print.template.list + {name}", + always, folder_rename), + cmd!(query "print.template.folder.delete", "Delete Print Template Folder", [], None, + "{name} — deletes a folder; its templates move to \"User Templates\", which can't be deleted → print.template.list + {deleted, moved: templates moved}", + always, folder_delete), cmd!(query "print.template.export", "Export Print Template", [], None, "{name, path}: writes the template as a .lcprint JSON file ({format, version, name, settings}; `.lcprint` is added when the path has no extension); replaces an existing file, never an original → {name, path}", always, template_export), cmd!(query "print.template.import", "Import Print Template", [], None, - "{path: a .lcprint file (at most 256 KB)}: checked like a saved template (format, version, name, every setting; cell photos and guides are dropped) and added under its name; a name taken (any case) gets \" (2)\"… → print.template.list + {name, renamed}", + "{path: a .lcprint file (at most 256 KB), folder? (default \"User Templates\")}: checked like a saved template (format, version, name, every setting; cell photos and guides are dropped) and added under its name; a name taken (any case) gets \" (2)\"… → print.template.list + {name, renamed}", always, template_import), ] } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 163a102680..3135cc1dfc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -346,6 +346,9 @@ pub struct Session { pub print: print::template::PrintSettings, /// Saved print templates (`print.template.*`), persisted in prefs.json. pub print_templates: Vec, + /// The Template Browser's folders besides [`print::template::DEFAULT_FOLDER`], sorted by name + /// (`print.template.folder.*`), persisted in prefs.json. + pub print_template_folders: Vec, /// Metadata presets (`metadata.*`), persisted in prefs.json. pub metadata_presets: Vec, /// Saved filter-bar settings (`filter.*`), persisted in prefs.json. @@ -507,6 +510,7 @@ impl Session { export_presets: Vec::new(), print: Default::default(), print_templates: Vec::new(), + print_template_folders: Vec::new(), metadata_presets: Vec::new(), filter_presets: Vec::new(), curve_presets: Vec::new(), diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index caf51a0ab6..3535e6a464 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -263,6 +263,8 @@ struct PrefsFile { export_presets: Vec, /// Print templates. print_templates: Vec, + /// Print Template Browser folders, empty ones included. + print_template_folders: Vec, /// Metadata presets. metadata_presets: Vec, /// Filter presets. @@ -547,6 +549,8 @@ impl Session { self.last_merge = prefs.last_merge; self.export_presets = prefs.export_presets; self.print_templates = prefs.print_templates; + self.print_template_folders = prefs.print_template_folders; + crate::print::template::tidy_folders(&mut self.print_template_folders, &mut self.print_templates); self.metadata_presets = prefs.metadata_presets; self.filter_presets = prefs.filter_presets; self.curve_presets = prefs.curve_presets; @@ -827,6 +831,7 @@ impl Session { last_merge: self.last_merge.clone(), export_presets: self.export_presets.clone(), print_templates: self.print_templates.clone(), + print_template_folders: self.print_template_folders.clone(), metadata_presets: self.metadata_presets.clone(), filter_presets: self.filter_presets.clone(), curve_presets: self.curve_presets.clone(), diff --git a/crates/engine/src/print/template.rs b/crates/engine/src/print/template.rs index 7bb5336129..6a98aec5ad 100644 --- a/crates/engine/src/print/template.rs +++ b/crates/engine/src/print/template.rs @@ -38,6 +38,11 @@ const FILE_FORMAT: &str = "lightcraft.printTemplate"; const FILE_VERSION: u64 = 1; /// Largest template file read, bytes. pub const MAX_FILE: u64 = 256 * 1024; +/// The Template Browser folder a template is in until it is moved to another. It always exists +/// and can't be renamed or deleted. +pub const DEFAULT_FOLDER: &str = "User Templates"; +/// Most Template Browser folders kept, besides [`DEFAULT_FOLDER`]. +pub const MAX_FOLDERS: usize = 100; /// A saved print template: the layout, image settings, page and job of a print, without the /// photos assigned to cells and without the guides (a view preference). The settings are kept as @@ -47,9 +52,59 @@ pub const MAX_FILE: u64 = 256 * 1024; #[serde(rename_all = "camelCase")] pub struct PrintTemplate { pub name: String, + /// The Template Browser folder the template is listed in; `None`: [`DEFAULT_FOLDER`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folder: Option, pub settings: serde_json::Value, } +/// A folder name: trimmed, 1 to [`MAX_NAME`] characters, no control characters, and not +/// [`DEFAULT_FOLDER`] in any case. +pub fn clean_folder(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() || name.chars().count() > MAX_NAME || name.chars().any(char::is_control) { + return Err(format!("a folder name is 1 to {MAX_NAME} characters without control characters")); + } + if name.eq_ignore_ascii_case(DEFAULT_FOLDER) { + return Err(format!("“{DEFAULT_FOLDER}” is always there; choose another name")); + } + Ok(name.to_string()) +} + +/// Sorts `folders` by name, ignoring case. +pub fn sort_folders(folders: &mut [String]) { + folders.sort_by_cached_key(|f| f.to_lowercase()); +} + +/// Makes folders and templates read from the preferences consistent: folders with a bad, reserved +/// or repeated name and those past [`MAX_FOLDERS`] are dropped; a template in a folder that isn't +/// listed gets the folder listed when its name is good and there is room, and goes to +/// [`DEFAULT_FOLDER`] otherwise; each template's folder takes the listed folder's spelling. +pub fn tidy_folders(folders: &mut Vec, templates: &mut [PrintTemplate]) { + let mut kept: Vec = Vec::new(); + for f in folders.iter() { + if let Ok(f) = clean_folder(f) + && kept.len() < MAX_FOLDERS + && !kept.iter().any(|k| k.eq_ignore_ascii_case(&f)) + { + kept.push(f); + } + } + for t in templates.iter_mut() { + let Some(f) = t.folder.take() else { continue }; + if let Some(k) = kept.iter().find(|k| k.eq_ignore_ascii_case(f.trim())) { + t.folder = Some(k.clone()); + } else if let Ok(f) = clean_folder(&f) + && kept.len() < MAX_FOLDERS + { + kept.push(f.clone()); + t.folder = Some(f); + } + } + sort_folders(&mut kept); + *folders = kept; +} + /// A template name: trimmed, 1 to [`MAX_NAME`] characters, no control characters. pub fn clean_name(name: &str) -> Result { let name = name.trim(); @@ -71,7 +126,7 @@ impl PrintTemplate { if let Some(o) = value.as_object_mut() { o.remove("guides"); } - Ok(Self { name: clean_name(name)?, settings: value }) + Ok(Self { name: clean_name(name)?, folder: None, settings: value }) } /// The settings, checked: unknown fields, hostile numbers and inconsistent layouts are errors. @@ -106,7 +161,7 @@ impl PrintTemplate { } let name = clean_name(v.get("name").and_then(serde_json::Value::as_str).ok_or("a print template file needs a `name`")?)?; let settings = v.get("settings").cloned().ok_or("a print template file needs `settings`")?; - let checked = PrintTemplate { name: name.clone(), settings }.settings(&Guides::default())?; + let checked = PrintTemplate { name: name.clone(), folder: None, settings }.settings(&Guides::default())?; Self::new(&name, &checked) } } @@ -163,7 +218,7 @@ mod tests { for name in ["", " ", "a\nb", &"x".repeat(MAX_NAME + 1)] { assert!(PrintTemplate::new(name, &PrintSettings::default()).is_err(), "{name:?}"); } - let bad = |v: serde_json::Value| PrintTemplate { name: "t".into(), settings: v }.settings(&Guides::default()).is_err(); + let bad = |v: serde_json::Value| PrintTemplate { name: "t".into(), folder: None, settings: v }.settings(&Guides::default()).is_err(); assert!(bad(json!("text"))); assert!(bad(json!({"surprise": 1}))); assert!(bad(json!({"job": {"ppi": 1e30}}))); diff --git a/crates/engine/src/tests/print.rs b/crates/engine/src/tests/print.rs index 5a35adb5ba..e663b62e80 100644 --- a/crates/engine/src/tests/print.rs +++ b/crates/engine/src/tests/print.rs @@ -410,6 +410,173 @@ fn templates_export_to_a_file_and_import_from_one() { assert!(fails(&mut s, "print.template.import", json!({"path": file.to_string_lossy()})).contains("at most")); } +/// The names of the folders `print.template.list` gives, User Templates first. +fn folder_names(r: &Value) -> Vec { + r["folders"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap().to_string()).collect() +} + +/// Each template's name and folder, in the order `print.template.list` gives them. +fn template_folders(r: &Value) -> Vec<(String, String)> { + r["templates"].as_array().unwrap().iter().map(|t| (t["name"].as_str().unwrap().into(), t["folder"].as_str().unwrap().into())).collect() +} + +fn pair(name: &str, folder: &str) -> (String, String) { + (name.into(), folder.into()) +} + +#[test] +fn template_folders_hold_templates_and_survive_reopening() { + let files = MemStore::new(); + let open = |files: &MemStore| { + let mut s = Session::with_demo(); + let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + s + }; + let mut s = open(&files); + let r = run(&mut s, "print.template.list", json!({})); + assert_eq!(r["folders"], json!([{"name": "User Templates", "default": true, "templates": 0}])); + + // a folder is kept while it is empty, and the folders are listed by name after User Templates + let r = run(&mut s, "print.template.folder.create", json!({"name": " Weddings "})); + assert_eq!(r["name"], "Weddings"); + run(&mut s, "print.template.folder.create", json!({"name": "Proofs"})); + let r = run(&mut open(&files), "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "Proofs", "Weddings"], "{r}"); + + // a template is saved into a folder, or into User Templates when none is named + run(&mut s, "print.set", json!({"layout": {"style": "contactSheet", "grid": {"columns": 4, "rows": 5}}})); + run(&mut s, "print.template.save", json!({"name": "Sheet", "folder": "weddings"})); + let r = run(&mut s, "print.template.save", json!({"name": "Plain"})); + assert_eq!(template_folders(&r), [pair("Sheet", "Weddings"), pair("Plain", "User Templates")]); + assert_eq!(r["folders"][2], json!({"name": "Weddings", "default": false, "templates": 1})); + // saving over a name keeps its folder unless the call names another + run(&mut s, "print.set", json!({"layout": {"grid": {"columns": 6}}})); + let r = run(&mut s, "print.template.save", json!({"name": "sheet"})); + assert_eq!(template_folders(&r), [pair("sheet", "Weddings"), pair("Plain", "User Templates")]); + let r = run(&mut s, "print.template.save", json!({"name": "Plain", "folder": "Proofs"})); + assert_eq!(template_folders(&r)[1], pair("Plain", "Proofs")); + + // a move changes only the folder; a move to where it is already does nothing + let settings = r["templates"][0]["settings"].clone(); + let r = run(&mut s, "print.template.move", json!({"name": "SHEET", "folder": "Proofs"})); + assert_eq!((r["moved"].as_bool(), template_folders(&r)[0].clone()), (Some(true), pair("sheet", "Proofs"))); + assert_eq!(r["templates"][0]["settings"], settings); + let r = run(&mut s, "print.template.move", json!({"name": "Sheet", "folder": "proofs"})); + assert_eq!(r["moved"], false); + let r = run(&mut s, "print.template.move", json!({"name": "Plain", "folder": "user templates"})); + assert_eq!(template_folders(&r)[1], pair("Plain", "User Templates")); + run(&mut s, "print.template.move", json!({"name": "Plain", "folder": "Weddings"})); + + // a rename takes the folder's templates along; a change of case is a rename too + let r = run(&mut s, "print.template.folder.rename", json!({"name": "proofs", "to": "Contact Sheets"})); + assert_eq!(folder_names(&r), ["User Templates", "Contact Sheets", "Weddings"]); + assert_eq!(template_folders(&r)[0], pair("sheet", "Contact Sheets")); + let r = run(&mut s, "print.template.folder.rename", json!({"name": "contact sheets", "to": "contact sheets"})); + assert_eq!(template_folders(&r)[0], pair("sheet", "contact sheets")); + + // the folders and where each template is survive reopening the library + let mut again = open(&files); + let r = run(&mut again, "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "contact sheets", "Weddings"]); + assert_eq!(template_folders(&r), [pair("sheet", "contact sheets"), pair("Plain", "Weddings")]); + run(&mut again, "print.template.apply", json!({"name": "Sheet"})); + assert_eq!(again.print.layout.grid.columns, 6); + + // deleting a folder keeps its templates: they go to User Templates + let r = run(&mut s, "print.template.folder.delete", json!({"name": "WEDDINGS"})); + assert_eq!((r["deleted"].as_str(), r["moved"].as_u64()), (Some("Weddings"), Some(1))); + assert_eq!(folder_names(&r), ["User Templates", "contact sheets"]); + assert_eq!(template_folders(&r), [pair("sheet", "contact sheets"), pair("Plain", "User Templates")]); + let r = run(&mut open(&files), "print.template.list", json!({})); + assert_eq!(template_folders(&r)[1], pair("Plain", "User Templates")); + + // refusals change nothing + let before = run(&mut s, "print.template.list", json!({})); + for (id, p, why) in [ + ("print.template.folder.create", json!({}), "missing `name`"), + ("print.template.folder.create", json!({"name": " "}), "folder name"), + ("print.template.folder.create", json!({"name": "a\tb"}), "folder name"), + ("print.template.folder.create", json!({"name": "x".repeat(81)}), "folder name"), + ("print.template.folder.create", json!({"name": "user templates"}), "always there"), + ("print.template.folder.create", json!({"name": "Contact Sheets"}), "already a folder"), + ("print.template.folder.rename", json!({"name": "User Templates", "to": "Mine"}), "can't be renamed"), + ("print.template.folder.rename", json!({"name": "Nope", "to": "Mine"}), "no print template folder"), + ("print.template.folder.rename", json!({"name": "contact sheets"}), "missing `to`"), + ("print.template.folder.rename", json!({"name": "contact sheets", "to": "User Templates"}), "always there"), + ("print.template.folder.delete", json!({"name": "User Templates"}), "can't be renamed or deleted"), + ("print.template.folder.delete", json!({"name": "Nope"}), "no print template folder"), + ("print.template.move", json!({"name": "Sheet"}), "missing `folder`"), + ("print.template.move", json!({"name": "Sheet", "folder": "Nope"}), "no print template folder"), + ("print.template.move", json!({"name": "Sheet", "folder": 3}), "`folder` must be"), + ("print.template.move", json!({"name": "Nope", "folder": "User Templates"}), "no print template `Nope`"), + ("print.template.save", json!({"name": "New", "folder": "Nope"}), "no print template folder"), + ("print.template.import", json!({"path": "x.lcprint", "folder": "Nope"}), "no print template folder"), + ] { + let e = fails(&mut s, id, p.clone()); + assert!(e.contains(why), "{id} {p}: {e}"); + } + run(&mut s, "print.template.folder.create", json!({"name": "Second"})); + assert!(fails(&mut s, "print.template.folder.rename", json!({"name": "second", "to": "CONTACT SHEETS"})).contains("already a folder")); + run(&mut s, "print.template.folder.delete", json!({"name": "Second"})); + assert_eq!(run(&mut s, "print.template.list", json!({})), before); + + // a full list of folders takes no more + while s.print_template_folders.len() < crate::print::template::MAX_FOLDERS { + let n = s.print_template_folders.len(); + run(&mut s, "print.template.folder.create", json!({"name": format!("F{n}")})); + } + assert!(fails(&mut s, "print.template.folder.create", json!({"name": "One more"})).contains("at most")); +} + +#[test] +fn templates_import_into_a_folder_and_export_without_it() { + let mut s = Session::with_demo(); + let scratch = Scratch::new("folders"); + let file = scratch.0.join("proofs.lcprint"); + run(&mut s, "print.template.folder.create", json!({"name": "Proofs"})); + run(&mut s, "print.template.save", json!({"name": "Sheet", "folder": "Proofs"})); + run(&mut s, "print.template.export", json!({"name": "Sheet", "path": file.to_string_lossy()})); + let doc: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let mut keys: Vec<&String> = doc.as_object().unwrap().keys().collect(); + keys.sort(); + assert_eq!(keys, ["format", "name", "settings", "version"], "a .lcprint file stays version 1, without the folder"); + let r = run(&mut s, "print.template.import", json!({"path": file.to_string_lossy()})); + assert_eq!(template_folders(&r)[1], pair("Sheet (2)", "User Templates")); + let r = run(&mut s, "print.template.import", json!({"path": file.to_string_lossy(), "folder": "proofs"})); + assert_eq!(template_folders(&r)[2], pair("Sheet (3)", "Proofs")); +} + +#[test] +fn templates_from_before_folders_are_in_user_templates() { + let files = MemStore::new(); + let old = json!({"printTemplates": [ + {"name": "Old", "settings": {"layout": {"style": "contactSheet"}}}, + {"name": "Kept", "folder": "Family", "settings": {}}, + {"name": "Spelled", "folder": " family ", "settings": {}}, + {"name": "Bad", "folder": "a\nb", "settings": {}}, + {"name": "Reserved", "folder": "USER TEMPLATES", "settings": {}} + ], "printTemplateFolders": ["Empty", "", "empty", "User Templates", "Family"]}); + files.set("prefs.json", serde_json::to_vec(&old).unwrap()); + let mut s = Session::with_demo(); + let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + assert!(s.take_library_warnings().is_empty()); + let r = run(&mut s, "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "Empty", "Family"]); + assert_eq!( + template_folders(&r), + [ + pair("Old", "User Templates"), + pair("Kept", "Family"), + pair("Spelled", "Family"), + pair("Bad", "User Templates"), + pair("Reserved", "User Templates") + ] + ); + run(&mut s, "print.template.apply", json!({"name": "Old"})); +} + /// A library whose `prefs.json` can't be read, so saving the preferences fails. #[derive(Clone, Default)] struct PrefsUnreadable(MemStore); @@ -442,7 +609,13 @@ fn template_changes_that_cant_be_saved_are_undone() { LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(PrefsUnreadable::default()), on_disk: false }; s.open_library_in(stores, false).unwrap(); s.print_templates.push(crate::print::template::PrintTemplate::new("Proofs", &s.print).unwrap()); - let names = |s: &Session| s.print_templates.iter().map(|t| (t.name.clone(), t.settings.clone())).collect::>(); + s.print_template_folders.push("Family".into()); + let names = |s: &Session| { + ( + s.print_templates.iter().map(|t| (t.name.clone(), t.folder.clone(), t.settings.clone())).collect::>(), + s.print_template_folders.clone(), + ) + }; let kept = names(&s); let scratch = Scratch::new("unsaved"); let file = scratch.0.join("proofs.lcprint"); @@ -454,6 +627,10 @@ fn template_changes_that_cant_be_saved_are_undone() { ("print.template.save", json!({"name": "proofs"})), ("print.template.delete", json!({"name": "Proofs"})), ("print.template.import", json!({"path": file.to_string_lossy()})), + ("print.template.move", json!({"name": "Proofs", "folder": "Family"})), + ("print.template.folder.create", json!({"name": "Work"})), + ("print.template.folder.rename", json!({"name": "Family", "to": "Home"})), + ("print.template.folder.delete", json!({"name": "Family"})), ] { assert!(fails(&mut s, id, p.clone()).contains("prefs.json"), "{id} {p}"); assert_eq!(names(&s), kept, "{id} {p}"); @@ -503,6 +680,10 @@ fn every_print_command_is_registered_with_a_description() { "print.template.delete", "print.template.export", "print.template.import", + "print.template.move", + "print.template.folder.create", + "print.template.folder.rename", + "print.template.folder.delete", ] { let c = crate::find_command(id).unwrap_or_else(|| panic!("{id} missing")); assert!(c.params.len() > 3, "{id}"); diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index e0ec9f1baa..8158c582f2 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -283,6 +283,7 @@ "Exported to {path}": "Exportováno do {path}", "Saved template {name}": "Uložena šablona {name}", "Imported {name}": "Importováno: {name}", + "Moved {name} to {folder}": "{name} přesunuto do složky {folder}", "Skipped {problem}": "Přeskočeno: {problem}", "…and {more} more": "…a další: {more}", "Template preview: {name}": "Náhled šablony: {name}", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 6a056bbfb9..a24253de71 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2438,5 +2438,9 @@ "Set up name suggestions…": "Nastavit návrhy jmen…", "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", - "Bottom bar": "Dolní lišta" + "Bottom bar": "Dolní lišta", + "User Templates": "Uživatelské šablony", + "Delete Folder": "Odstranit složku", + "Folder name": "Název složky", + "Its templates move to User Templates.": "Její šablony se přesunou do složky Uživatelské šablony." } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 782886be84..22c1799c8c 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -284,6 +284,7 @@ "Exported to {path}": "Exportiert nach {path}", "Saved template {name}": "Vorlage {name} gespeichert", "Imported {name}": "{name} importiert", + "Moved {name} to {folder}": "{name} nach {folder} verschoben", "Skipped {problem}": "Übersprungen: {problem}", "…and {more} more": "…und {more} weitere", "Template preview: {name}": "Vorlagenvorschau: {name}", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 405c54a464..22d25fabf0 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3470,5 +3470,9 @@ "Top bar": "Obere Leiste", "Tool strip": "Werkzeugleiste", "Bottom bar": "Untere Leiste", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)", + "User Templates": "Benutzervorlagen", + "Delete Folder": "Ordner löschen", + "Folder name": "Ordnername", + "Its templates move to User Templates.": "Seine Vorlagen werden nach „Benutzervorlagen“ verschoben." } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 41ae09d66e..54fa87374a 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -285,6 +285,7 @@ "Exported to {path}": "Exportado a {path}", "Saved template {name}": "Plantilla {name} guardada", "Imported {name}": "Se importó {name}", + "Moved {name} to {folder}": "{name} se movió a {folder}", "Skipped {problem}": "Omitido: {problem}", "…and {more} more": "…y {more} más", "Template preview: {name}": "Vista previa de la plantilla: {name}", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index e43ae8c49b..a35be35e6a 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2390,5 +2390,9 @@ "Top bar": "Barra superior", "Tool strip": "Barra de herramientas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)", + "User Templates": "Plantillas del usuario", + "Delete Folder": "Eliminar carpeta", + "Folder name": "Nombre de la carpeta", + "Its templates move to User Templates.": "Sus plantillas se moverán a Plantillas del usuario." } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 720519a1cc..510a2f841d 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -99,6 +99,7 @@ "Import warnings ({n}):\n{warnings}": "Tuontivaroitukset ({n}):\n{warnings}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Tuotuja maskitehosteita: {e}{:.0} (Maskaus → Tehoste)", "Imported {name}": "{name} tuotu", + "Moved {name} to {folder}": "{name} siirretty kansioon {folder}", "Imported {n} point curve preset{}": "Tuotuja pistekäyrän esiasetuksia: {n}{:.0}", "Imported {n} preset{}": "Tuotuja esiasetuksia: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Tuotuja esiasetuksia: {n}{:.0}, ei luettavissa olevia tiedostoja: {f}{:.0}", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index ff7e03c066..bacf89c76b 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2356,5 +2356,9 @@ "Set up name suggestions…": "Määritä nimiehdotukset…", "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", - "Bottom bar": "Alapalkki" + "Bottom bar": "Alapalkki", + "User Templates": "Käyttäjän mallipohjat", + "Delete Folder": "Poista kansio", + "Folder name": "Kansion nimi", + "Its templates move to User Templates.": "Sen mallipohjat siirretään kansioon Käyttäjän mallipohjat." } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index fc46d653c6..f568fd63b9 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -285,6 +285,7 @@ "Exported to {path}": "Exporté vers {path}", "Saved template {name}": "Modèle {name} enregistré", "Imported {name}": "{name} importé", + "Moved {name} to {folder}": "{name} déplacé vers {folder}", "Skipped {problem}": "Ignoré : {problem}", "…and {more} more": "…et {more} de plus", "Template preview: {name}": "Aperçu du modèle : {name}", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index e032cf52f3..b06ca1727b 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3573,5 +3573,9 @@ "Top bar": "Barre supérieure", "Tool strip": "Barre d’outils", "Bottom bar": "Barre inférieure", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)", + "User Templates": "Modèles utilisateur", + "Delete Folder": "Supprimer le dossier", + "Folder name": "Nom du dossier", + "Its templates move to User Templates.": "Ses modèles sont déplacés vers Modèles utilisateur." } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 22eb2d49e3..9f98c8d0bc 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -286,6 +286,7 @@ "Exported to {path}": "Diekspor ke {path}", "Saved template {name}": "Templat {name} disimpan", "Imported {name}": "{name} diimpor", + "Moved {name} to {folder}": "{name} dipindahkan ke {folder}", "Skipped {problem}": "Dilewati: {problem}", "…and {more} more": "…dan {more} lainnya", "Template preview: {name}": "Pratinjau templat: {name}", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 1c70f26344..21d4efc19b 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2370,5 +2370,9 @@ "Set up name suggestions…": "Siapkan saran nama…", "Top bar": "Bilah atas", "Tool strip": "Bilah alat", - "Bottom bar": "Bilah bawah" + "Bottom bar": "Bilah bawah", + "User Templates": "Templat pengguna", + "Delete Folder": "Hapus folder", + "Folder name": "Nama folder", + "Its templates move to User Templates.": "Templatnya dipindahkan ke Templat pengguna." } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 4437aa644d..6e9b5d5fba 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -285,6 +285,7 @@ "{n} JPEG files": "File JPEG: {n}", "Exported {} effect preset{}": "Preset effetto esportati: {}{:.0}", "Imported {name}": "{name} importato", + "Moved {name} to {folder}": "{name} spostato in {folder}", "{n} pages": "Pagine: {n}", " · kept, not applied: {}": " · conservato, non applicato: {}", "Delete the effect preset “{name}”?": "Eliminare il preset effetto “{name}”?", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a0d39d0610..bd288561f1 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2556,5 +2556,9 @@ "Unit": "Unità", "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", - "Bottom bar": "Barra inferiore" + "Bottom bar": "Barra inferiore", + "User Templates": "Modelli utente", + "Delete Folder": "Elimina cartella", + "Folder name": "Nome della cartella", + "Its templates move to User Templates.": "I suoi modelli vengono spostati in Modelli utente." } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 2fb625ff6a..c8eed23029 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -289,6 +289,7 @@ "Exported to {path}": "{path} に書き出しました", "Saved template {name}": "テンプレート {name} を保存しました", "Imported {name}": "{name} を読み込みました", + "Moved {name} to {folder}": "{name} を {folder} に移動しました", "Skipped {problem}": "スキップ: {problem}", "…and {more} more": "…ほか {more} 件", "Template preview: {name}": "テンプレートのプレビュー: {name}", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 5f80d7896b..a82b2cbded 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2388,5 +2388,9 @@ "Top bar": "上部バー", "Tool strip": "ツールバー", "Bottom bar": "下部バー", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)", + "User Templates": "ユーザーテンプレート", + "Delete Folder": "フォルダを削除", + "Folder name": "フォルダ名", + "Its templates move to User Templates.": "中のテンプレートは「ユーザーテンプレート」に移動します。" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 329662ac1b..2fd821e83d 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -271,6 +271,7 @@ "Exported {} effect preset{}": "ექსპორტირებულია ეფექტის პრესეტი: {}{:.0}", "Imported {e} mask effect{} (Masking ▸ Effect)": "იმპორტირებულია ნიღბის ეფექტი: {e}{:.0} (ნიღბვა → ეფექტი)", "Imported {name}": "იმპორტირებულია: {name}", + "Moved {name} to {folder}": "{name} გადატანილია: {folder}", "Keywords of {n} selected photos": "მონიშნული ფოტოების ({n}) საკვანძო სიტყვები", "LightCraft stopped unexpectedly: {e}": "LightCraft მოულოდნელად შეწყდა: {e}", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft მოულოდნელად შეწყდა: {e}\n\nდეტალები ჟურნალის ფაილშია: {path}", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 0ea7d3d805..da6c1b8ff3 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3659,5 +3659,9 @@ "Top bar": "ზედა ზოლი", "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", + "User Templates": "მომხმარებლის შაბლონები", + "Delete Folder": "საქაღალდის წაშლა", + "Folder name": "საქაღალდის სახელი", + "Its templates move to User Templates.": "მისი შაბლონები გადავა „მომხმარებლის შაბლონებში“." } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 3f0fd43a22..f8b6ef9453 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -277,6 +277,7 @@ "Exported to {path}": "Wyeksportowano do {path}", "Saved template {name}": "Zapisano szablon {name}", "Imported {name}": "Zaimportowano {name}", + "Moved {name} to {folder}": "Przeniesiono {name} do {folder}", "Skipped {problem}": "Pominięto: {problem}", "…and {more} more": "…i jeszcze {more}", "Template preview: {name}": "Podgląd szablonu: {name}", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index bb3729a5b6..5f595e8fbe 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2315,5 +2315,9 @@ "Set up name suggestions…": "Skonfiguruj propozycje imion…", "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", - "Bottom bar": "Dolny pasek" + "Bottom bar": "Dolny pasek", + "User Templates": "Szablony użytkownika", + "Delete Folder": "Usuń folder", + "Folder name": "Nazwa folderu", + "Its templates move to User Templates.": "Jego szablony zostaną przeniesione do folderu Szablony użytkownika." } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index c26b2e281e..57cc0d3e07 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -289,6 +289,7 @@ "Exported to {path}": "Exportado para {path}", "Saved template {name}": "Modelo {name} salvo", "Imported {name}": "{name} importado", + "Moved {name} to {folder}": "{name} movido para {folder}", "Skipped {problem}": "Ignorado: {problem}", "…and {more} more": "…e mais {more}", "Template preview: {name}": "Prévia do modelo: {name}", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index a0884dc56a..09211ff2b2 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2234,5 +2234,9 @@ "Top bar": "Barra superior", "Tool strip": "Barra de ferramentas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)", + "User Templates": "Modelos do usuário", + "Delete Folder": "Excluir pasta", + "Folder name": "Nome da pasta", + "Its templates move to User Templates.": "Os modelos dela vão para Modelos do usuário." } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 4be240ec5b..7c785a25d2 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -285,6 +285,7 @@ "Exported to {path}": "Экспортировано в {path}", "Saved template {name}": "Шаблон {name} сохранён", "Imported {name}": "Импортировано: {name}", + "Moved {name} to {folder}": "{name} перемещено в {folder}", "Skipped {problem}": "Пропущено: {problem}", "…and {more} more": "…и ещё {more}", "Template preview: {name}": "Просмотр шаблона: {name}", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 598893c3bc..57d9796bfe 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2596,5 +2596,9 @@ "Top bar": "Верхняя панель", "Tool strip": "Панель инструментов", "Bottom bar": "Нижняя панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)", + "User Templates": "Пользовательские шаблоны", + "Delete Folder": "Удалить папку", + "Folder name": "Название папки", + "Its templates move to User Templates.": "Её шаблоны будут перемещены в «Пользовательские шаблоны»." } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 7d40388d1b..5e8c6f243f 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -97,6 +97,7 @@ "Import warnings ({n}):\n{warnings}": "Importvarningar ({n}):\n{warnings}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Importerade {e} maskeffekt{} (Maskering → Effekt)", "Imported {name}": "Importerade {name}", + "Moved {name} to {folder}": "Flyttade {name} till {folder}", "Imported {n} point curve preset{}": "Importerade {n} punktkurvförinställning{}", "Imported {n} preset{}": "Importerade {n} förinställning{}", "Imported {n} preset{}, {f} file{} not readable": "Importerade {n} förinställning{}, {f} fil{} kunde inte läsas", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index f229b9547c..c5209b58ee 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2459,5 +2459,9 @@ "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Knappen Taggar visar platshållare för mallen, till exempel {date} eller {seq}. Varje fil byter namn på disken tillsammans med sin XMP-sidofil; ett namn som redan finns får -1, -2…", "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", - "Bottom bar": "Nedre fältet" + "Bottom bar": "Nedre fältet", + "User Templates": "Användarmallar", + "Delete Folder": "Radera mapp", + "Folder name": "Mappnamn", + "Its templates move to User Templates.": "Dess mallar flyttas till Användarmallar." } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index e87bd03749..943e69fffc 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -285,6 +285,7 @@ "Exported to {path}": "Експортовано до {path}", "Saved template {name}": "Шаблон {name} збережено", "Imported {name}": "Імпортовано: {name}", + "Moved {name} to {folder}": "{name} переміщено до {folder}", "Skipped {problem}": "Пропущено: {problem}", "…and {more} more": "…і ще {more}", "Template preview: {name}": "Перегляд шаблону: {name}", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index a4efe34a60..c753263313 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2386,5 +2386,9 @@ "Top bar": "Верхня панель", "Tool strip": "Панель інструментів", "Bottom bar": "Нижня панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)", + "User Templates": "Власні шаблони", + "Delete Folder": "Видалити теку", + "Folder name": "Назва теки", + "Its templates move to User Templates.": "Її шаблони буде переміщено до «Власні шаблони»." } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index dbf1d28db5..ea881103d7 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -99,6 +99,7 @@ "Import warnings ({n}):\n{warnings}": "Cảnh báo khi nhập ({n}):\n{warnings}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", "Imported {name}": "Imported {name}", + "Moved {name} to {folder}": "Đã chuyển {name} vào {folder}", "Imported {n} point curve preset{}": "Đã nhập {n} thiết lập sẵn đường cong điểm{:.0}", "Imported {n} preset{}": "Đã nhập {n} thiết lập sẵn{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Đã nhập {n} thiết lập sẵn{:.0}, {f} tệp{:.0} không đọc được", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index c1610e428f..f612cd7db7 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2684,5 +2684,9 @@ "Set up name suggestions…": "Thiết lập gợi ý tên…", "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", - "Bottom bar": "Thanh dưới cùng" + "Bottom bar": "Thanh dưới cùng", + "User Templates": "Mẫu người dùng", + "Delete Folder": "Xóa thư mục", + "Folder name": "Tên thư mục", + "Its templates move to User Templates.": "Các mẫu trong đó sẽ được chuyển vào Mẫu người dùng." } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 0a8b94115f..8eabaabdd5 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -289,6 +289,7 @@ "Exported to {path}": "已导出到 {path}", "Saved template {name}": "已保存模板 {name}", "Imported {name}": "已导入 {name}", + "Moved {name} to {folder}": "已将 {name} 移到 {folder}", "Skipped {problem}": "已跳过:{problem}", "…and {more} more": "…还有 {more} 个", "Template preview: {name}": "模板预览:{name}", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ea867f35e6..d71eb52d00 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2389,5 +2389,9 @@ "Set up name suggestions…": "设置姓名建议…", "Top bar": "顶部栏", "Tool strip": "工具栏", - "Bottom bar": "底部栏" + "Bottom bar": "底部栏", + "User Templates": "用户模板", + "Delete Folder": "删除文件夹", + "Folder name": "文件夹名称", + "Its templates move to User Templates.": "其中的模板将移到“用户模板”。" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 178cd55a03..5c95be0ff8 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -289,6 +289,7 @@ "Exported to {path}": "已匯出到 {path}", "Saved template {name}": "已儲存範本 {name}", "Imported {name}": "已匯入 {name}", + "Moved {name} to {folder}": "已將 {name} 移至 {folder}", "Skipped {problem}": "已略過:{problem}", "…and {more} more": "…還有 {more} 個", "Template preview: {name}": "範本預覽:{name}", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 90b3670ec3..8e2bbf9815 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2389,5 +2389,9 @@ "Top bar": "頂部列", "Tool strip": "工具列", "Bottom bar": "底部列", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)", + "User Templates": "使用者範本", + "Delete Folder": "刪除資料夾", + "Folder name": "資料夾名稱", + "Its templates move to User Templates.": "其中的範本會移到「使用者範本」。" } diff --git a/crates/ui-egui/src/dialogs/print_view.rs b/crates/ui-egui/src/dialogs/print_view.rs index c9af1d776d..fdf9c643b0 100644 --- a/crates/ui-egui/src/dialogs/print_view.rs +++ b/crates/ui-egui/src/dialogs/print_view.rs @@ -10,7 +10,7 @@ use lightcraft_catalog::PhotoId; use lightcraft_engine::export::ExportOptions; use lightcraft_engine::print::compose::{self, place}; use lightcraft_engine::print::layout::{self, Snap, Style, Unit}; -use lightcraft_engine::print::template::PrintSettings; +use lightcraft_engine::print::template::{DEFAULT_FOLDER, PrintSettings}; use lightcraft_engine::print_color::{ManagedSpace, PrintColorSettings, PrintIntent, PrintMedia, PrintProfile, PrintSharpen}; use serde_json::{Value, json}; @@ -49,10 +49,27 @@ pub struct PrintUi { drag: Option, /// The name typed for Save Template. pub template_name: String, + /// The folder Save and Import… put a template in; `None`: User Templates. + pub save_folder: Option, + /// A folder name being typed in the Template Browser. + pub folder_edit: Option, + /// The folder whose Delete Folder waits for a confirmation. + pub delete_folder: Option, + /// Template Browser folders shown closed, lowercase. + pub closed_folders: Vec, + /// The template being dragged onto a folder. + pub dragging_template: Option, /// Size of the next cell added, inches. pub new_cell: Option<(f64, f64)>, } +/// New Folder… (`from: None`) or Rename Folder… of the folder `from`, with the name typed so far. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FolderEdit { + pub from: Option, + pub name: String, +} + fn run(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Option { match app.run(id, params) { Ok(v) => Some(v), @@ -196,31 +213,241 @@ pub fn body(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens) { app.ui.print = pu; } -/// The print templates: save the settings as one, import, and the saved ones to apply, export and delete. +/// The folder a command names for `folder` (`None`: User Templates). +fn folder_param(folder: Option<&str>) -> &str { + folder.unwrap_or(DEFAULT_FOLDER) +} + +/// How the Template Browser names `folder`: User Templates in the interface's language, a folder +/// of the user's as it was typed. +fn folder_label(folder: Option<&str>) -> String { + folder.map_or_else(|| crate::i18n::tr("User Templates").to_string(), str::to_string) +} + +/// The print templates: save the settings as one into a folder, import, and the Template Browser: +/// its folders (New Folder…, Rename Folder…, Delete Folder) and in each the saved templates to +/// apply, export, delete, and drag onto another folder or move there from their menu. fn templates_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi) { let ctx = ui.ctx().clone(); heading(ui, t, "Templates"); + // a folder deleted or renamed by a command is no longer the one Save uses + if pu.save_folder.as_ref().is_some_and(|f| !app.session.print_template_folders.contains(f)) { + pu.save_folder = None; + } ui.horizontal(|ui| { crate::text_field::TextField::singleline("field:printTemplateName", &mut pu.template_name) .hint(crate::i18n::tr("Template name")) .width(140.0) .show(ui); + let folder = folder_param(pu.save_folder.as_deref()).to_string(); if text_button(ui, "printSaveTemplate", "Save", false).clicked() && !pu.template_name.trim().is_empty() { - run(app, &ctx, "print.template.save", json!({"name": pu.template_name})); + run(app, &ctx, "print.template.save", json!({"name": pu.template_name, "folder": folder})); } if app.services.pick_print_templates.is_some() && text_button(ui, "printTemplateImport", "Import…", false).clicked() { let paths = app.services.pick_print_templates.as_mut().map(|pick| pick()).unwrap_or_default(); for path in paths { - if let Some(r) = run(app, &ctx, "print.template.import", json!({"path": path})) { + if let Some(r) = run(app, &ctx, "print.template.import", json!({"path": path, "folder": folder})) { app.toast(&ctx, crate::i18n::tr_format!("Imported {name}", name = r["name"].as_str().unwrap_or_default())); } } } }); - let names: Vec = app.session.print_templates.iter().map(|t| t.name.clone()).collect(); - for (i, name) in names.iter().enumerate() { + let folders: Vec> = std::iter::once(None).chain(app.session.print_template_folders.iter().cloned().map(Some)).collect(); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(crate::i18n::tr("Folder")).color(t.text_label)); + let c = craft_ui::ComboBox::from_id_salt("printSaveFolder").width(120.0).selected_text(folder_label(pu.save_folder.as_deref())).show_ui( + ui, + |ui| { + for (j, f) in folders.iter().enumerate() { + let r = ui.selectable_label(pu.save_folder == *f, folder_label(f.as_deref())); + register(ui, format!("item:printSaveFolder-{j}"), r.rect); + if r.clicked() { + pu.save_folder.clone_from(f); + } + } + }, + ); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Folder")); + register(ui, "combo:printSaveFolder", c.response.rect); + if text_button(ui, "printTemplateNewFolder", "New Folder…", false).clicked() { + pu.folder_edit = Some(FolderEdit::default()); + pu.delete_folder = None; + } + }); + folder_editor(app, ui, &ctx, pu); + folder_delete_confirmation(app, ui, t, &ctx, pu); + for (j, folder) in folders.iter().enumerate() { + folder_rows(app, ui, t, pu, j, folder.as_deref(), &folders); + } + template_drag_feedback(&ctx, t, pu); +} + +/// The New Folder… / Rename Folder… field under the Save row, while one is open: Return or its +/// button runs the command, Esc or Cancel closes it. A refused name keeps it open, with the reason +/// in a toast. +fn folder_editor(app: &mut LightcraftApp, ui: &mut Ui, ctx: &egui::Context, pu: &mut PrintUi) { + let Some(mut edit) = pu.folder_edit.take() else { return }; + let (mut confirm, mut cancel) = (false, false); + ui.horizontal(|ui| { + let r = crate::text_field::TextField::singleline("field:printFolderName", &mut edit.name) + .hint(crate::i18n::tr("Folder name")) + .width(140.0) + .select_on_focus(true) + .show(ui); + if super::frame::just_opened(ui, "printFolderName") { + r.response.request_focus(); + } + match r.ending { + Some(crate::text_field::Ending::Return) => confirm = true, + Some(crate::text_field::Ending::Escape) => cancel = true, + _ => {} + } + confirm |= text_button(ui, "printFolderOk", if edit.from.is_some() { "Rename" } else { "Create" }, false).clicked(); + cancel |= text_button(ui, "printFolderCancel", "Cancel", false).clicked(); + }); + if cancel { + return; + } + if confirm { + let (id, params) = match &edit.from { + None => ("print.template.folder.create", json!({"name": edit.name})), + Some(from) => ("print.template.folder.rename", json!({"name": from, "to": edit.name})), + }; + if let Some(r) = run(app, ctx, id, params) { + let made = r["name"].as_str().map(str::to_string); + // a new folder is where the next Save goes; a renamed one keeps its place there and its closed state + if edit.from.is_none() || pu.save_folder == edit.from { + pu.save_folder.clone_from(&made); + } + if let (Some(from), Some(to)) = (&edit.from, &made) { + for c in &mut pu.closed_folders { + if *c == from.to_lowercase() { + *c = to.to_lowercase(); + } + } + } + return; + } + } + pu.folder_edit = Some(edit); +} + +/// Delete Folder's question, while it is asked: the folder's templates move to User Templates. +fn folder_delete_confirmation(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context, pu: &mut PrintUi) { + let Some(name) = pu.delete_folder.clone() else { return }; + let question = + format!("{} {}", crate::i18n::tr_format!("Delete “{name}”?", name = name), crate::i18n::tr("Its templates move to User Templates.")); + ui.label(egui::RichText::new(question).color(t.text_label)); + ui.horizontal(|ui| { + if text_button(ui, "printFolderDeleteConfirm", "Delete Folder", false).clicked() + && run(app, ctx, "print.template.folder.delete", json!({"name": name})).is_some() + { + pu.delete_folder = None; + pu.closed_folders.retain(|c| *c != name.to_lowercase()); + } + if text_button(ui, "printFolderDeleteCancel", "Cancel", false).clicked() { + pu.delete_folder = None; + } + }); +} + +/// Moves the template `name` to `folder` and says so; nothing when it is there already. +fn move_template(app: &mut LightcraftApp, ctx: &egui::Context, name: &str, folder: Option<&str>) { + if let Some(r) = run(app, ctx, "print.template.move", json!({"name": name, "folder": folder_param(folder)})) + && r["moved"] == true + { + app.toast(ctx, crate::i18n::tr_format!("Moved {name} to {folder}", name = name, folder = folder_label(folder))); + } +} + +/// One Template Browser folder: its row (a click opens or closes it, a template dropped on it moves +/// there, its menu has New Folder… and, for the user's folders, Rename Folder… and Delete Folder), +/// then, while it is open, its templates. +fn folder_rows(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, j: usize, folder: Option<&str>, folders: &[Option]) { + let ctx = ui.ctx().clone(); + let label = folder_label(folder); + let key = folder_param(folder).to_lowercase(); + let open = !pu.closed_folders.contains(&key); + let count = app.session.print_templates.iter().filter(|x| x.folder.as_deref() == folder).count(); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); + crate::widgets::announce_disclosure(&resp, true, open, &label); + register(ui, format!("printTemplateFolder-{j}"), r); + let pointer = ui.input(|i| i.pointer.latest_pos()); + let under_drag = pu.dragging_template.is_some() && crate::docking::drop_target(ui, r, pointer); + if under_drag { + ui.painter().rect_stroke(r.shrink(1.0), 4.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); + } else if resp.hovered() { + ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.6)); + } + crate::icons::paint( + ui.painter(), + Rect::from_center_size(pos2(r.left() + 8.0, r.center().y), vec2(14.0, 14.0)), + if open { crate::icons::Icon::ChevronDown } else { crate::icons::Icon::ChevronRight }, + t.text_label, + ); + ui.painter().text(pos2(r.left() + 20.0, r.center().y), Align2::LEFT_CENTER, &label, t.semibold(12.0), t.text); + ui.painter().text(pos2(r.right() - 4.0, r.center().y), Align2::RIGHT_CENTER, count.to_string(), t.font(11.0), t.text_dim); + if resp.clicked() { + if open { + pu.closed_folders.push(key); + } else { + pu.closed_folders.retain(|c| *c != key); + } + } + if under_drag + && ui.input(|i| i.pointer.primary_released()) + && let Some(name) = pu.dragging_template.take() + { + move_template(app, &ctx, &name, folder); + } + crate::widgets::context_menu(&resp, |ui| { + let new = ui.button(crate::i18n::tr("New Folder…")); + register(ui, format!("item:printFolderNew-{j}"), new.rect); + if new.clicked() { + pu.folder_edit = Some(FolderEdit::default()); + pu.delete_folder = None; + } + if let Some(f) = folder { + let rename = ui.button(crate::i18n::tr("Rename Folder…")); + register(ui, format!("item:printFolderRename-{j}"), rename.rect); + if rename.clicked() { + pu.folder_edit = Some(FolderEdit { from: Some(f.to_string()), name: f.to_string() }); + pu.delete_folder = None; + } + let delete = ui.button(crate::i18n::tr("Delete Folder")); + register(ui, format!("item:printFolderDelete-{j}"), delete.rect); + if delete.clicked() { + pu.delete_folder = Some(f.to_string()); + pu.folder_edit = None; + } + } + }); + if !open { + return; + } + let rows: Vec<(usize, String)> = + app.session.print_templates.iter().enumerate().filter(|(_, x)| x.folder.as_deref() == folder).map(|(i, x)| (i, x.name.clone())).collect(); + for (i, name) in &rows { + let (i, name) = (*i, name.as_str()); ui.horizontal(|ui| { - ui.label(egui::RichText::new(name).color(t.text_label)); + ui.add_space(20.0); + let resp = ui.add(egui::Label::new(egui::RichText::new(name).color(t.text_label)).sense(Sense::click_and_drag())); + register(ui, format!("printTemplate-{i}"), resp.rect); + if resp.drag_started() { + pu.dragging_template = Some(name.to_string()); + } + crate::widgets::context_menu(&resp, |ui| { + let sub = crate::widgets::menu_button(ui, crate::i18n::tr("Move to Folder"), |ui| { + for (k, f) in folders.iter().enumerate().filter(|(_, f)| f.as_deref() != folder) { + let item = ui.button(folder_label(f.as_deref())); + register(ui, format!("item:printTemplateMove-{i}-{k}"), item.rect); + if item.clicked() { + move_template(app, &ctx, name, f.as_deref()); + } + } + }); + register(ui, format!("item:printTemplateMoveMenu-{i}"), sub.response.rect); + }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if text_button(ui, &format!("printTemplateDelete-{i}"), "Delete", false).clicked() { run(app, &ctx, "print.template.delete", json!({"name": name})); @@ -244,6 +471,28 @@ fn templates_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut } } +/// A template being dragged: its name follows the pointer, and the drag ends with the button's +/// release (after the folder rows, which take the drop) or with Esc. +fn template_drag_feedback(ctx: &egui::Context, t: &Tokens, pu: &mut PrintUi) { + let Some(name) = pu.dragging_template.clone() else { return }; + let (released, down, at, esc) = + ctx.input(|i| (i.pointer.any_released(), i.pointer.any_down(), i.pointer.latest_pos(), i.key_pressed(egui::Key::Escape))); + if released || !down || esc { + pu.dragging_template = None; + return; + } + let Some(at) = at else { return }; + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + egui::Area::new(egui::Id::unique("drag-print-template")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show( + ctx, + |ui| { + egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { + ui.label(egui::RichText::new(name).color(Color32::WHITE).font(t.semibold(12.0))); + }); + }, + ); +} + /// The image settings: zoom, rotation, border and stroke. fn image_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, st: &PrintSettings) { let ctx = ui.ctx().clone(); diff --git a/crates/ui-egui/src/tests/print.rs b/crates/ui-egui/src/tests/print.rs index 68f3d328d0..5169e47a56 100644 --- a/crates/ui-egui/src/tests/print.rs +++ b/crates/ui-egui/src/tests/print.rs @@ -90,6 +90,11 @@ fn style_buttons_and_checkboxes_run_print_set() { click(&mut h, "check:printZoomFill"); click(&mut h, "check:printStroke"); assert!(h.app.session.print.image.zoom_to_fill && h.app.session.print.image.stroke_enabled); + // (the page settings are below the Template Browser: the settings column is scrolled to them) + let column = rect(&h, "check:printStroke").center(); + h.request("ui.move", json!({"x": column.x, "y": column.y}), T); + h.request("ui.scroll", json!({"dy": -200.0}), T); + h.settle(T); click(&mut h, "button:printOrientation-1"); assert_eq!(h.app.session.print.layout.page.orientation, lightcraft_engine::print::layout::Orientation::Landscape); let p = rect(&h, "print:page"); @@ -248,6 +253,122 @@ fn templates_export_and_import_from_the_dialog() { let _ = std::fs::remove_dir_all(dir); } +/// Each template's name and folder (`None`: User Templates). +fn template_folders(h: &Headless) -> Vec<(String, Option)> { + h.app.session.print_templates.iter().map(|t| (t.name.clone(), t.folder.clone())).collect() +} + +/// Drags the widget `from` onto the center of the widget `to`. +fn drag_onto(h: &mut Headless, from: &str, to: &str) { + let (a, b) = (rect(h, from).center(), rect(h, to).center()); + drag(h, from, b.x - a.x, b.y - a.y); +} + +#[test] +fn the_template_browser_makes_folders_and_saves_into_one() { + let mut h = demo(Services::default()); + open_print(&mut h); + assert!(has(&h, "printTemplateFolder-0"), "User Templates is listed"); + assert!(!has(&h, "printTemplateFolder-1")); + click(&mut h, "button:printTemplateNewFolder"); + assert!(has(&h, "field:printFolderName")); + h.app.ui.print.folder_edit.as_mut().unwrap().name = "Weddings".into(); + click(&mut h, "button:printFolderOk"); + assert_eq!(h.app.session.print_template_folders, ["Weddings"]); + assert!(h.app.ui.print.folder_edit.is_none()); + assert!(has(&h, "printTemplateFolder-1")); + assert_eq!(h.app.ui.print.save_folder.as_deref(), Some("Weddings"), "a new folder is where Save goes"); + // a name taken is refused, and the field stays open + click(&mut h, "button:printTemplateNewFolder"); + h.app.ui.print.folder_edit.as_mut().unwrap().name = "weddings".into(); + click(&mut h, "button:printFolderOk"); + assert!(h.app.ui.print.folder_edit.is_some()); + click(&mut h, "button:printFolderCancel"); + assert!(h.app.ui.print.folder_edit.is_none()); + assert_eq!(h.app.session.print_template_folders.len(), 1); + + h.app.ui.print.template_name = "Sheet".into(); + click(&mut h, "button:printSaveTemplate"); + h.app.ui.print.save_folder = None; + h.app.ui.print.template_name = "Plain".into(); + click(&mut h, "button:printSaveTemplate"); + assert_eq!(template_folders(&h), [("Sheet".into(), Some("Weddings".into())), ("Plain".into(), None)]); + // a folder's row opens and closes its list + assert!(has(&h, "printTemplate-0")); + click(&mut h, "printTemplateFolder-1"); + assert!(!has(&h, "printTemplate-0"), "a closed folder hides its templates"); + assert!(has(&h, "printTemplate-1")); + click(&mut h, "printTemplateFolder-1"); + assert!(has(&h, "printTemplate-0")); +} + +#[test] +fn a_template_dragged_onto_a_folder_moves_there() { + let mut h = demo(Services::default()); + open_print(&mut h); + cmd(&mut h, "print.template.folder.create", json!({"name": "Weddings"})); + cmd(&mut h, "print.template.save", json!({"name": "Plain"})); + let settings = h.app.session.print_templates[0].settings.clone(); + drag_onto(&mut h, "printTemplate-0", "printTemplateFolder-1"); + assert_eq!(template_folders(&h), [("Plain".into(), Some("Weddings".into()))]); + assert_eq!(h.app.session.print_templates[0].settings, settings, "only the folder changes"); + assert!(h.app.ui.print.dragging_template.is_none()); + // and back onto User Templates + drag_onto(&mut h, "printTemplate-0", "printTemplateFolder-0"); + assert_eq!(template_folders(&h), [("Plain".into(), None)]); + // a drop anywhere else leaves it where it is + drag(&mut h, "printTemplate-0", 0.0, 300.0); + assert_eq!(template_folders(&h), [("Plain".into(), None)]); + assert!(h.app.ui.print.dragging_template.is_none()); +} + +#[test] +fn a_templates_menu_moves_it_and_a_folders_menu_renames_and_deletes() { + let mut h = demo(Services::default()); + open_print(&mut h); + cmd(&mut h, "print.template.folder.create", json!({"name": "Weddings"})); + cmd(&mut h, "print.template.save", json!({"name": "Plain"})); + let r = h.request("ui.clickWidget", json!({"id": "printTemplate-0", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + assert_eq!(h.request("ui.hoverWidget", json!({"id": "item:printTemplateMoveMenu-0"}), T)["ok"], true); + h.settle(T); + click(&mut h, "item:printTemplateMove-0-1"); + assert_eq!(template_folders(&h), [("Plain".into(), Some("Weddings".into()))]); + + let r = h.request("ui.clickWidget", json!({"id": "printTemplateFolder-1", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + click(&mut h, "item:printFolderRename-1"); + assert_eq!(h.app.ui.print.folder_edit.as_ref().and_then(|e| e.from.as_deref()), Some("Weddings")); + h.app.ui.print.folder_edit.as_mut().unwrap().name = "Family".into(); + click(&mut h, "button:printFolderOk"); + assert_eq!(h.app.session.print_template_folders, ["Family"]); + assert_eq!(template_folders(&h), [("Plain".into(), Some("Family".into()))]); + + // Delete Folder asks first; its templates then go to User Templates + let r = h.request("ui.clickWidget", json!({"id": "printTemplateFolder-1", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + click(&mut h, "item:printFolderDelete-1"); + assert_eq!(h.app.session.print_template_folders, ["Family"], "nothing is deleted before the confirmation"); + click(&mut h, "button:printFolderDeleteCancel"); + assert_eq!(h.app.session.print_template_folders, ["Family"]); + h.app.ui.print.delete_folder = Some("Family".into()); + h.settle(T); + click(&mut h, "button:printFolderDeleteConfirm"); + assert!(h.app.session.print_template_folders.is_empty()); + assert_eq!(template_folders(&h), [("Plain".into(), None)]); + assert!(h.app.ui.print.delete_folder.is_none()); + + // User Templates has New Folder… but no Rename or Delete + let r = h.request("ui.clickWidget", json!({"id": "printTemplateFolder-0", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + assert!(has(&h, "item:printFolderNew-0")); + assert!(!has(&h, "item:printFolderRename-0") && !has(&h, "item:printFolderDelete-0")); +} + #[test] fn template_files_need_the_hosts_file_dialogs() { let mut h = demo(Services::default()); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a9dd725236..f807285f20 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -766,7 +766,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-PRINT-CELLS | Picture-package cells | P2 | ✅ | `cmd:print.cell.add`, `cmd:print.cell.move`, `cmd:print.cell.resize`, `cmd:print.cell.delete`, `cmd:print.cell.stack`, `cmd:print.cell.photo`, `cmd:print.cell.page`, `cmd:print.layout.autoLayout`, `crates/ui-egui/src/dialogs/print_view.rs` | add cells at standard or custom sizes, drag and resize them on the page preview (snap to cells, grid or off), Send to Back / Backward / Forward / Bring to Front, a photo per cell (Custom Package), Auto Layout packing, New Page, Clear Layout; no Auto Layout for Custom Package | | LRC-PRINT-PAGE | Print page options | P2 | 🟡 | `cmd:print.set`, `cmd:export.contactSheet`, `crates/engine/src/print/compose.rs`, `crates/ui-egui/src/dialogs/print_view.rs` | page background colour and margins in the Print dialog; Page Options for Single Image and Contact Sheet (`print.set {page: {pageNumbers, pageInfo, cropMarks}}`, checkboxes in the Page section, kept in templates): the page number at the bottom right, the print settings line (sharpening, profile, resolution) at the bottom left, crop marks at each photo's corners, drawn in the preview and in the PDF (`print::compose::tests::crop_marks_sit_outside_each_photo_corner`); filename captions in the contact-sheet PDF; no identity plate, watermark, photo info or package Cut Guides | | LRC-PRINT-JOB | Print job & colour management | P2 | 🟡 | `cmd:print.set`, `cmd:print.exportPdf`, `crates/ui-egui/src/dialogs/print_view.rs`, `crates/engine/src/print_color.rs`, `crates/codecs/src/print.rs`, `crates/engine/src/pdf.rs`, `cmd:export.contactSheet` | the Print dialog's Print Job panel and `print.set {job}`: print resolution 72–720 ppi; colour management: Managed by Printer (sRGB / Adobe RGB, profile embedded) or a printer / paper ICC profile (RGB, CMYK or grey) converted here and named as the PDF's output intent; perceptual / relative colorimetric with black point compensation; Print Adjustment brightness / contrast; print sharpening Low / Standard / High for Matte / Glossy; 16-bit (or 8-bit) ICC-tagged lossless page images; a bad profile fails before rendering (`tests_print::export_pdf_with_a_printer_profile`). The contact sheet keeps its fixed 150 dpi sRGB JPEG PDF. Missing: printing to a printer (OS print dialog), JPEG file output, Draft Mode | -| LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete`, `cmd:print.template.export`, `cmd:print.template.import`, `crates/ui-egui/src/dialogs/print_view.rs` | save, apply and delete named templates (layout, image settings, page, job) at the top of the Print dialog, kept with the library; Export… writes a template to a `.lcprint` file and Import… adds one from such a file (checked like a saved template; a name already in use gets " (2)"); no built-in templates, no folders | +| LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete`, `cmd:print.template.export`, `cmd:print.template.import`, `cmd:print.template.move`, `cmd:print.template.folder.create`, `cmd:print.template.folder.rename`, `cmd:print.template.folder.delete`, `crates/ui-egui/src/dialogs/print_view.rs` | save, apply and delete named templates (layout, image settings, page, job) at the top of the Print dialog, kept with the library; Export… writes a template to a `.lcprint` file and Import… adds one from such a file (checked like a saved template; a name already in use gets " (2)"); the Template Browser lists the templates in folders: User Templates and folders made with New Folder… (its button, or a folder's context menu), which open and close; Save and Import… put a template in the folder chosen beside them; a template dragged onto a folder, or moved with its context menu's Move to Folder, moves there; Rename Folder… and Delete Folder (asks first, and moves the folder's templates to User Templates, LightCraft's own rule) for every folder but User Templates; no built-in templates | | LRC-WEB-LAYOUT | Web gallery layouts | OOS | 🚫 | | | | LRC-WEB-SITEINFO | Web gallery site info | OOS | 🚫 | | | | LRC-WEB-COLOR | Web gallery colours | OOS | 🚫 | | | @@ -1025,3 +1025,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | +| 2026-10-31 | minor | LRC-PRINT-TEMPLATES: the Print dialog's Template Browser has folders (`print.template.folder.create` / `rename` / `delete`), Save and Import… put a template in a chosen folder, and a template dragged onto a folder moves there (`print.template.move`); deleting a folder moves its templates to User Templates; status unchanged (🟡: no built-in templates) |