LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
LRC-SS-TEMPLATES: slideshow templates: built-ins of our own, user templates, browser with hover preview
Jason Baldwin6bfe2235af82
diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rsindex 592a534a9..dbcef01ef 100644--- a/apps/lightcraft-cli/src/main.rs+++ b/apps/lightcraft-cli/src/main.rs@@ -732,12 +732,15 @@ fn snapshot(args: &[String]) -> Result<(), String> {let t0 = Instant::now();let mut session = match &library {Some(dir) => {- let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models();+ let mut s =+ Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates();s.open_library(dir, false).map_err(|e| library_error(dir, e))?;s}- None if files.is_empty() => Session::with_demo().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models(),- None => Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models(),+ None if files.is_empty() => {+ Session::with_demo().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates()+ }+ None => Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates(),};// Apply compute policy before imports or the first scripted query can discover an adapter.session.execute("app.gpu", &json!({"enabled": false})).map_err(|e| e.to_string())?;diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rsindex 592d05cd1..bbf14ea50 100644--- a/apps/lightcraft-web/src/web.rs+++ b/apps/lightcraft-web/src/web.rs@@ -218,6 +218,8 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozensave_keyword_list: None,pick_curve_preset_files: None,save_curve_preset_file: None,+ pick_slideshow_templates: None,+ save_slideshow_template: None,write: Some(Box::new(download)),// downloads happen on the main thread: exports run in the foreground on the webwrite_shared: None,diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rsindex 09cb14343..438104cf4 100644--- a/apps/lightcraft/src/main.rs+++ b/apps/lightcraft/src/main.rs@@ -567,6 +567,24 @@ fn services(ctx: egui::Context, log_file: Option<&std::path::Path>) -> Services.save_file().map(|p| p.to_string_lossy().to_string())})),+ pick_slideshow_templates: Some(Box::new(|| {+ rfd::FileDialog::new()+ .set_title(lightcraft_ui_egui::i18n::tr("Import Slideshow Templates"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Slideshow Templates"), &["json"])+ .pick_files()+ .unwrap_or_default()+ .into_iter()+ .map(|p| p.to_string_lossy().to_string())+ .collect()+ })),+ save_slideshow_template: Some(Box::new(|name: &str| {+ rfd::FileDialog::new()+ .set_title(lightcraft_ui_egui::i18n::tr("Export Slideshow Template"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Slideshow Templates"), &["json"])+ .set_file_name(name)+ .save_file()+ .map(|p| p.to_string_lossy().to_string())+ })),// atomic (temp file + sync + rename): a failed write never leaves a truncated filewrite_shared: Some(std::sync::Arc::new(lightcraft_engine::export::write_file)),write: Some(Box::new(lightcraft_engine::export::write_file)),@@ -579,10 +597,12 @@ fn services(ctx: egui::Context, log_file: Option<&std::path::Path>) -> Services}}-/// The library session with the folder face models are kept in (`<config>/models`).+/// The library session with the folders face models (`<config>/models`) and slideshow templates+/// (`<config>/slideshow-templates`) are kept in.fn open_session(in_memory: bool, dir: Option<std::path::PathBuf>, seed_demo: bool) -> (Session, Option<LibraryProblem>) {let (mut s, problem) = open_library_session(in_memory, dir, seed_demo);s.face_models_dir = lightcraft_engine::config::default_face_models_dir();+ s.slide_templates_dir = lightcraft_engine::config::config_dir().map(|d| d.join(lightcraft_engine::slide_template::DIR_NAME));(s, problem)}diff --git a/crates/engine/src/cmd/slideshow.rs b/crates/engine/src/cmd/slideshow.rsindex 62e4b4313..92c1a325c 100644--- a/crates/engine/src/cmd/slideshow.rs+++ b/crates/engine/src/cmd/slideshow.rs@@ -6,12 +6,15 @@//! the identity plate, rating stars, text overlays with tokens and the watermark drawn on every//! slide (also a library preference). `slideshow.titles`: the intro and ending screens (colour,//! identity plate or text, scale, duration; a library preference). `slideshow.preview` composes-//! one slide, or a title screen, as a PNG.+//! one slide, or a title screen, as a PNG (with the library's settings, or a template's).+//! `slideshow.templates.*`: the Template Browser (built-in and user templates; see+//! [`crate::slide_template`]).use lightcraft_catalog::PhotoId;use serde_json::{Value, json};use super::{CommandSpec, always, bad, cmd, str_param};+use crate::slide_template::{self as tpl, SlideLook};use crate::{Result, Session};/// Largest side `slideshow.preview` renders.@@ -71,7 +74,7 @@ fn titles(s: &mut Session, p: &Value) -> Result<Value> {/// A slide size from the request: both sides given, one (the other from the aspect preview), or/// neither (1280 wide). Each side 16–[`PREVIEW_MAX`].-fn preview_size(s: &Session, p: &Value) -> Result<(usize, usize)> {+fn preview_size(layout: &lightcraft_slideshow::SlideSettings, p: &Value) -> Result<(usize, usize)> {const C: &str = "slideshow.preview";let side = |k: &str| -> Result<Option<usize>> {match p.get(k) {@@ -82,7 +85,7 @@ fn preview_size(s: &Session, p: &Value) -> Result<(usize, usize)> {},}};- let ratio = s.slide_layout.aspect.ratio(f64::NAN);+ let ratio = layout.aspect.ratio(f64::NAN);let clamp = |v: f64| (v.round() as usize).clamp(16, PREVIEW_MAX);Ok(match (side("width")?, side("height")?) {(Some(w), Some(h)) => (w, h),@@ -110,7 +113,7 @@ fn encode_png(img: &lightcraft_raster::Rgba8) -> Result<Vec<u8>> {}/// `slideshow.preview {title}`: a title screen (whether or not it is switched on).-fn preview_title(s: &mut Session, p: &Value, title: &Value) -> Result<Value> {+fn preview_title(s: &mut Session, p: &Value, title: &Value, look: &SlideLook) -> Result<Value> {const C: &str = "slideshow.preview";let t = title.as_str()@@ -119,18 +122,18 @@ fn preview_title(s: &mut Session, p: &Value, title: &Value) -> Result<Value> {if p.get("id").is_some_and(|v| !v.is_null()) {return Err(bad(C, "pass `id` or `title`, not both"));}- let (w, h) = preview_size(s, p)?;+ let (w, h) = preview_size(&look.layout, p)?;let path = str_param(p, "path").map(str::trim).filter(|x| !x.is_empty());if let Some(path) = path {s.check_write_target(path).map_err(|e| bad(C, e))?;}- let c = s.title_compose(t, w, h);+ let c = crate::slide_title::TitleCompose::new(&look.titles, &look.overlays, t, w, h);let img = c.compose();let png = encode_png(&img)?;let rect = |r: lightcraft_slideshow::Rect| json!([r.x0, r.y0, r.x1, r.y1]);let mut out = json!({"title": t.id(),- "enabled": s.slide_titles.screen(t).enabled,+ "enabled": look.titles.screen(t).enabled,"width": img.width,"height": img.height,"plate": c.plate_box().map(rect),@@ -141,8 +144,19 @@ fn preview_title(s: &mut Session, p: &Value, title: &Value) -> Result<Value> {fn preview(s: &mut Session, p: &Value) -> Result<Value> {const C: &str = "slideshow.preview";+ // a template's look (the Template Browser's hover preview), else the library's settings+ let template = match p.get("template") {+ None | Some(Value::Null) => None,+ Some(Value::String(id)) => Some(s.slide_template(id.trim()).map_err(|e| bad(C, e))?),+ Some(v) => return Err(bad(C, format!("`template` must be a template id, not {v}"))),+ };+ let look = template.as_ref().map_or_else(|| SlideLook::of(s), |t| t.look.clone());if let Some(t) = p.get("title").filter(|v| !v.is_null()) {- return preview_title(s, p, t);+ let mut out = preview_title(s, p, t, &look)?;+ if let Some(t) = &template {+ out["template"] = json!(t.id);+ }+ return Ok(out);}let id = match p.get("id") {None | Some(Value::Null) => s.active().ok_or_else(|| bad(C, "no photo selected (select one or pass `id`)"))?,@@ -151,13 +165,13 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {if s.catalog.photo(id).is_none() {return Err(bad(C, format!("no photo {}", id.0)));}- let (w, h) = preview_size(s, p)?;+ let (w, h) = preview_size(&look.layout, p)?;let path = str_param(p, "path").map(str::trim).filter(|x| !x.is_empty());if let Some(path) = path {s.check_write_target(path).map_err(|e| bad(C, e))?;}- let settings = s.slide_layout.clone();- let img = s.slide_now(&settings, id, w, h).map_err(crate::EngineError::Other)?;+ let settings = look.layout.clone();+ let img = s.slide_now_look(&settings, &look.overlays, id, w, h).map_err(crate::EngineError::Other)?;let png = encode_png(&img)?;let aspect = s.slide_photo_aspect(id).unwrap_or(1.5);let l = lightcraft_slideshow::layout(&settings, aspect, img.width, img.height);@@ -170,8 +184,11 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {"photo": rect(l.visible),});let photo = s.catalog.photo(id).cloned();- let o = crate::slide_overlay::SlideOverlays::resolve(&s.slide_overlays, photo.as_deref());+ let o = crate::slide_overlay::SlideOverlays::resolve(&look.overlays, photo.as_deref());out["overlays"] = o.boxes(&l).into_iter().map(|(k, r)| json!({"kind": k.id(), "box": rect(r)})).collect();+ if let Some(t) = &template {+ out["template"] = json!(t.id);+ }deliver(&png, path, &mut out)?;Ok(out)}@@ -192,6 +209,104 @@ fn base64(bytes: &[u8]) -> String {out}+// ------------------------------------------------------------------------------- templates++/// The settings as the `slideshow.*` commands return them (for template replies).+fn settings_json(s: &Session) -> Value {+ json!({+ "playback": s.slideshow.to_json(),+ "layout": s.slide_layout.to_json(),+ "overlays": s.slide_overlays.to_json(),+ "titles": s.slide_titles.to_json(),+ })+}++fn tpl_list(s: &mut Session, _p: &Value) -> Result<Value> {+ let l = s.slide_templates();+ Ok(json!({+ "templates": l.templates.iter().map(|t| t.info()).collect::<Vec<_>>(),+ "previous": s.slide_templates_previous.is_some(),+ "folder": s.slide_templates_dir.as_ref().map(|d| d.to_string_lossy().to_string()),+ "problems": l.problems,+ }))+}++/// The template `id` or `name` names.+fn named(s: &mut Session, p: &Value, c: &str) -> Result<std::sync::Arc<tpl::Template>> {+ s.slide_template_named(str_param(p, "id"), str_param(p, "name")).map_err(|e| bad(c, e))+}++fn tpl_apply(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "slideshow.templates.apply";+ let t = named(s, p, C)?;+ let warnings = s.apply_slide_look(&t.look)?;+ let mut out = json!({"applied": t.id, "name": t.name, "warnings": warnings, "previous": s.slide_templates_previous.is_some()});+ out["settings"] = settings_json(s);+ Ok(out)+}++fn tpl_reply(t: &tpl::Template) -> Value {+ t.info()+}++fn tpl_save(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "slideshow.templates.save";+ let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;+ let replace = match p.get("replace") {+ None | Some(Value::Null) => false,+ Some(v) => v.as_bool().ok_or_else(|| bad(C, format!("`replace` must be true or false, not {v}")))?,+ };+ let t = s.save_slide_template(name, replace).map_err(|e| bad(C, e))?;+ Ok(tpl_reply(&t))+}++fn id_param<'a>(p: &'a Value, c: &str) -> Result<&'a str> {+ str_param(p, "id").map(str::trim).filter(|x| !x.is_empty()).ok_or_else(|| bad(c, "missing `id` (a template id from slideshow.templates.list)"))+}++fn tpl_update(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "slideshow.templates.update";+ let id = id_param(p, C)?;+ let t = s.update_slide_template(id).map_err(|e| bad(C, e))?;+ Ok(tpl_reply(&t))+}++fn tpl_rename(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "slideshow.templates.rename";+ let id = id_param(p, C)?;+ let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;+ let t = s.rename_slide_template(id, name).map_err(|e| bad(C, e))?;+ Ok(tpl_reply(&t))+}++fn tpl_delete(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "slideshow.templates.delete";+ let id = id_param(p, C)?;+ let t = s.delete_slide_template(id).map_err(|e| bad(C, e))?;+ Ok(json!({"deleted": t.id, "name": t.name}))+}++fn tpl_import(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "slideshow.templates.import";+ let path = str_param(p, "path").map(str::trim).filter(|x| !x.is_empty()).ok_or_else(|| bad(C, "missing `path`"))?;+ let (t, renamed) = s.import_slide_template(std::path::Path::new(path)).map_err(|e| bad(C, e))?;+ let mut out = tpl_reply(&t);+ out["renamed"] = json!(renamed);+ out["warnings"] = json!(t.look.warnings(s));+ Ok(out)+}++fn tpl_export(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "slideshow.templates.export";+ let id = id_param(p, C)?;+ let path = str_param(p, "path").map(str::trim).filter(|x| !x.is_empty()).ok_or_else(|| bad(C, "missing `path`"))?;+ let t = s.slide_template(id).map_err(|e| bad(C, e))?;+ s.check_write_target(path).map_err(|e| bad(C, e))?;+ let bytes = serde_json::to_vec_pretty(&t.to_doc()).map_err(|e| crate::EngineError::Other(e.to_string()))?;+ crate::export::write_file(path, &bytes).map_err(crate::EngineError::Other)?;+ Ok(json!({"id": t.id, "name": t.name, "path": path}))+}+pub fn specs() -> Vec<CommandSpec> {vec![cmd!(@@ -230,12 +345,84 @@ pub fn specs() -> Vec<CommandSpec> {always,titles),+ cmd!(+ query "slideshow.templates.list",+ "Slideshow Templates",+ [],+ None,+ "{} → {templates: [{id: \"builtin:…\"|\"user:…\", name, builtin, group: \"builtin\"|\"user\", description?, path? (a user template's file)}], previous: bool (the settings before the last apply can be restored with apply {id: \"previous\"}), folder: the user templates folder | null, problems: [\"file: why it was skipped\"]} — built-ins first, then user templates by name (files in <settings>/slideshow-templates, at most 1000)",+ always,+ tpl_list+ ),+ cmd!(+ "slideshow.templates.apply",+ "Apply Slideshow Template",+ [],+ None,+ "{id: template id | \"previous\" (the settings before the last apply) | name: template name (case-insensitive)} — replaces the playback (prepare previews kept), layout, overlays and titles settings with the template's and saves them with the library; there is no undo: the replaced settings are kept as \"previous\" for this session → {applied, name, warnings: [a background photo not in this library, an unreadable identity plate / watermark image…], previous, settings: {playback, layout, overlays, titles}}",+ always,+ tpl_apply+ ),+ cmd!(+ "slideshow.templates.save",+ "Save Slideshow Template",+ [],+ None,+ "{name: 1–80 characters, replace?: bool (over a user template of that name)} — the current playback, layout, overlays and titles settings as a user template, <settings>/slideshow-templates/<name>.json (path separators and other reserved characters become _); a name taken (case-insensitive) or a built-in's is refused unless replace → {id, name, builtin, group, path}",+ always,+ tpl_save+ ),+ cmd!(+ "slideshow.templates.update",+ "Update Slideshow Template",+ [],+ None,+ "{id: user template} — replace its settings with the current ones (name kept); built-ins can't change → {id, name, builtin, group, path}",+ always,+ tpl_update+ ),+ cmd!(+ "slideshow.templates.rename",+ "Rename Slideshow Template",+ [],+ None,+ "{id: user template, name} — its file follows the name; a name taken is refused → {id (the new one), name, builtin, group, path}",+ always,+ tpl_rename+ ),+ cmd!(+ "slideshow.templates.delete",+ "Delete Slideshow Template",+ [],+ None,+ "{id: user template} — deletes its file → {deleted, name}",+ always,+ tpl_delete+ ),+ cmd!(+ "slideshow.templates.import",+ "Import Slideshow Template",+ [],+ None,+ "{path: a template .json file (at most 256 KB)} — checked like a saved one (format, version, every setting) and saved as a user template under its name (else the file's); a name taken gets \" (2)\"… → {id, name, builtin, group, path, renamed, warnings}",+ always,+ tpl_import+ ),+ cmd!(+ "slideshow.templates.export",+ "Export Slideshow Template",+ [],+ None,+ "{id: template (built-in or user), path: .json file to write} → {id, name, path}",+ always,+ tpl_export+ ),cmd!(query "slideshow.preview","Slideshow Slide Preview",[],None,- "{id?: photo (default: the active one) | title?: \"intro\"|\"ending\", width?, height?: pixels (16–4096; one given: the other from the aspect preview; neither: 1280 wide), path?: write the PNG here} — the photo's slide composed with the slideshow layout and overlays → {id, width, height, cell: [x0,y0,x1,y1], photo: [x0,y0,x1,y1] (the visible photo, slide pixels), overlays: [{kind: identityPlate|ratingStars|textN|watermark, box: [x0,y0,x1,y1]}], path | png (base64 PNG)}; with `title`, that title screen (`slideshow.titles`; drawn even while it is off) → {title, enabled, width, height, plate: [x0,y0,x1,y1] | null (the plate or text), path | png}",+ "{id?: photo (default: the active one) | title?: \"intro\"|\"ending\", template?: a template id (slideshow.templates.list): compose with its settings instead of the library's, which don't change (the Template Browser's hover preview), width?, height?: pixels (16–4096; one given: the other from the aspect preview; neither: 1280 wide), path?: write the PNG here} — the photo's slide composed with the slideshow layout and overlays → {id, width, height, cell: [x0,y0,x1,y1], photo: [x0,y0,x1,y1] (the visible photo, slide pixels), overlays: [{kind: identityPlate|ratingStars|textN|watermark, box: [x0,y0,x1,y1]}], path | png (base64 PNG)}; with `title`, that title screen (`slideshow.titles`; drawn even while it is off) → {title, enabled, width, height, plate: [x0,y0,x1,y1] | null (the plate or text), path | png}",always,preview),diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 00f39baec..5cb09fd87 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -57,6 +57,7 @@ pub mod segment;pub mod sidecar;pub mod slide;pub mod slide_overlay;+pub mod slide_template;pub mod slide_title;pub mod slideshow;pub mod smart;@@ -285,6 +286,14 @@ pub struct Session {pub slide_overlays: slide_overlay::OverlaySettings,/// Slideshow intro and ending screens (`slideshow.titles`; persisted in prefs.json).pub slide_titles: slide_title::TitleSettings,+ /// Where user slideshow templates are kept (`<config>/slideshow-templates`;+ /// [`Session::with_default_slide_templates`]). `None`: the built-in templates only.+ pub slide_templates_dir: Option<std::path::PathBuf>,+ /// The slideshow settings before the last template was applied ("Previous settings"; this+ /// session only: library preferences have no undo).+ pub slide_templates_previous: Option<slide_template::SlideLook>,+ /// The templates as last listed.+ pub(crate) slide_templates_cache: slide_template::Cache,/// The background image the slides last rendered (shared by slide jobs: rendered once).pub slide_backdrop: std::sync::Arc<slide::BackdropCache>,/// Where smart previews are kept when not in the library folder (persisted in prefs.json).@@ -373,6 +382,9 @@ impl Session {slide_layout: slide::SlideSettings::default(),slide_overlays: slide_overlay::OverlaySettings::default(),slide_titles: slide_title::TitleSettings::default(),+ slide_templates_dir: None,+ slide_templates_previous: None,+ slide_templates_cache: None,slide_backdrop: Default::default(),smart_previews_dir: None,forget_local_days: lightcraft_catalog::DEFAULT_FORGET_DAYS,diff --git a/crates/engine/src/slide.rs b/crates/engine/src/slide.rsindex ab252cf6d..009a2e2ac 100644--- a/crates/engine/src/slide.rs+++ b/crates/engine/src/slide.rs@@ -103,6 +103,19 @@ impl crate::Session {/// (the photo `settings.background_image` names, when it is in the catalog) and the library's/// overlays resolved for `photo`.pub fn slide_compose(&mut self, settings: &SlideSettings, width: usize, height: usize, photo: Option<PhotoId>) -> Arc<SlideCompose> {+ let overlays = self.slide_overlays.clone();+ self.slide_compose_with(settings, &overlays, width, height, photo)+ }++ /// [`Self::slide_compose`] with `overlays` in place of the library's (a template's preview).+ pub fn slide_compose_with(+ &mut self,+ settings: &SlideSettings,+ overlays: &crate::slide_overlay::OverlaySettings,+ width: usize,+ height: usize,+ photo: Option<PhotoId>,+ ) -> Arc<SlideCompose> {let settings = settings.clone().sanitized();let backdrop = settings.background_image.filter(|_| settings.background_opacity > 0.0).and_then(|bid| {let id = PhotoId(bid);@@ -113,9 +126,9 @@ impl crate::Session {let job = self.render_job(id, w, h, false, true)?;Some(Backdrop { photo: id, job: Box::new(job), cache: self.slide_backdrop.clone() })});- let overlays = self.slide_overlays.any().then(|| {+ let overlays = overlays.any().then(|| {let p = photo.and_then(|id| self.catalog.photo(id));- Arc::new(crate::slide_overlay::SlideOverlays::resolve(&self.slide_overlays, p.map(|p| &**p)))+ Arc::new(crate::slide_overlay::SlideOverlays::resolve(overlays, p.map(|p| &**p)))});Arc::new(SlideCompose { settings, width, height, backdrop, overlays })}@@ -139,6 +152,22 @@ impl crate::Session {height: usize,photo_edge: Option<usize>,view: bool,+ ) -> Option<RenderJob> {+ let overlays = self.slide_overlays.clone();+ self.slide_job_look(settings, &overlays, id, width, height, photo_edge, view)+ }++ /// [`Self::slide_job_with`] with `overlays` in place of the library's (a template's preview).+ #[allow(clippy::too_many_arguments)]+ pub fn slide_job_look(+ &mut self,+ settings: &SlideSettings,+ overlays: &crate::slide_overlay::OverlaySettings,+ id: PhotoId,+ width: usize,+ height: usize,+ photo_edge: Option<usize>,+ view: bool,) -> Option<RenderJob> {let aspect = self.slide_photo_aspect(id)?;let (mut w, mut h) = lightcraft_slideshow::photo_size(settings, aspect, width, height);@@ -147,13 +176,26 @@ impl crate::Session {(w, h) = (((w as f64 * k).round() as usize).max(1), ((h as f64 * k).round() as usize).max(1));}let job = if view { self.loupe_job(id, w.max(8), h.max(8), true)? } else { self.render_job(id, w.max(8), h.max(8), false, true)? };- let compose = self.slide_compose(settings, width, height, Some(id));+ let compose = self.slide_compose_with(settings, overlays, width, height, Some(id));Some(job.with_slide(compose))}/// Photo `id`'s slide at `width × height` with `settings`, rendered now on this thread.pub fn slide_now(&mut self, settings: &SlideSettings, id: PhotoId, width: usize, height: usize) -> Result<Rgba8, String> {- let job = self.slide_job_with(settings, id, width, height, None, false).ok_or("no such photo")?;+ let overlays = self.slide_overlays.clone();+ self.slide_now_look(settings, &overlays, id, width, height)+ }++ /// [`Self::slide_now`] with `overlays` in place of the library's.+ pub fn slide_now_look(+ &mut self,+ settings: &SlideSettings,+ overlays: &crate::slide_overlay::OverlaySettings,+ id: PhotoId,+ width: usize,+ height: usize,+ ) -> Result<Rgba8, String> {+ let job = self.slide_job_look(settings, overlays, id, width, height, None, false).ok_or("no such photo")?;let r = job.run();self.accept(&r);r.rendered.map(|r| r.image)diff --git a/crates/engine/src/slide_template.rs b/crates/engine/src/slide_template.rsnew file mode 100644index 000000000..32e26ed59--- /dev/null+++ b/crates/engine/src/slide_template.rs@@ -0,0 +1,632 @@+//! Slideshow templates (Lightroom Classic's Template Browser): a named snapshot of how a+//! slideshow looks and plays — the Playback settings, the slide's Layout / Options / Backdrop,+//! the Overlays and the Titles — as one JSON document with a format version.+//!+//! Built-in templates are our own designs ([`builtins`], JSON files beside this module). User+//! templates are files in the settings folder, `<config>/slideshow-templates/<name>.json`+//! ([`Session::slide_templates_dir`]); they are shared by every library on the machine, like+//! Lightroom's templates. Every section is read through the settings' own `merged()` (so a+//! hand-edited or hostile file can never set a value the panels couldn't), files are capped in+//! size and number, a file that can't be used is reported and skipped, and file names are made+//! from the template's name so they can never leave the templates folder.+//!+//! Applying a template replaces the four settings in one step and saves them with the library.+//! Library preferences have no undo, so the settings it replaced are kept for the session as+//! "Previous settings" ([`PREVIOUS`]): applying that puts them back (and applying it again goes+//! forward). "Prepare previews" is a machine preference, not part of a look: templates neither+//! save nor change it.++use std::path::{Path, PathBuf};+use std::sync::Arc;++use serde_json::{Map, Value, json};++use crate::Session;+use crate::slide::SlideSettings;+use crate::slide_overlay::OverlaySettings;+use crate::slide_title::TitleSettings;+use crate::slideshow::PlaybackSettings;++/// The `format` of a template document.+pub const FORMAT: &str = "lightcraft.slideshowTemplate";+/// The newest document version this build reads (and the one it writes).+pub const VERSION: u64 = 1;+/// Largest template file read (bytes).+pub const MAX_FILE: u64 = 256 * 1024;+/// Most user templates listed (the rest of a folder that holds more are reported, not read).+pub const MAX_TEMPLATES: usize = 1000;+/// Directory entries looked at before giving up on a huge folder.+const MAX_SCAN: usize = 20_000;+/// Longest template name (characters).+pub const NAME_MAX: usize = 80;+/// Longest description (characters).+pub const DESCRIPTION_MAX: usize = 500;+/// Longest file stem made from a name (characters).+const STEM_MAX: usize = 64;+/// The folder under the settings folder user templates live in.+pub const DIR_NAME: &str = "slideshow-templates";+/// Id prefix of built-in templates.+pub const BUILTIN: &str = "builtin:";+/// Id prefix of user templates (followed by the file stem).+pub const USER: &str = "user:";+/// Id of the settings before the last template was applied.+pub const PREVIOUS: &str = "previous";++/// Everything a template sets.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct SlideLook {+ pub playback: PlaybackSettings,+ pub layout: SlideSettings,+ pub overlays: OverlaySettings,+ pub titles: TitleSettings,+}++impl SlideLook {+ /// The library's current slideshow settings.+ pub fn of(s: &Session) -> SlideLook {+ SlideLook {+ playback: s.slideshow.clone(),+ layout: s.slide_layout.clone(),+ overlays: s.slide_overlays.clone(),+ titles: s.slide_titles.clone(),+ }+ }++ /// The four sections as JSON (playback without `preparePreviews`, which isn't part of a look).+ pub fn sections(&self) -> Map<String, Value> {+ let mut playback = self.playback.to_json();+ if let Some(o) = playback.as_object_mut() {+ o.remove("preparePreviews");+ }+ let mut m = Map::new();+ m.insert("playback".into(), playback);+ m.insert("layout".into(), self.layout.to_json());+ m.insert("overlays".into(), self.overlays.to_json());+ m.insert("titles".into(), self.titles.to_json());+ m+ }++ /// Read the sections of a template document: each one merged onto the defaults by the+ /// settings' own validation (a missing section is the defaults; a wrong type, an unknown key+ /// or a non-finite number is an error).+ fn from_sections(doc: &Map<String, Value>) -> Result<SlideLook, String> {+ fn section<T>(doc: &Map<String, Value>, key: &str, merge: impl Fn(&Value) -> Result<T, String>, default: T) -> Result<T, String> {+ match doc.get(key) {+ None | Some(Value::Null) => Ok(default),+ Some(v @ Value::Object(_)) => merge(v).map_err(|e| format!("{key}: {e}")),+ Some(v) => Err(format!("`{key}` must be an object, not {v}")),+ }+ }+ let mut playback = section(doc, "playback", |v| PlaybackSettings::default().merged(v), PlaybackSettings::default())?;+ playback.prepare_previews = PlaybackSettings::default().prepare_previews;+ Ok(SlideLook {+ playback,+ layout: section(doc, "layout", |v| SlideSettings::default().merged(v), SlideSettings::default())?,+ overlays: section(doc, "overlays", |v| OverlaySettings::default().merged(v), OverlaySettings::default())?,+ titles: section(doc, "titles", |v| TitleSettings::default().merged(v), TitleSettings::default())?,+ })+ }++ /// What doesn't work with this look in `s`'s library: a background photo that isn't in it,+ /// an identity plate or watermark image file that can't be read, unknown tokens, a title+ /// screen with nothing to show. The look still applies; these draw nothing.+ pub fn warnings(&self, s: &Session) -> Vec<String> {+ let mut out = Vec::new();+ if let Some(id) = self.layout.background_image+ && s.catalog.photo(lightcraft_catalog::PhotoId(id)).is_none()+ {+ out.push(format!("the background image (photo {id}) isn't in this library; the backdrop colour shows instead"));+ }+ out.extend(self.overlays.warnings());+ let w = &self.overlays.watermark;+ if self.overlays.show_watermark && !w.image.trim().is_empty() && crate::export::watermark_logo(w.image.trim()).is_none() {+ out.push(format!("watermark image {} can't be read; nothing is drawn", w.image.trim()));+ }+ for t in self.titles.warnings(&self.overlays) {+ if !out.contains(&t) {+ out.push(t);+ }+ }+ out+ }+}++/// A template: built in or a user's file.+#[derive(Clone, Debug, PartialEq)]+pub struct Template {+ /// `builtin:<slug>` or `user:<file stem>`.+ pub id: String,+ pub name: String,+ pub description: String,+ pub builtin: bool,+ /// The file a user template is read from.+ pub path: Option<PathBuf>,+ pub look: SlideLook,+}++impl Template {+ /// The template as a document (what a user template's file holds, and what export writes).+ pub fn to_doc(&self) -> Value {+ doc(&self.name, &self.description, &self.look)+ }++ /// The template for listings (no settings).+ pub fn info(&self) -> Value {+ let mut v = json!({+ "id": self.id,+ "name": self.name,+ "builtin": self.builtin,+ "group": if self.builtin { "builtin" } else { "user" },+ });+ if !self.description.is_empty() {+ v["description"] = json!(self.description);+ }+ if let Some(p) = &self.path {+ v["path"] = json!(p.to_string_lossy());+ }+ v+ }+}++/// A template document for `look`.+pub fn doc(name: &str, description: &str, look: &SlideLook) -> Value {+ let mut m = Map::new();+ m.insert("format".into(), json!(FORMAT));+ m.insert("version".into(), json!(VERSION));+ m.insert("name".into(), json!(name));+ if !description.is_empty() {+ m.insert("description".into(), json!(description));+ }+ m.extend(look.sections());+ Value::Object(m)+}++/// A template document read and checked: its name (`None` when it has none), description and look.+#[derive(Clone, Debug, PartialEq)]+pub struct Parsed {+ pub name: Option<String>,+ pub description: String,+ pub look: SlideLook,+}++/// Read a template document. Refused: more than [`MAX_FILE`] bytes, not JSON, another format, a+/// version from a newer LightCraft, a bad name, unknown keys and any setting its section's+/// validation refuses.+pub fn parse(bytes: &[u8]) -> Result<Parsed, String> {+ if bytes.len() as u64 > MAX_FILE {+ return Err(format!("{} bytes is too large for a slideshow template (at most {} KB)", bytes.len(), MAX_FILE / 1024));+ }+ let text = std::str::from_utf8(bytes).map_err(|_| "not a slideshow template (not UTF-8 text)".to_string())?;+ let text = text.trim_start_matches('\u{feff}');+ let v: Value = serde_json::from_str(text).map_err(|e| format!("not a slideshow template: {e}"))?;+ let Value::Object(o) = v else { return Err("not a slideshow template (not a JSON object)".into()) };+ match o.get("format").and_then(Value::as_str) {+ Some(FORMAT) => {}+ Some(other) => return Err(format!("not a slideshow template (format `{other}`, expected `{FORMAT}`)")),+ None => return Err(format!("not a slideshow template (no `format`: \"{FORMAT}\")")),+ }+ match o.get("version") {+ Some(v) => match v.as_u64() {+ Some(n) if n > VERSION => {+ return Err(format!(+ "made by a newer LightCraft (template version {n}; this one reads version {VERSION}): update LightCraft to use it"+ ));+ }+ Some(n) if n >= 1 => {}+ _ => return Err(format!("`version` must be a whole number from 1, not {v}")),+ },+ None => return Err("no `version`".into()),+ }+ for k in o.keys() {+ if !matches!(k.as_str(), "format" | "version" | "name" | "description" | "playback" | "layout" | "overlays" | "titles") {+ return Err(format!("unknown key `{k}` (format, version, name, description, playback, layout, overlays, titles)"));+ }+ }+ let name = match o.get("name") {+ None | Some(Value::Null) => None,+ Some(Value::String(n)) if n.trim().is_empty() => None,+ Some(Value::String(n)) => Some(valid_name(n)?),+ Some(v) => return Err(format!("`name` must be text, not {v}")),+ };+ let description = match o.get("description") {+ None | Some(Value::Null) => String::new(),+ Some(Value::String(d)) => clean_text(d, DESCRIPTION_MAX),+ Some(v) => return Err(format!("`description` must be text, not {v}")),+ };+ Ok(Parsed { name, description, look: SlideLook::from_sections(&o)? })+}++/// `s` without control characters, trimmed, at most `max` characters.+fn clean_text(s: &str, max: usize) -> String {+ s.chars().filter(|c| !c.is_control()).take(max).collect::<String>().trim().to_string()+}++/// A template name as stored: trimmed, 1–[`NAME_MAX`] characters, no control characters.+pub fn valid_name(name: &str) -> Result<String, String> {+ let n = name.trim();+ if n.is_empty() {+ return Err("a template needs a name".into());+ }+ if n.chars().any(char::is_control) {+ return Err("a template name can't contain control characters (line breaks, tabs…)".into());+ }+ if n.chars().count() > NAME_MAX {+ return Err(format!("a template name has at most {NAME_MAX} characters"));+ }+ Ok(n.to_string())+}++/// The file stem a template called `name` is saved as: letters, digits, spaces, `-`, `_`, `(`+/// and `)` kept, anything else (path separators, dots, `:`, `*`…) `_`; trimmed; at most 64+/// characters; Windows' reserved device names get a `_`. `None` when nothing usable is left.+pub fn file_stem(name: &str) -> Option<String> {+ let s: String =+ name.trim().chars().map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-' | '_' | '(' | ')') { c } else { '_' }).take(STEM_MAX).collect();+ let s = s.trim().to_string();+ if s.is_empty() || s.chars().all(|c| c == '_') {+ return None;+ }+ let upper = s.to_ascii_uppercase();+ let reserved = matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")+ || ((upper.starts_with("COM") || upper.starts_with("LPT")) && upper.len() == 4 && upper.ends_with(|c: char| c.is_ascii_digit()));+ Some(if reserved { format!("{s}_") } else { s })+}++/// The stem of a user template id, when it is one this module could have made (so it can't+/// name a file outside the templates folder).+fn user_stem(id: &str) -> Option<&str> {+ let stem = id.strip_prefix(USER)?;+ (file_stem(stem).as_deref() == Some(stem)).then_some(stem)+}++/// The built-in templates: our own designs (no Lightroom template, name or design copied).+const BUILTINS: &[(&str, &str)] = &[+ ("plain-black", include_str!("slideshow_templates/plain-black.json")),+ ("gallery-wall", include_str!("slideshow_templates/gallery-wall.json")),+ ("edge-to-edge", include_str!("slideshow_templates/edge-to-edge.json")),+ ("cinema-wide", include_str!("slideshow_templates/cinema-wide.json")),+ ("shooting-data", include_str!("slideshow_templates/shooting-data.json")),+];++/// The built-in templates (one that doesn't parse — a bug the tests catch — is left out).+pub fn builtins() -> Vec<Template> {+ BUILTINS+ .iter()+ .filter_map(|(slug, json)| {+ let p = parse(json.as_bytes()).inspect_err(|e| eprintln!("lightcraft: built-in slideshow template {slug}: {e}")).ok()?;+ Some(Template {+ id: format!("{BUILTIN}{slug}"),+ name: p.name.unwrap_or_else(|| (*slug).to_string()),+ description: p.description,+ builtin: true,+ path: None,+ look: p.look,+ })+ })+ .collect()+}++/// Every template, and what couldn't be read.+#[derive(Clone, Debug, Default)]+pub struct Listing {+ /// Built-ins first (in their order), then user templates by name.+ pub templates: Vec<Arc<Template>>,+ /// Files skipped, each with why.+ pub problems: Vec<String>,+}++impl Listing {+ pub fn get(&self, id: &str) -> Option<&Arc<Template>> {+ self.templates.iter().find(|t| t.id == id)+ }++ /// A template by name (case-insensitive); a user template before a built-in.+ pub fn by_name(&self, name: &str) -> Option<&Arc<Template>> {+ let n = name.trim().to_lowercase();+ let mut hits = self.templates.iter().filter(|t| t.name.to_lowercase() == n);+ let first = hits.next()?;+ Some(hits.find(|t| !t.builtin).unwrap_or(first))+ }+}++/// When the templates folder last changed (the listing is read again when this does).+type Stamp = (Option<PathBuf>, Option<std::time::SystemTime>);++/// The cached listing and the folder stamp it was read at.+pub type Cache = Option<(Stamp, Arc<Listing>)>;++fn stamp(dir: Option<&Path>) -> Stamp {+ (dir.map(Path::to_path_buf), dir.and_then(|d| std::fs::metadata(d).ok()).and_then(|m| m.modified().ok()))+}++/// Read the user templates in `dir`: `*.json` regular files, at most [`MAX_TEMPLATES`], each+/// parsed and checked; anything else reported.+fn read_dir(dir: &Path, out: &mut Listing) {+ let entries = match std::fs::read_dir(dir) {+ Ok(e) => e,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,+ Err(e) => {+ out.problems.push(format!("{}: {e}", dir.display()));+ return;+ }+ };+ let mut files: Vec<(String, PathBuf)> = Vec::new();+ for entry in entries.take(MAX_SCAN).flatten() {+ let path = entry.path();+ let is_json = path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("json"));+ if !is_json {+ continue;+ }+ let file = entry.file_name().to_string_lossy().to_string();+ files.push((file, path));+ }+ files.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()).then_with(|| a.0.cmp(&b.0)));+ if files.len() > MAX_TEMPLATES {+ out.problems.push(format!("{}: {} template files; only the first {MAX_TEMPLATES} are listed", dir.display(), files.len()));+ files.truncate(MAX_TEMPLATES);+ }+ let mut user = Vec::new();+ for (file, path) in files {+ match read_user(&file, &path) {+ Ok(t) => user.push(Arc::new(t)),+ Err(e) => out.problems.push(format!("{file}: {e}")),+ }+ }+ user.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.id.cmp(&b.id)));+ out.templates.extend(user);+}++/// One user template file.+fn read_user(file: &str, path: &Path) -> Result<Template, String> {+ let stem = file.get(..file.len().saturating_sub(5)).unwrap_or_default();+ if file_stem(stem).as_deref() != Some(stem) {+ return Err("the file name isn't one LightCraft makes (letters, digits, spaces, - _ ( ) only); rename the file".into());+ }+ let meta = std::fs::symlink_metadata(path).map_err(|e| e.to_string())?;+ if !meta.file_type().is_file() {+ return Err("not a regular file (a link or a folder)".into());+ }+ if meta.len() > MAX_FILE {+ return Err(format!("{} bytes is too large for a slideshow template (at most {} KB)", meta.len(), MAX_FILE / 1024));+ }+ let bytes = std::fs::read(path).map_err(|e| e.to_string())?;+ let p = parse(&bytes)?;+ Ok(Template {+ id: format!("{USER}{stem}"),+ name: p.name.unwrap_or_else(|| stem.to_string()),+ description: p.description,+ builtin: false,+ path: Some(path.to_path_buf()),+ look: p.look,+ })+}++/// Read a template file the user picked (import): size-capped, then [`parse`]d. Its name is the+/// document's, else the file's.+pub fn read_file(path: &Path) -> Result<Parsed, String> {+ let meta = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;+ if !meta.is_file() {+ return Err(format!("{}: not a file", path.display()));+ }+ if meta.len() > MAX_FILE {+ return Err(format!("{}: {} bytes is too large for a slideshow template (at most {} KB)", path.display(), meta.len(), MAX_FILE / 1024));+ }+ let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;+ let mut p = parse(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;+ if p.name.is_none() {+ let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();+ p.name = valid_name(&clean_text(&stem, NAME_MAX)).ok();+ }+ Ok(p)+}++fn write_json(path: &Path, v: &Value) -> Result<(), String> {+ let bytes = serde_json::to_vec_pretty(v).map_err(|e| e.to_string())?;+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ }+ lightcraft_catalog::safe_file::write_atomic(path, &bytes).map_err(|e| format!("{}: {e}", path.display()))+}++impl Session {+ /// Keep user slideshow templates in `<config>/slideshow-templates` (hosts with a file system).+ pub fn with_default_slide_templates(mut self) -> Self {+ self.slide_templates_dir = crate::config::config_dir().map(|d| d.join(DIR_NAME));+ self+ }++ /// Every template (built-in, then the user's), read again when the templates folder changed.+ pub fn slide_templates(&mut self) -> Arc<Listing> {+ let now = stamp(self.slide_templates_dir.as_deref());+ if let Some((st, l)) = &self.slide_templates_cache+ && *st == now+ {+ return l.clone();+ }+ let mut l = Listing { templates: builtins().into_iter().map(Arc::new).collect(), problems: Vec::new() };+ if let Some(dir) = self.slide_templates_dir.clone() {+ read_dir(&dir, &mut l);+ }+ let l = Arc::new(l);+ self.slide_templates_cache = Some((now, l.clone()));+ l+ }++ /// Forget the cached listing (after a write: a folder's time may not change within its+ /// resolution).+ fn templates_changed(&mut self) {+ self.slide_templates_cache = None;+ }++ /// The template `id` (or [`PREVIOUS`], the settings before the last apply).+ pub fn slide_template(&mut self, id: &str) -> Result<Arc<Template>, String> {+ if id == PREVIOUS {+ let look = self.slide_templates_previous.clone().ok_or("no previous settings (no template has been applied this session)")?;+ return Ok(Arc::new(Template {+ id: PREVIOUS.into(),+ name: "Previous settings".into(),+ description: String::new(),+ builtin: false,+ path: None,+ look,+ }));+ }+ if id.starts_with(USER) && user_stem(id).is_none() {+ return Err(format!("`{id}` isn't a template id (user templates are `user:` and a file name LightCraft made)"));+ }+ self.slide_templates().get(id).cloned().ok_or_else(|| format!("no slideshow template `{id}`"))+ }++ /// The template a command names: `id`, or `name` (case-insensitive).+ pub fn slide_template_named(&mut self, id: Option<&str>, name: Option<&str>) -> Result<Arc<Template>, String> {+ match (id.map(str::trim).filter(|s| !s.is_empty()), name.map(str::trim).filter(|s| !s.is_empty())) {+ (Some(id), _) => self.slide_template(id),+ (None, Some(name)) => self.slide_templates().by_name(name).cloned().ok_or_else(|| format!("no slideshow template named \"{name}\"")),+ (None, None) => Err("name a template: `id` or `name`".into()),+ }+ }++ /// Replace the slideshow settings with `look` (prepare previews kept) and save them; the+ /// settings it replaced become [`PREVIOUS`]. Returns the warnings for this library.+ pub fn apply_slide_look(&mut self, look: &SlideLook) -> crate::Result<Vec<String>> {+ let before = SlideLook::of(self);+ let mut next = look.clone();+ next.playback.prepare_previews = self.slideshow.prepare_previews;+ let next = SlideLook {+ playback: next.playback.sanitized(),+ layout: next.layout.sanitized(),+ overlays: next.overlays.sanitized(),+ titles: next.titles.sanitized(),+ };+ let warnings = next.warnings(self);+ if next != before {+ (self.slideshow, self.slide_layout, self.slide_overlays, self.slide_titles) = (next.playback, next.layout, next.overlays, next.titles);+ if let Err(e) = self.save_prefs() {+ (self.slideshow, self.slide_layout, self.slide_overlays, self.slide_titles) =+ (before.playback, before.layout, before.overlays, before.titles);+ return Err(e);+ }+ self.slide_templates_previous = Some(before);+ }+ Ok(warnings)+ }++ fn templates_dir(&self) -> Result<PathBuf, String> {+ self.slide_templates_dir.clone().ok_or_else(|| {+ "user templates need a settings folder, and this LightCraft has none (the web build, or LIGHTCRAFT_CONFIG_DIR is set empty)".into()+ })+ }++ /// Is a user template file called `stem` there, or one whose name differs only in case?+ fn stem_taken(&mut self, dir: &Path, stem: &str, except: Option<&str>) -> bool {+ let lower = stem.to_lowercase();+ let other = |s: &str| except.is_none_or(|e| e.to_lowercase() != s.to_lowercase());+ (dir.join(format!("{stem}.json")).exists() && other(stem))+ || self.slide_templates().templates.iter().filter_map(|t| t.id.strip_prefix(USER)).any(|s| s.to_lowercase() == lower && other(s))+ }++ fn builtin_name(name: &str) -> bool {+ builtins().iter().any(|b| b.name.to_lowercase() == name.to_lowercase())+ }++ /// Save the current settings as user template `name` (`replace`: over one of that name).+ pub fn save_slide_template(&mut self, name: &str, replace: bool) -> Result<Arc<Template>, String> {+ let name = valid_name(name)?;+ if Self::builtin_name(&name) {+ return Err(format!("\"{name}\" is the name of a built-in template; pick another name"));+ }+ let stem = file_stem(&name).ok_or_else(|| format!("\"{name}\" has no letters or digits to make a file name from"))?;+ let dir = self.templates_dir()?;+ if !replace && self.stem_taken(&dir, &stem, None) {+ return Err(format!("a template named \"{name}\" (file {stem}.json) already exists: update it, or save under another name"));+ }+ let look = SlideLook::of(self);+ write_json(&dir.join(format!("{stem}.json")), &doc(&name, "", &look))?;+ self.templates_changed();+ self.slide_template(&format!("{USER}{stem}"))+ }++ /// A user template (not a built-in).+ fn user_template(&mut self, id: &str) -> Result<(Arc<Template>, PathBuf), String> {+ if id.starts_with(BUILTIN) {+ return Err(format!("`{id}` is a built-in template and can't be changed (save the settings as a template of your own)"));+ }+ if id == PREVIOUS {+ return Err("the previous settings aren't a saved template".into());+ }+ let t = self.slide_template(id)?;+ let path = t.path.clone().ok_or_else(|| format!("`{id}` isn't a user template"))?;+ Ok((t, path))+ }++ /// Replace user template `id`'s settings with the current ones (its name kept).+ pub fn update_slide_template(&mut self, id: &str) -> Result<Arc<Template>, String> {+ let (t, path) = self.user_template(id)?;+ write_json(&path, &doc(&t.name, &t.description, &SlideLook::of(self)))?;+ self.templates_changed();+ self.slide_template(id)+ }++ /// Rename user template `id` (its file follows the name).+ pub fn rename_slide_template(&mut self, id: &str, name: &str) -> Result<Arc<Template>, String> {+ let (t, path) = self.user_template(id)?;+ let name = valid_name(name)?;+ if Self::builtin_name(&name) {+ return Err(format!("\"{name}\" is the name of a built-in template; pick another name"));+ }+ let stem = file_stem(&name).ok_or_else(|| format!("\"{name}\" has no letters or digits to make a file name from"))?;+ let dir = self.templates_dir()?;+ let old = id.strip_prefix(USER).unwrap_or_default().to_string();+ if self.stem_taken(&dir, &stem, Some(&old)) {+ return Err(format!("a template named \"{name}\" (file {stem}.json) already exists"));+ }+ // the new name into the file, then the file to its new name (one rename: never two copies+ // or none, and a change of case works on case-insensitive file systems too)+ write_json(&path, &doc(&name, &t.description, &t.look))?;+ let to = dir.join(format!("{stem}.json"));+ if to != path {+ std::fs::rename(&path, &to).map_err(|e| format!("{}: {e}", to.display()))?;+ }+ self.templates_changed();+ self.slide_template(&format!("{USER}{stem}"))+ }++ /// Delete user template `id`'s file.+ pub fn delete_slide_template(&mut self, id: &str) -> Result<Arc<Template>, String> {+ let (t, path) = self.user_template(id)?;+ std::fs::remove_file(&path).map_err(|e| format!("{}: {e}", path.display()))?;+ self.templates_changed();+ Ok(t)+ }++ /// Import the template file at `path` as a user template. A name already taken gets " (2)",+ /// " (3)"…; returns the template and whether it was renamed.+ pub fn import_slide_template(&mut self, path: &Path) -> Result<(Arc<Template>, bool), String> {+ let p = read_file(path)?;+ let dir = self.templates_dir()?;+ let base = p.name.clone().ok_or_else(|| format!("{}: the template has no name, nor a file name to take one from", path.display()))?;+ let mut name = base.clone();+ let mut n = 1;+ loop {+ let free = !Self::builtin_name(&name) && file_stem(&name).is_some_and(|stem| !self.stem_taken(&dir, &stem, None));+ if free {+ break;+ }+ n += 1;+ if n > 999 {+ return Err(format!("too many templates named \"{base}\""));+ }+ let suffix = format!(" ({n})");+ let keep: String = base.chars().take(NAME_MAX.saturating_sub(suffix.chars().count())).collect();+ name = format!("{}{suffix}", keep.trim_end());+ }+ let stem = file_stem(&name).ok_or_else(|| format!("\"{name}\" has no letters or digits to make a file name from"))?;+ write_json(&dir.join(format!("{stem}.json")), &doc(&name, &p.description, &p.look))?;+ self.templates_changed();+ Ok((self.slide_template(&format!("{USER}{stem}"))?, name != base))+ }+}++#[cfg(test)]+#[path = "tests_slide_template.rs"]+mod tests;diff --git a/crates/engine/src/slideshow_templates/cinema-wide.json b/crates/engine/src/slideshow_templates/cinema-wide.jsonnew file mode 100644index 000000000..d8660d604--- /dev/null+++ b/crates/engine/src/slideshow_templates/cinema-wide.json@@ -0,0 +1,19 @@+{+ "format": "lightcraft.slideshowTemplate",+ "version": 1,+ "name": "Cinema Wide",+ "description": "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.",+ "playback": {"slideDuration": 6, "fadeDuration": 1.5, "fadeColor": "#000000", "randomOrder": false, "repeat": false},+ "layout": {+ "aspect": "16:9", "linkMargins": false, "marginLeft": 0, "marginRight": 0, "marginTop": 0.09, "marginBottom": 0.09,+ "zoomToFill": true, "backdropColor": "#000000"+ },+ "overlays": {+ "texts": [+ {"text": "{title}", "size": 0.03, "color": "#f0ece4", "opacity": 0.9, "anchor": "bottomLeft", "offsetX": 0.04, "offsetY": -0.025, "relativeTo": "slide", "shadow": false}+ ]+ },+ "titles": {+ "ending": {"enabled": true, "color": "#000000", "content": "text", "text": "The End", "overrideColor": true, "textColor": "#e8e2d6", "scale": 0.07, "duration": 3}+ }+}diff --git a/crates/engine/src/slideshow_templates/edge-to-edge.json b/crates/engine/src/slideshow_templates/edge-to-edge.jsonnew file mode 100644index 000000000..ba2943342--- /dev/null+++ b/crates/engine/src/slideshow_templates/edge-to-edge.json@@ -0,0 +1,10 @@+{+ "format": "lightcraft.slideshowTemplate",+ "version": 1,+ "name": "Edge to Edge",+ "description": "Every photo cropped to fill the whole screen, with slow crossfades.",+ "playback": {"slideDuration": 6, "fadeDuration": 2, "fadeColor": null, "randomOrder": false, "repeat": true},+ "layout": {"zoomToFill": true},+ "overlays": {},+ "titles": {}+}diff --git a/crates/engine/src/slideshow_templates/gallery-wall.json b/crates/engine/src/slideshow_templates/gallery-wall.jsonnew file mode 100644index 000000000..7703795a5--- /dev/null+++ b/crates/engine/src/slideshow_templates/gallery-wall.json@@ -0,0 +1,20 @@+{+ "format": "lightcraft.slideshowTemplate",+ "version": 1,+ "name": "Gallery Wall",+ "description": "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.",+ "playback": {"slideDuration": 5, "fadeDuration": 1.2, "fadeColor": null, "randomOrder": false, "repeat": true},+ "layout": {+ "linkMargins": false, "marginLeft": 0.1, "marginRight": 0.1, "marginTop": 0.08, "marginBottom": 0.16,+ "strokeBorder": true, "strokeColor": "#ffffff", "strokeWidth": 0.012,+ "castShadow": true, "shadowOpacity": 0.35, "shadowOffset": 0.012, "shadowRadius": 0.02, "shadowAngle": -60,+ "backdropColor": "#dcd9d4"+ },+ "overlays": {+ "ratingStars": {"enabled": true, "color": "#55524d", "size": 0.03, "anchor": "bottomRight", "offsetX": 0, "offsetY": 0.075, "relativeTo": "photo"},+ "texts": [+ {"text": "{caption}", "size": 0.032, "color": "#3c3a36", "opacity": 1, "anchor": "bottomLeft", "offsetX": 0, "offsetY": 0.08, "relativeTo": "photo", "shadow": false}+ ]+ },+ "titles": {}+}diff --git a/crates/engine/src/slideshow_templates/plain-black.json b/crates/engine/src/slideshow_templates/plain-black.jsonnew file mode 100644index 000000000..83085cedb--- /dev/null+++ b/crates/engine/src/slideshow_templates/plain-black.json@@ -0,0 +1,10 @@+{+ "format": "lightcraft.slideshowTemplate",+ "version": 1,+ "name": "Plain Black",+ "description": "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.",+ "playback": {"slideDuration": 4, "fadeDuration": 1, "fadeColor": null, "randomOrder": false, "repeat": true},+ "layout": {},+ "overlays": {},+ "titles": {}+}diff --git a/crates/engine/src/slideshow_templates/shooting-data.json b/crates/engine/src/slideshow_templates/shooting-data.jsonnew file mode 100644index 000000000..4e95fcddf--- /dev/null+++ b/crates/engine/src/slideshow_templates/shooting-data.json@@ -0,0 +1,18 @@+{+ "format": "lightcraft.slideshowTemplate",+ "version": 1,+ "name": "Shooting Data",+ "description": "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.",+ "playback": {"slideDuration": 5, "fadeDuration": 0.8, "fadeColor": null, "randomOrder": false, "repeat": true},+ "layout": {+ "linkMargins": false, "marginLeft": 0.05, "marginRight": 0.05, "marginTop": 0.05, "marginBottom": 0.15,+ "backdropColor": "#1d2126", "colorWash": true, "washColor": "#3a4550", "washOpacity": 0.7, "washAngle": 90+ },+ "overlays": {+ "texts": [+ {"text": "{exposure} ISO {iso} {focal}", "size": 0.034, "color": "#e6e8ea", "opacity": 1, "anchor": "bottom", "offsetX": 0, "offsetY": -0.062, "relativeTo": "slide", "shadow": false},+ {"text": "{camera} {lens}", "size": 0.026, "color": "#9aa4ae", "opacity": 1, "anchor": "bottom", "offsetX": 0, "offsetY": -0.024, "relativeTo": "slide", "shadow": false}+ ]+ },+ "titles": {}+}diff --git a/crates/engine/src/tests_slide_template.rs b/crates/engine/src/tests_slide_template.rsnew file mode 100644index 000000000..3adfcdcca--- /dev/null+++ b/crates/engine/src/tests_slide_template.rs@@ -0,0 +1,360 @@+//! Slideshow templates: built-ins, user template files, validation, apply / previous.++use std::path::PathBuf;++use serde_json::{Value, json};++use super::*;+use crate::Session;++fn temp_dir(tag: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("lc-sstpl-{tag}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++/// A demo session whose user templates live in a fresh folder.+fn session(tag: &str) -> (Session, PathBuf) {+ let dir = temp_dir(tag);+ let mut s = Session::with_demo();+ s.slide_templates_dir = Some(dir.join(DIR_NAME));+ (s, dir)+}++fn run(s: &mut Session, id: &str, p: Value) -> Value {+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))+}++fn err(s: &mut Session, id: &str, p: Value) -> String {+ match s.execute(id, &p) {+ Ok(v) => panic!("{id} {p} should fail, got {v}"),+ Err(e) => e.to_string(),+ }+}++fn ids(s: &mut Session) -> Vec<String> {+ run(s, "slideshow.templates.list", json!({}))["templates"].as_array().unwrap().iter().map(|t| t["id"].as_str().unwrap().to_string()).collect()+}++/// A look different from the defaults in every section.+fn custom(s: &mut Session) {+ run(s, "slideshow.playback", json!({"slideDuration": 7.5, "fadeDuration": 0.5, "fadeColor": "#102030", "randomOrder": true, "repeat": false}));+ run(+ s,+ "slideshow.layout",+ json!({"margins": 0.1, "strokeBorder": true, "strokeColor": "#ff0000", "castShadow": true, "aspect": "4:3", "backdropColor": "#334455"}),+ );+ run(+ s,+ "slideshow.overlays",+ json!({"ratingStars": {"enabled": true}, "addText": {"text": "{caption} — {exposure}", "anchor": "top"}, "showWatermark": true, "watermark": "© me"}),+ );+ run(s, "slideshow.titles", json!({"intro": {"enabled": true, "content": "text", "text": "Hello", "duration": 3}}));+}++#[test]+fn builtins_are_valid_distinct_and_apply_cleanly() {+ let b = builtins();+ assert_eq!(b.len(), BUILTINS.len(), "every built-in parses");+ assert!((4..=6).contains(&b.len()));+ let mut names: Vec<_> = b.iter().map(|t| t.name.to_lowercase()).collect();+ names.dedup();+ assert_eq!(names.len(), b.len(), "unique names");+ // our own names: none of Lightroom Classic's built-in slideshow template names+ for lr in ["default", "simple", "caption and rating", "crop to fill", "exif metadata", "widescreen"] {+ assert!(!names.contains(&lr.to_string()), "{lr}");+ }+ for t in &b {+ assert!(!t.description.is_empty(), "{}", t.id);+ // no image or font files: nothing that needs an attribution or can go missing+ assert!(+ t.look.overlays.identity_plate.image.is_empty() && t.look.overlays.watermark.image.is_empty() && t.look.layout.background_image.is_none()+ );+ // the document form reads back to the same look+ let back = parse(&serde_json::to_vec(&t.to_doc()).unwrap()).unwrap();+ assert_eq!(back.look, t.look, "{}", t.id);+ }+ let looks: Vec<_> = b.iter().map(|t| &t.look).collect();+ for (i, a) in looks.iter().enumerate() {+ assert!(looks.iter().skip(i + 1).all(|o| o != a), "each built-in looks different");+ }+ let (mut s, dir) = session("builtins");+ let active = s.active().unwrap();+ for t in b {+ let r = run(&mut s, "slideshow.templates.apply", json!({"id": t.id}));+ assert_eq!(r["warnings"], json!([]), "{}: {r}", t.id);+ assert_eq!(+ SlideLook { playback: PlaybackSettings { prepare_previews: true, ..t.look.playback.clone() }, ..t.look.clone() },+ SlideLook::of(&s)+ );+ let img = run(&mut s, "slideshow.preview", json!({"id": active.0, "width": 160}));+ assert_eq!(img["width"], 160, "{}", t.id);+ }+ // by name, case-insensitive+ run(&mut s, "slideshow.templates.apply", json!({"name": "edge TO edge"}));+ assert!(s.slide_layout.zoom_to_fill);+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn save_list_apply_restores_exactly_and_previous_goes_back() {+ let (mut s, dir) = session("roundtrip");+ s.slideshow.prepare_previews = false;+ custom(&mut s);+ let saved = SlideLook::of(&s);+ let r = run(&mut s, "slideshow.templates.save", json!({"name": "My Look"}));+ assert_eq!(r["id"], "user:My Look");+ let path = PathBuf::from(r["path"].as_str().unwrap());+ assert_eq!(path, dir.join(DIR_NAME).join("My Look.json"));+ let doc: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ assert_eq!((doc["format"].as_str(), doc["version"].as_u64(), doc["name"].as_str()), (Some(FORMAT), Some(VERSION), Some("My Look")));+ assert!(doc["playback"].get("preparePreviews").is_none(), "a machine preference, not part of the look");+ assert!(ids(&mut s).contains(&"user:My Look".to_string()));++ run(&mut s, "slideshow.templates.apply", json!({"id": "builtin:plain-black"}));+ assert_ne!(SlideLook::of(&s), saved);+ assert!(!s.slideshow.prepare_previews, "prepare previews is kept");+ let r = run(&mut s, "slideshow.templates.apply", json!({"id": "user:My Look"}));+ assert_eq!(r["applied"], "user:My Look");+ assert_eq!(SlideLook::of(&s), saved, "applying restores every setting exactly");++ // previous: back to Plain Black's, then forward again+ let plain = builtins().into_iter().find(|t| t.id == "builtin:plain-black").unwrap();+ run(&mut s, "slideshow.templates.apply", json!({"id": PREVIOUS}));+ assert_eq!(s.slide_layout, plain.look.layout);+ run(&mut s, "slideshow.templates.apply", json!({"id": PREVIOUS}));+ assert_eq!(SlideLook::of(&s), saved);+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn previous_needs_an_apply_first() {+ let (mut s, dir) = session("noprev");+ assert_eq!(run(&mut s, "slideshow.templates.list", json!({}))["previous"], false);+ assert!(err(&mut s, "slideshow.templates.apply", json!({"id": "previous"})).contains("no previous settings"));+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn update_rename_delete_export_import() {+ let (mut s, dir) = session("ops");+ run(&mut s, "slideshow.templates.save", json!({"name": "Mine"}));+ // a taken name, case-insensitively, and a built-in's are refused; replace overwrites+ assert!(err(&mut s, "slideshow.templates.save", json!({"name": "mine"})).contains("already exists"));+ assert!(err(&mut s, "slideshow.templates.save", json!({"name": "Plain Black"})).contains("built-in"));+ run(&mut s, "slideshow.layout", json!({"margins": 0.2}));+ run(&mut s, "slideshow.templates.save", json!({"name": "Mine", "replace": true}));+ assert_eq!(s.slide_template("user:Mine").unwrap().look.layout.margin_top, 0.2);+ // update+ run(&mut s, "slideshow.layout", json!({"margins": 0.05}));+ run(&mut s, "slideshow.templates.update", json!({"id": "user:Mine"}));+ assert_eq!(s.slide_template("user:Mine").unwrap().look.layout.margin_top, 0.05);+ assert!(err(&mut s, "slideshow.templates.update", json!({"id": "builtin:plain-black"})).contains("built-in"));+ // rename (also just the case)+ let r = run(&mut s, "slideshow.templates.rename", json!({"id": "user:Mine", "name": "Ours"}));+ assert_eq!(r["id"], "user:Ours");+ assert!(!dir.join(DIR_NAME).join("Mine.json").exists());+ let r = run(&mut s, "slideshow.templates.rename", json!({"id": "user:Ours", "name": "OURS"}));+ assert_eq!(r["id"], "user:OURS");+ assert_eq!(ids(&mut s).iter().filter(|i| i.starts_with(USER)).count(), 1);+ run(&mut s, "slideshow.templates.save", json!({"name": "Other"}));+ assert!(err(&mut s, "slideshow.templates.rename", json!({"id": "user:Other", "name": "ours"})).contains("already exists"));+ assert!(err(&mut s, "slideshow.templates.rename", json!({"id": "builtin:cinema-wide", "name": "X"})).contains("built-in"));+ // export a user template and a built-in, import them back+ let out = dir.join("out");+ let a = out.join("ours.json").to_string_lossy().to_string();+ run(&mut s, "slideshow.templates.export", json!({"id": "user:OURS", "path": a}));+ let b = out.join("cinema.json").to_string_lossy().to_string();+ run(&mut s, "slideshow.templates.export", json!({"id": "builtin:cinema-wide", "path": b}));+ let r = run(&mut s, "slideshow.templates.import", json!({"path": a}));+ assert_eq!((r["name"].as_str(), r["renamed"].as_bool()), (Some("OURS (2)"), Some(true)), "{r}");+ assert_eq!(s.slide_template("user:OURS (2)").unwrap().look, s.slide_template("user:OURS").unwrap().look);+ let r = run(&mut s, "slideshow.templates.import", json!({"path": b}));+ assert_eq!(r["name"], "Cinema Wide (2)", "a built-in's name is taken too");+ let cinema = s.slide_template("builtin:cinema-wide").unwrap();+ assert_eq!(s.slide_template("user:Cinema Wide (2)").unwrap().look, cinema.look);+ // delete+ run(&mut s, "slideshow.templates.delete", json!({"id": "user:OURS"}));+ assert!(!ids(&mut s).contains(&"user:OURS".to_string()));+ assert!(err(&mut s, "slideshow.templates.delete", json!({"id": "user:OURS"})).contains("no slideshow template"));+ assert!(err(&mut s, "slideshow.templates.delete", json!({"id": "builtin:plain-black"})).contains("built-in"));+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn file_names_are_sanitised_and_ids_never_leave_the_folder() {+ assert_eq!(file_stem("../../etc/passwd").as_deref(), Some("______etc_passwd"));+ assert_eq!(file_stem(r"C:\x\y").as_deref(), Some("C__x_y"));+ assert_eq!(file_stem("a:b*c?d\"e<f>g|h").as_deref(), Some("a_b_c_d_e_f_g_h"));+ assert_eq!(file_stem(" Holiday (2024) ").as_deref(), Some("Holiday (2024)"));+ assert_eq!(file_stem("Été à Kyōto 京都").as_deref(), Some("Été à Kyōto 京都"));+ assert_eq!(file_stem("con").as_deref(), Some("con_"));+ assert_eq!(file_stem("LPT1").as_deref(), Some("LPT1_"));+ assert_eq!(file_stem("..."), None);+ assert_eq!(file_stem("///"), None);+ assert_eq!(file_stem(&"x".repeat(500)).map(|s| s.chars().count()), Some(64));+ let (mut s, dir) = session("escape");+ let folder = dir.join(DIR_NAME);+ let r = run(&mut s, "slideshow.templates.save", json!({"name": "../../escape"}));+ assert_eq!(r["id"], "user:______escape");+ assert!(folder.join("______escape.json").exists());+ assert!(!dir.join("escape.json").exists());+ for name in ["", " ", "...", "/", "a\nb", &"y".repeat(81)] {+ err(&mut s, "slideshow.templates.save", json!({"name": name}));+ }+ // an id can't point outside the folder (or at a file LightCraft wouldn't name)+ std::fs::write(dir.join("victim.json"), b"{}").unwrap();+ for id in ["user:../victim", "user:..", "user:/etc/passwd", "user:a/b", "user:", "user:x.json"] {+ let e = err(&mut s, "slideshow.templates.delete", json!({"id": id}));+ assert!(e.contains("isn't a template id"), "{id}: {e}");+ }+ assert!(dir.join("victim.json").exists());+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn bad_files_are_reported_and_skipped() {+ let (mut s, dir) = session("bad");+ let folder = dir.join(DIR_NAME);+ std::fs::create_dir_all(&folder).unwrap();+ run(&mut s, "slideshow.templates.save", json!({"name": "Good"}));+ let doc = |extra: Value| {+ let mut d = json!({"format": FORMAT, "version": 1, "name": "X"});+ for (k, v) in extra.as_object().unwrap() {+ d[k] = v.clone();+ }+ serde_json::to_vec(&d).unwrap()+ };+ let files: Vec<(&str, Vec<u8>, &str)> = vec![+ ("truncated.json", br#"{"format": "lightcraft.slideshowTemplate", "vers"#.to_vec(), "not a slideshow template"),+ ("binary.json", vec![0xff, 0xfe, 0x00, 0x01], "not UTF-8"),+ ("array.json", b"[1, 2]".to_vec(), "not a JSON object"),+ ("preset.json", br#"{"format": "lightcraft.preset", "version": 1}"#.to_vec(), "format `lightcraft.preset`"),+ ("newer.json", doc(json!({"version": 2})), "newer LightCraft"),+ ("noversion.json", br#"{"format": "lightcraft.slideshowTemplate"}"#.to_vec(), "no `version`"),+ ("badversion.json", doc(json!({"version": -1})), "`version`"),+ ("unknown.json", doc(json!({"music": {}})), "unknown key `music`"),+ ("nan.json", doc(json!({"layout": {"margins": "wide"}})), "layout"),+ ("badkey.json", doc(json!({"overlays": {"fireworks": true}})), "overlays"),+ ("badtype.json", doc(json!({"titles": [1]})), "`titles` must be an object"),+ ("toomanytexts.json", doc(json!({"overlays": {"texts": vec![json!({}); 40]}})), "at most"),+ ("badname.json", doc(json!({"name": 5})), "`name`"),+ ("huge.json", vec![b' '; MAX_FILE as usize + 1], "too large"),+ ("bad name!.json", doc(json!({})), "file name"),+ ];+ for (f, bytes, _) in &files {+ std::fs::write(folder.join(f), bytes).unwrap();+ }+ std::fs::create_dir_all(folder.join("folder.json")).unwrap();+ std::fs::write(folder.join("notes.txt"), b"ignored").unwrap();+ let r = run(&mut s, "slideshow.templates.list", json!({}));+ let user: Vec<_> = r["templates"].as_array().unwrap().iter().filter(|t| t["builtin"] == false).collect();+ assert_eq!(user.len(), 1, "only the good one: {r}");+ let problems: Vec<String> = r["problems"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_string()).collect();+ for (f, _, why) in &files {+ assert!(problems.iter().any(|p| p.starts_with(f) && p.contains(why)), "{f}: {why} in {problems:?}");+ }+ assert!(problems.iter().any(|p| p.starts_with("folder.json") && p.contains("not a regular file")), "{problems:?}");+ assert_eq!(problems.len(), files.len() + 1, "{problems:?}");+ // the same refusals on import+ for (f, _, why) in files.iter().filter(|(f, _, _)| *f != "bad name!.json") {+ let e = err(&mut s, "slideshow.templates.import", json!({"path": folder.join(f)}));+ assert!(e.contains(why), "{f}: {e}");+ }+ // out-of-range numbers in a hand-edited file are clamped, never applied as they are+ std::fs::write(folder.join("wild.json"), doc(json!({"layout": {"margins": 9, "shadowAngle": 1e300}, "playback": {"slideDuration": 1e9}})))+ .unwrap();+ let t = s.slide_template("user:wild").unwrap();+ assert_eq!(t.look.layout.margin_left, lightcraft_slideshow::MARGIN_MAX);+ assert_eq!(t.look.playback.slide_duration, crate::slideshow::SLIDE_MAX);+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn thousands_of_templates_are_capped_not_fatal() {+ let (mut s, dir) = session("many");+ let folder = dir.join(DIR_NAME);+ std::fs::create_dir_all(&folder).unwrap();+ let body = |i: usize| format!(r#"{{"format": "{FORMAT}", "version": 1, "name": "T{i}"}}"#);+ for i in 0..MAX_TEMPLATES + 50 {+ std::fs::write(folder.join(format!("T{i:05}.json")), body(i)).unwrap();+ }+ let r = run(&mut s, "slideshow.templates.list", json!({}));+ let user = r["templates"].as_array().unwrap().iter().filter(|t| t["builtin"] == false).count();+ assert_eq!(user, MAX_TEMPLATES);+ assert!(r["problems"][0].as_str().unwrap().contains("only the first"), "{r}");+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn missing_files_apply_with_a_warning() {+ let (mut s, dir) = session("missing");+ let folder = dir.join(DIR_NAME);+ std::fs::create_dir_all(&folder).unwrap();+ let d = json!({+ "format": FORMAT, "version": 1, "name": "Logo",+ "layout": {"backgroundImage": 987654},+ "overlays": {"identityPlate": {"enabled": true, "image": "/no/such/logo.png"}, "showWatermark": true, "watermark": {"text": "", "image": "/no/such/mark.png"}}+ });+ std::fs::write(folder.join("Logo.json"), serde_json::to_vec(&d).unwrap()).unwrap();+ let r = run(&mut s, "slideshow.templates.apply", json!({"id": "user:Logo"}));+ let w = r["warnings"].to_string();+ assert!(w.contains("background image") && w.contains("logo.png") && w.contains("mark.png"), "{w}");+ assert_eq!(s.slide_overlays.identity_plate.image, "/no/such/logo.png", "applied anyway");+ // the slide still renders (the backdrop colour, no plate)+ let id = s.active().unwrap();+ run(&mut s, "slideshow.preview", json!({"id": id.0, "width": 64}));+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn preview_of_a_template_leaves_the_settings_alone() {+ let (mut s, dir) = session("preview");+ custom(&mut s);+ let before = SlideLook::of(&s);+ let id = s.active().unwrap();+ let mine = run(&mut s, "slideshow.preview", json!({"id": id.0, "width": 200, "height": 120}));+ let r = run(&mut s, "slideshow.preview", json!({"id": id.0, "width": 200, "height": 120, "template": "builtin:edge-to-edge"}));+ assert_eq!(r["template"], "builtin:edge-to-edge");+ assert_eq!(r["photo"], json!([0.0, 0.0, 200.0, 120.0]), "zoom to fill, no margins: {r}");+ assert_ne!(r["photo"], mine["photo"]);+ assert_eq!(r["overlays"], json!([]), "the template's overlays (none), not the library's");+ let t = run(&mut s, "slideshow.preview", json!({"title": "ending", "template": "builtin:cinema-wide", "width": 160}));+ assert_eq!((t["enabled"].as_bool(), t["height"].as_u64()), (Some(true), Some(90)), "the template's ending, at its 16:9 aspect: {t}");+ assert_eq!(SlideLook::of(&s), before, "nothing changed");+ assert!(s.slide_templates_previous.is_none());+ assert!(err(&mut s, "slideshow.preview", json!({"template": "builtin:nope"})).contains("no slideshow template"));+ assert!(err(&mut s, "slideshow.preview", json!({"template": 3})).contains("template id"));+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn without_a_settings_folder_only_builtins() {+ let mut s = Session::with_demo();+ assert!(s.slide_templates_dir.is_none());+ let r = run(&mut s, "slideshow.templates.list", json!({}));+ assert_eq!(r["templates"].as_array().unwrap().len(), BUILTINS.len());+ assert!(err(&mut s, "slideshow.templates.save", json!({"name": "X"})).contains("settings folder"));+ run(&mut s, "slideshow.templates.apply", json!({"id": "builtin:gallery-wall"}));+ assert!(s.slide_overlays.rating_stars.enabled);+}++#[test]+fn a_saved_template_reads_back_through_its_section_validation() {+ let (mut s, dir) = session("sections");+ custom(&mut s);+ let look = SlideLook::of(&s);+ let parsed = parse(&serde_json::to_vec(&doc("N", "d", &look)).unwrap()).unwrap();+ assert_eq!(parsed.name.as_deref(), Some("N"));+ assert_eq!(parsed.description, "d");+ assert_eq!(parsed.look.layout, look.layout);+ assert_eq!(parsed.look.overlays, look.overlays);+ assert_eq!(parsed.look.titles, look.titles);+ assert_eq!(PlaybackSettings { prepare_previews: look.playback.prepare_previews, ..parsed.look.playback }, look.playback);+ // a BOM and a missing name are fine+ let mut bytes = "\u{feff}".as_bytes().to_vec();+ bytes.extend(br#"{"format": "lightcraft.slideshowTemplate", "version": 1}"#);+ assert_eq!(parse(&bytes).unwrap().name, None);+ let _ = std::fs::remove_dir_all(dir);+}diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rsindex acbecb60b..d939002b9 100644--- a/crates/mcp/src/headless.rs+++ b/crates/mcp/src/headless.rs@@ -32,7 +32,9 @@ impl Drop for Headless {impl Default for Headless {fn default() -> Self {- Self::new(Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models())+ Self::new(+ Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates(),+ )}}@@ -43,7 +45,14 @@ impl Headless {/// A headless session with the procedurally generated demo library.pub fn demo() -> Self {- Self::new(Session::with_demo().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models())+ Self::new(+ Session::with_demo()+ .with_fs()+ .with_default_denoise_models()+ .with_system_clock()+ .with_default_face_models()+ .with_default_slide_templates(),+ )}fn photo_or_active(&self, p: &Value) -> Result<PhotoId, String> {diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.jsonindex 671da17d4..ed7549c32 100644--- a/crates/ui-egui/locales/de-formats.json+++ b/crates/ui-egui/locales/de-formats.json@@ -228,5 +228,14 @@"+{n} more": "+{n} weitere","1 task is still running: {names}. Quitting stops it.": "1 Aufgabe läuft noch: {names}. Beenden bricht sie ab.","{n} tasks are still running: {names}. Quitting stops them.": "{n} Aufgaben laufen noch: {names}. Beenden bricht sie ab.",- "{what} merge cancelled": "{what}-Zusammenfügung abgebrochen"+ "{what} merge cancelled": "{what}-Zusammenfügung abgebrochen",+ "Applied {name}": "{name} angewendet",+ "Delete “{name}”?": "„{name}“ löschen?",+ "Updated {name}": "{name} aktualisiert",+ "Exported to {path}": "Exportiert nach {path}",+ "Saved template {name}": "Vorlage {name} gespeichert",+ "Imported {name}": "{name} importiert",+ "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.jsonindex c98bd2f41..78b215d7e 100644--- a/crates/ui-egui/locales/de.json+++ b/crates/ui-egui/locales/de.json@@ -2093,5 +2093,29 @@"The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "Das Intro läuft einmal vor dem ersten Foto, der Abschluss nach dem letzten Foto, wenn Wiederholen aus ist. Die Erkennungstafel ist die unter Überlagerungen eingestellte. Titel werden wie Dias überblendet, und die zufällige Reihenfolge verschiebt sie nie.","This screen is off: turn it on under Titles to play it.": "Dieser Bildschirm ist aus: Schalten Sie ihn unter Titel ein, um ihn abzuspielen.","The intro screen, before the first photo.": "Der Intro-Bildschirm, vor dem ersten Foto.",- "The ending screen, after the last photo.": "Der Abschlussbildschirm, nach dem letzten Foto."+ "The ending screen, after the last photo.": "Der Abschlussbildschirm, nach dem letzten Foto.",+ "Templates": "Vorlagen",+ "Built-in": "Integriert",+ "Your templates": "Eigene Vorlagen",+ "None yet: save the current settings as a template below.": "Noch keine: Speichern Sie die aktuellen Einstellungen unten als Vorlage.",+ "Before the last template": "Vor der letzten Vorlage",+ "Previous settings": "Vorherige Einstellungen",+ "New template name": "Name der neuen Vorlage",+ "Save as Template": "Als Vorlage speichern",+ "Import…": "Importieren…",+ "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "Eigene Vorlagen brauchen einen Einstellungsordner, den diese Version nicht hat; die integrierten funktionieren.",+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "Klicken Sie auf eine Vorlage, um sie anzuwenden; zeigen Sie auf eine, um sie am ausgewählten Foto in der Vorschau zu sehen. Rechtsklicken Sie auf eigene, um sie zu aktualisieren, umzubenennen, zu exportieren oder zu löschen.",+ "Import Slideshow Templates": "Diashow-Vorlagen importieren",+ "Export Slideshow Template": "Diashow-Vorlage exportieren",+ "Slideshow Templates": "Diashow-Vorlagen",+ "Plain Black": "Schlicht schwarz",+ "Gallery Wall": "Galeriewand",+ "Edge to Edge": "Randlos",+ "Cinema Wide": "Kino-Breitbild",+ "Shooting Data": "Aufnahmedaten",+ "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "Jedes Foto so groß wie möglich auf Schwarz, mit kurzer Überblendung. Nichts darüber gezeichnet.",+ "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Eine hellgraue Wand mit weißem Passepartout und weichem Schatten; Bildunterschrift und Bewertung unter dem Foto.",+ "Every photo cropped to fill the whole screen, with slow crossfades.": "Jedes Foto auf den ganzen Bildschirm beschnitten, mit langsamen Überblendungen.",+ "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Ein 16:9-Bild mit schwarzen Balken oben und unten, dem Titel in der Ecke, Blenden über Schwarz und einer Abschlusstafel.",+ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Ein dunkler Schieferhintergrund mit Belichtung, ISO und Brennweite, darunter Kamera und Objektiv, unter jedem Foto."}diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.jsonindex 9ba1c8f10..167288981 100644--- a/crates/ui-egui/locales/es-formats.json+++ b/crates/ui-egui/locales/es-formats.json@@ -228,5 +228,14 @@"+{n} more": "+{n} más","1 task is still running: {names}. Quitting stops it.": "1 tarea sigue en curso: {names}. Salir la detiene.","{n} tasks are still running: {names}. Quitting stops them.": "{n} tareas siguen en curso: {names}. Salir las detiene.",- "{what} merge cancelled": "Combinación {what} cancelada"+ "{what} merge cancelled": "Combinación {what} cancelada",+ "Applied {name}": "Se aplicó {name}",+ "Delete “{name}”?": "¿Eliminar «{name}»?",+ "Updated {name}": "Se actualizó {name}",+ "Exported to {path}": "Exportado a {path}",+ "Saved template {name}": "Plantilla {name} guardada",+ "Imported {name}": "Se importó {name}",+ "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.jsonindex e18046491..e826a8393 100644--- a/crates/ui-egui/locales/es.json+++ b/crates/ui-egui/locales/es.json@@ -1938,5 +1938,29 @@"The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "La introducción se reproduce una vez antes de la primera foto; el final, después de la última foto cuando Repetir está desactivado. La placa de identidad es la definida en Superposiciones. Los títulos se funden como las diapositivas y el orden aleatorio nunca los mueve.","This screen is off: turn it on under Titles to play it.": "Esta pantalla está desactivada: actívela en Títulos para reproducirla.","The intro screen, before the first photo.": "La pantalla de introducción, antes de la primera foto.",- "The ending screen, after the last photo.": "La pantalla final, después de la última foto."+ "The ending screen, after the last photo.": "La pantalla final, después de la última foto.",+ "Templates": "Plantillas",+ "Built-in": "Integradas",+ "Your templates": "Tus plantillas",+ "None yet: save the current settings as a template below.": "Aún no hay ninguna: guarda los ajustes actuales como plantilla abajo.",+ "Before the last template": "Antes de la última plantilla",+ "Previous settings": "Ajustes anteriores",+ "New template name": "Nombre de la nueva plantilla",+ "Save as Template": "Guardar como plantilla",+ "Import…": "Importar…",+ "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "Tus propias plantillas necesitan una carpeta de ajustes, que esta versión no tiene; las integradas funcionan.",+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "Haz clic en una plantilla para aplicarla; señala una para previsualizarla en la foto seleccionada. Haz clic derecho en las tuyas para actualizarlas, cambiarles el nombre, exportarlas o eliminarlas.",+ "Import Slideshow Templates": "Importar plantillas de presentación",+ "Export Slideshow Template": "Exportar plantilla de presentación",+ "Slideshow Templates": "Plantillas de presentación",+ "Plain Black": "Negro liso",+ "Gallery Wall": "Pared de galería",+ "Edge to Edge": "De borde a borde",+ "Cinema Wide": "Cine panorámico",+ "Shooting Data": "Datos de toma",+ "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "Cada foto lo más grande posible, sobre negro, con un fundido cruzado breve. Nada encima.",+ "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Una pared gris claro con paspartú blanco y sombra suave; el pie de foto y la valoración debajo de la foto.",+ "Every photo cropped to fill the whole screen, with slow crossfades.": "Cada foto recortada para llenar toda la pantalla, con fundidos cruzados lentos.",+ "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Un encuadre 16:9 con franjas negras arriba y abajo, el título en la esquina, fundidos a negro y un cartel final.",+ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Un fondo pizarra oscuro con la exposición, el ISO y la distancia focal, y luego la cámara y el objetivo, bajo cada foto."}diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.jsonindex 7ccaf5a38..f5c7823fa 100644--- a/crates/ui-egui/locales/fr-formats.json+++ b/crates/ui-egui/locales/fr-formats.json@@ -228,5 +228,14 @@"+{n} more": "+{n} autres","1 task is still running: {names}. Quitting stops it.": "1 tâche est encore en cours : {names}. Quitter l'arrête.","{n} tasks are still running: {names}. Quitting stops them.": "{n} tâches sont encore en cours : {names}. Quitter les arrête.",- "{what} merge cancelled": "Fusion {what} annulée"+ "{what} merge cancelled": "Fusion {what} annulée",+ "Applied {name}": "{name} appliqué",+ "Delete “{name}”?": "Supprimer « {name} » ?",+ "Updated {name}": "{name} mis à jour",+ "Exported to {path}": "Exporté vers {path}",+ "Saved template {name}": "Modèle {name} enregistré",+ "Imported {name}": "{name} importé",+ "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.jsonindex 5eab00c00..dece0397c 100644--- a/crates/ui-egui/locales/fr.json+++ b/crates/ui-egui/locales/fr.json@@ -1938,5 +1938,29 @@"The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "L'introduction est lue une fois avant la première photo ; l'écran de fin après la dernière photo lorsque Répéter est désactivé. La plaque d'identification est celle définie sous Incrustations. Les titres apparaissent en fondu comme les diapositives et l'ordre aléatoire ne les déplace jamais.","This screen is off: turn it on under Titles to play it.": "Cet écran est désactivé : activez-le sous Titres pour le lire.","The intro screen, before the first photo.": "L'écran d'introduction, avant la première photo.",- "The ending screen, after the last photo.": "L'écran de fin, après la dernière photo."+ "The ending screen, after the last photo.": "L'écran de fin, après la dernière photo.",+ "Templates": "Modèles",+ "Built-in": "Intégrés",+ "Your templates": "Vos modèles",+ "None yet: save the current settings as a template below.": "Aucun pour l'instant : enregistrez les réglages actuels comme modèle ci-dessous.",+ "Before the last template": "Avant le dernier modèle",+ "Previous settings": "Réglages précédents",+ "New template name": "Nom du nouveau modèle",+ "Save as Template": "Enregistrer comme modèle",+ "Import…": "Importer…",+ "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "Vos propres modèles nécessitent un dossier de réglages, absent de cette version ; les modèles intégrés fonctionnent.",+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "Cliquez sur un modèle pour l'appliquer ; survolez-en un pour l'afficher sur la photo sélectionnée. Clic droit sur les vôtres pour les mettre à jour, les renommer, les exporter ou les supprimer.",+ "Import Slideshow Templates": "Importer des modèles de diaporama",+ "Export Slideshow Template": "Exporter le modèle de diaporama",+ "Slideshow Templates": "Modèles de diaporama",+ "Plain Black": "Noir uni",+ "Gallery Wall": "Mur de galerie",+ "Edge to Edge": "Bord à bord",+ "Cinema Wide": "Cinéma large",+ "Shooting Data": "Données de prise de vue",+ "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "Chaque photo aussi grande que possible, sur noir, avec un court fondu enchaîné. Rien par-dessus.",+ "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Un mur gris clair avec un passe-partout blanc et une ombre douce ; la légende et la note sous la photo.",+ "Every photo cropped to fill the whole screen, with slow crossfades.": "Chaque photo recadrée pour remplir tout l'écran, avec des fondus enchaînés lents.",+ "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Un cadre 16:9 avec des bandes noires en haut et en bas, le titre dans le coin, des fondus au noir et un carton de fin.",+ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Un fond ardoise sombre avec l'exposition, l'ISO et la focale, puis le boîtier et l'objectif, sous chaque photo."}diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.jsonindex f1c06351c..e40560762 100644--- a/crates/ui-egui/locales/ja-formats.json+++ b/crates/ui-egui/locales/ja-formats.json@@ -228,5 +228,14 @@"+{n} more": "ほか{n}件","1 task is still running: {names}. Quitting stops it.": "1件のタスクが実行中です:{names}。終了すると停止します。","{n} tasks are still running: {names}. Quitting stops them.": "{n}件のタスクが実行中です:{names}。終了すると停止します。",- "{what} merge cancelled": "{what}合成をキャンセルしました"+ "{what} merge cancelled": "{what}合成をキャンセルしました",+ "Applied {name}": "{name} を適用しました",+ "Delete “{name}”?": "「{name}」を削除しますか?",+ "Updated {name}": "{name} を更新しました",+ "Exported to {path}": "{path} に書き出しました",+ "Saved template {name}": "テンプレート {name} を保存しました",+ "Imported {name}": "{name} を読み込みました",+ "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.jsonindex 81c57d3e1..62ce87d27 100644--- a/crates/ui-egui/locales/ja.json+++ b/crates/ui-egui/locales/ja.json@@ -1940,5 +1940,29 @@"The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "イントロは最初の写真の前に 1 回再生され、エンディングは繰り返しがオフのとき最後の写真の後に再生されます。ID プレートはオーバーレイで設定したものです。タイトルはスライドと同様にフェードし、ランダム順でも位置は変わりません。","This screen is off: turn it on under Titles to play it.": "この画面はオフです。再生するにはタイトルでオンにしてください。","The intro screen, before the first photo.": "イントロ画面(最初の写真の前)。",- "The ending screen, after the last photo.": "エンディング画面(最後の写真の後)。"+ "The ending screen, after the last photo.": "エンディング画面(最後の写真の後)。",+ "Templates": "テンプレート",+ "Built-in": "組み込み",+ "Your templates": "自分のテンプレート",+ "None yet: save the current settings as a template below.": "まだありません。下で現在の設定をテンプレートとして保存できます。",+ "Before the last template": "最後のテンプレートの前",+ "Previous settings": "以前の設定",+ "New template name": "新しいテンプレート名",+ "Save as Template": "テンプレートとして保存",+ "Import…": "読み込み…",+ "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "自分のテンプレートには設定フォルダーが必要ですが、このビルドにはありません。組み込みテンプレートは使えます。",+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "テンプレートをクリックすると適用、ポインターを合わせると選択中の写真でプレビューします。自分のテンプレートは右クリックで更新・名前変更・書き出し・削除できます。",+ "Import Slideshow Templates": "スライドショーテンプレートを読み込み",+ "Export Slideshow Template": "スライドショーテンプレートを書き出し",+ "Slideshow Templates": "スライドショーテンプレート",+ "Plain Black": "シンプルブラック",+ "Gallery Wall": "ギャラリーの壁",+ "Edge to Edge": "全面表示",+ "Cinema Wide": "シネマワイド",+ "Shooting Data": "撮影データ",+ "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "各写真を黒地にできるだけ大きく表示し、短いクロスフェードでつなぎます。上には何も描きません。",+ "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "明るいグレーの壁に白いマットと柔らかな影。写真の下にキャプションとレーティング。",+ "Every photo cropped to fill the whole screen, with slow crossfades.": "各写真を画面全体に合わせて切り抜き、ゆっくりクロスフェードします。",+ "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "上下に黒帯のある16:9の画面、隅にタイトル、黒を経由するフェード、エンディングカード。",+ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "暗いスレート色の背景。各写真の下に露出・ISO・焦点距離、その下にカメラとレンズ。"}diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.jsonindex 4a9d1168a..6b5b32988 100644--- a/crates/ui-egui/locales/pt-br-formats.json+++ b/crates/ui-egui/locales/pt-br-formats.json@@ -228,5 +228,14 @@"+{n} more": "+{n} mais","1 task is still running: {names}. Quitting stops it.": "1 tarefa ainda está em andamento: {names}. Sair a interrompe.","{n} tasks are still running: {names}. Quitting stops them.": "{n} tarefas ainda estão em andamento: {names}. Sair as interrompe.",- "{what} merge cancelled": "{what} mesclagem cancelada"+ "{what} merge cancelled": "{what} mesclagem cancelada",+ "Applied {name}": "{name} aplicado",+ "Delete “{name}”?": "Excluir “{name}”?",+ "Updated {name}": "{name} atualizado",+ "Exported to {path}": "Exportado para {path}",+ "Saved template {name}": "Modelo {name} salvo",+ "Imported {name}": "{name} importado",+ "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.jsonindex 9be14b0d2..9329b2d23 100644--- a/crates/ui-egui/locales/pt-br.json+++ b/crates/ui-egui/locales/pt-br.json@@ -1938,5 +1938,29 @@"The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "A abertura é exibida uma vez antes da primeira foto; o encerramento, após a última foto quando Repetir está desativado. A placa de identidade é a definida em Sobreposições. Os títulos fazem transição como os slides e a ordem aleatória nunca os move.","This screen is off: turn it on under Titles to play it.": "Esta tela está desativada: ative-a em Títulos para exibi-la.","The intro screen, before the first photo.": "A tela de abertura, antes da primeira foto.",- "The ending screen, after the last photo.": "A tela de encerramento, após a última foto."+ "The ending screen, after the last photo.": "A tela de encerramento, após a última foto.",+ "Templates": "Modelos",+ "Built-in": "Integrados",+ "Your templates": "Seus modelos",+ "None yet: save the current settings as a template below.": "Nenhum ainda: salve as configurações atuais como modelo abaixo.",+ "Before the last template": "Antes do último modelo",+ "Previous settings": "Configurações anteriores",+ "New template name": "Nome do novo modelo",+ "Save as Template": "Salvar como modelo",+ "Import…": "Importar…",+ "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "Seus próprios modelos precisam de uma pasta de configurações, que esta versão não tem; os integrados funcionam.",+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "Clique em um modelo para aplicá-lo; aponte para um para prévia na foto selecionada. Clique com o botão direito nos seus para atualizar, renomear, exportar ou excluir.",+ "Import Slideshow Templates": "Importar modelos de apresentação",+ "Export Slideshow Template": "Exportar modelo de apresentação",+ "Slideshow Templates": "Modelos de apresentação",+ "Plain Black": "Preto simples",+ "Gallery Wall": "Parede de galeria",+ "Edge to Edge": "De ponta a ponta",+ "Cinema Wide": "Cinema widescreen",+ "Shooting Data": "Dados da captura",+ "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "Cada foto o maior possível, sobre preto, com uma transição curta. Nada desenhado por cima.",+ "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Uma parede cinza-clara com passe-partout branco e sombra suave; a legenda e a classificação abaixo da foto.",+ "Every photo cropped to fill the whole screen, with slow crossfades.": "Cada foto recortada para preencher a tela inteira, com transições lentas.",+ "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Um quadro 16:9 com faixas pretas acima e abaixo, o título no canto, transições pelo preto e uma cartela final.",+ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Um fundo ardósia escuro com a exposição, ISO e distância focal, e depois a câmera e a lente, abaixo de cada foto."}diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.jsonindex ba3560ad0..177857dc4 100644--- a/crates/ui-egui/locales/ru-formats.json+++ b/crates/ui-egui/locales/ru-formats.json@@ -228,5 +228,14 @@"+{n} more": "ещё {n}","1 task is still running: {names}. Quitting stops it.": "Ещё выполняется задача: {names}. Выход прервёт её.","{n} tasks are still running: {names}. Quitting stops them.": "Ещё выполняется задач: {n} — {names}. Выход прервёт их.",- "{what} merge cancelled": "{what}: слияние отменено"+ "{what} merge cancelled": "{what}: слияние отменено",+ "Applied {name}": "Применено: {name}",+ "Delete “{name}”?": "Удалить «{name}»?",+ "Updated {name}": "Обновлено: {name}",+ "Exported to {path}": "Экспортировано в {path}",+ "Saved template {name}": "Шаблон {name} сохранён",+ "Imported {name}": "Импортировано: {name}",+ "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.jsonindex 34cb5f33c..2a0b609eb 100644--- a/crates/ui-egui/locales/ru.json+++ b/crates/ui-egui/locales/ru.json@@ -1653,5 +1653,30 @@"The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "Вступление показывается один раз перед первым фото, финал — после последнего фото, если повтор выключен. Фирменная табличка — та, что задана в разделе «Наложения». Титры появляются и исчезают как слайды, а случайный порядок их не перемещает.","This screen is off: turn it on under Titles to play it.": "Этот экран выключен: включите его в разделе «Титры», чтобы показывать.","The intro screen, before the first photo.": "Вступительный экран, перед первым фото.",- "The ending screen, after the last photo.": "Заключительный экран, после последнего фото."+ "The ending screen, after the last photo.": "Заключительный экран, после последнего фото.",+ "Templates": "Шаблоны",+ "Built-in": "Встроенные",+ "Your templates": "Ваши шаблоны",+ "None yet: save the current settings as a template below.": "Пока нет: сохраните текущие настройки как шаблон ниже.",+ "Before the last template": "До последнего шаблона",+ "Previous settings": "Предыдущие настройки",+ "New template name": "Имя нового шаблона",+ "Save as Template": "Сохранить как шаблон",+ "Import…": "Импорт…",+ "Apply": "Применить",+ "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "Для своих шаблонов нужна папка настроек, которой в этой сборке нет; встроенные работают.",+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "Щёлкните шаблон, чтобы применить его; наведите указатель, чтобы увидеть его на выбранном фото. Щёлкните свой шаблон правой кнопкой, чтобы обновить, переименовать, экспортировать или удалить его.",+ "Import Slideshow Templates": "Импорт шаблонов слайд-шоу",+ "Export Slideshow Template": "Экспорт шаблона слайд-шоу",+ "Slideshow Templates": "Шаблоны слайд-шоу",+ "Plain Black": "Просто чёрный",+ "Gallery Wall": "Стена галереи",+ "Edge to Edge": "От края до края",+ "Cinema Wide": "Широкий экран",+ "Shooting Data": "Данные съёмки",+ "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "Каждое фото как можно крупнее на чёрном, с короткой сменой наплывом. Поверх ничего.",+ "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Светло-серая стена с белым паспарту и мягкой тенью; подпись и рейтинг под фото.",+ "Every photo cropped to fill the whole screen, with slow crossfades.": "Каждое фото обрезано на весь экран, с медленной сменой наплывом.",+ "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Кадр 16:9 с чёрными полосами сверху и снизу, название в углу, затемнения через чёрный и финальная карточка.",+ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Тёмный грифельный фон с экспозицией, ISO и фокусным расстоянием, а ниже камерой и объективом под каждым фото."}diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.jsonindex c33dd0cb0..d334f2649 100644--- a/crates/ui-egui/locales/uk-formats.json+++ b/crates/ui-egui/locales/uk-formats.json@@ -228,5 +228,14 @@"+{n} more": "+{n} ще","1 task is still running: {names}. Quitting stops it.": "1 завдання ще виконується: {names}. Вихід зупинить його.","{n} tasks are still running: {names}. Quitting stops them.": "Ще виконуються завдання ({n}): {names}. Вихід зупинить їх.",- "{what} merge cancelled": "Об’єднання {what} скасовано"+ "{what} merge cancelled": "Об’єднання {what} скасовано",+ "Applied {name}": "Застосовано: {name}",+ "Delete “{name}”?": "Видалити «{name}»?",+ "Updated {name}": "Оновлено: {name}",+ "Exported to {path}": "Експортовано до {path}",+ "Saved template {name}": "Шаблон {name} збережено",+ "Imported {name}": "Імпортовано: {name}",+ "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.jsonindex 2b41d5769..e7b3687bf 100644--- a/crates/ui-egui/locales/uk.json+++ b/crates/ui-egui/locales/uk.json@@ -2132,5 +2132,29 @@"The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "Вступ показується один раз перед першим фото, фінал — після останнього фото, якщо повтор вимкнено. Фірмова табличка — та, що задана в розділі «Накладання». Титри з'являються й зникають як слайди, а випадковий порядок їх не переміщує.","This screen is off: turn it on under Titles to play it.": "Цей екран вимкнено: увімкніть його в розділі «Титри», щоб показувати.","The intro screen, before the first photo.": "Вступний екран, перед першим фото.",- "The ending screen, after the last photo.": "Завершальний екран, після останнього фото."+ "The ending screen, after the last photo.": "Завершальний екран, після останнього фото.",+ "Templates": "Шаблони",+ "Built-in": "Вбудовані",+ "Your templates": "Ваші шаблони",+ "None yet: save the current settings as a template below.": "Поки немає: збережіть поточні налаштування як шаблон нижче.",+ "Before the last template": "До останнього шаблону",+ "Previous settings": "Попередні налаштування",+ "New template name": "Назва нового шаблону",+ "Save as Template": "Зберегти як шаблон",+ "Import…": "Імпорт…",+ "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "Для власних шаблонів потрібна тека налаштувань, якої в цій збірці немає; вбудовані працюють.",+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "Клацніть шаблон, щоб застосувати його; наведіть вказівник, щоб побачити його на вибраному фото. Клацніть власний шаблон правою кнопкою, щоб оновити, перейменувати, експортувати чи видалити його.",+ "Import Slideshow Templates": "Імпорт шаблонів слайд-шоу",+ "Export Slideshow Template": "Експорт шаблону слайд-шоу",+ "Slideshow Templates": "Шаблони слайд-шоу",+ "Plain Black": "Просто чорний",+ "Gallery Wall": "Стіна галереї",+ "Edge to Edge": "Від краю до краю",+ "Cinema Wide": "Широкий екран",+ "Shooting Data": "Дані зйомки",+ "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "Кожне фото якомога більше на чорному, з короткою зміною накладанням. Поверх нічого.",+ "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Світло-сіра стіна з білим паспарту та м'якою тінню; підпис і рейтинг під фото.",+ "Every photo cropped to fill the whole screen, with slow crossfades.": "Кожне фото обрізане на весь екран, з повільною зміною накладанням.",+ "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Кадр 16:9 з чорними смугами згори й знизу, назва в куті, затемнення через чорний і фінальна картка.",+ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Темне грифельне тло з експозицією, ISO та фокусною відстанню, а нижче камерою й об'єктивом під кожним фото."}diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.jsonindex eb429af42..0d6aa11ef 100644--- a/crates/ui-egui/locales/zh-hans-formats.json+++ b/crates/ui-egui/locales/zh-hans-formats.json@@ -228,5 +228,14 @@"+{n} more": "还有 {n} 项","1 task is still running: {names}. Quitting stops it.": "仍有 1 个任务在运行:{names}。退出将停止它。","{n} tasks are still running: {names}. Quitting stops them.": "仍有 {n} 个任务在运行:{names}。退出将停止它们。",- "{what} merge cancelled": "已取消 {what} 合并"+ "{what} merge cancelled": "已取消 {what} 合并",+ "Applied {name}": "已应用 {name}",+ "Delete “{name}”?": "删除“{name}”?",+ "Updated {name}": "已更新 {name}",+ "Exported to {path}": "已导出到 {path}",+ "Saved template {name}": "已保存模板 {name}",+ "Imported {name}": "已导入 {name}",+ "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.jsonindex 9dfa236e0..0780ecb42 100644--- a/crates/ui-egui/locales/zh-hans.json+++ b/crates/ui-egui/locales/zh-hans.json@@ -1938,5 +1938,29 @@"The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "片头在第一张照片之前播放一次;关闭“重复”时,片尾在最后一张照片之后播放。身份标识即“叠加”中设置的那个。标题与幻灯片一样淡入淡出,随机顺序不会移动它们。","This screen is off: turn it on under Titles to play it.": "此画面已关闭:在“标题”中打开即可播放。","The intro screen, before the first photo.": "片头画面,在第一张照片之前。",- "The ending screen, after the last photo.": "片尾画面,在最后一张照片之后。"+ "The ending screen, after the last photo.": "片尾画面,在最后一张照片之后。",+ "Templates": "模板",+ "Built-in": "内置",+ "Your templates": "你的模板",+ "None yet: save the current settings as a template below.": "还没有:在下方将当前设置保存为模板。",+ "Before the last template": "应用上一个模板之前",+ "Previous settings": "之前的设置",+ "New template name": "新模板名称",+ "Save as Template": "存储为模板",+ "Import…": "导入…",+ "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "你自己的模板需要设置文件夹,而此版本没有;内置模板可以使用。",+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "单击模板即可应用;指向模板可在所选照片上预览。右键单击你自己的模板可更新、重命名、导出或删除。",+ "Import Slideshow Templates": "导入幻灯片放映模板",+ "Export Slideshow Template": "导出幻灯片放映模板",+ "Slideshow Templates": "幻灯片放映模板",+ "Plain Black": "纯黑",+ "Gallery Wall": "画廊墙",+ "Edge to Edge": "满屏",+ "Cinema Wide": "宽银幕",+ "Shooting Data": "拍摄数据",+ "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "每张照片尽可能大地显示在黑色背景上,带短暂交叉淡化。上面不绘制任何内容。",+ "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "浅灰色墙面、白色卡纸和柔和阴影;照片下方显示说明和星级。",+ "Every photo cropped to fill the whole screen, with slow crossfades.": "每张照片裁剪以填满整个屏幕,带缓慢交叉淡化。",+ "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "16:9 画面,上下黑边,标题在角落,经黑色淡入淡出,并有结尾卡。",+ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "深石板色背景,每张照片下方显示曝光、ISO 和焦距,再下面是相机和镜头。"}diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.jsonindex 0b2ec7657..e3e30a19b 100644--- a/crates/ui-egui/locales/zh-hant-formats.json+++ b/crates/ui-egui/locales/zh-hant-formats.json@@ -228,5 +228,14 @@"+{n} more": "還有 {n} 項","1 task is still running: {names}. Quitting stops it.": "仍有 1 個工作在執行:{names}。結束將停止它。","{n} tasks are still running: {names}. Quitting stops them.": "仍有 {n} 個工作在執行:{names}。結束將停止它們。",- "{what} merge cancelled": "已取消{what}合併"+ "{what} merge cancelled": "已取消{what}合併",+ "Applied {name}": "已套用 {name}",+ "Delete “{name}”?": "刪除「{name}」?",+ "Updated {name}": "已更新 {name}",+ "Exported to {path}": "已匯出到 {path}",+ "Saved template {name}": "已儲存範本 {name}",+ "Imported {name}": "已匯入 {name}",+ "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.jsonindex c217a16d6..66e802ef9 100644--- a/crates/ui-egui/locales/zh-hant.json+++ b/crates/ui-egui/locales/zh-hant.json@@ -1938,5 +1938,29 @@"The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "片頭在第一張照片之前播放一次;關閉「重複」時,片尾在最後一張照片之後播放。身分標識即「疊加」中設定的那個。標題與幻燈片一樣淡入淡出,隨機順序不會移動它們。","This screen is off: turn it on under Titles to play it.": "此畫面已關閉:在「標題」中開啟即可播放。","The intro screen, before the first photo.": "片頭畫面,在第一張照片之前。",- "The ending screen, after the last photo.": "片尾畫面,在最後一張照片之後。"+ "The ending screen, after the last photo.": "片尾畫面,在最後一張照片之後。",+ "Templates": "範本",+ "Built-in": "內建",+ "Your templates": "你的範本",+ "None yet: save the current settings as a template below.": "還沒有:在下方將目前設定儲存為範本。",+ "Before the last template": "套用上一個範本之前",+ "Previous settings": "之前的設定",+ "New template name": "新範本名稱",+ "Save as Template": "儲存為範本",+ "Import…": "匯入…",+ "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "你自己的範本需要設定資料夾,而此版本沒有;內建範本可以使用。",+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "按一下範本即可套用;指向範本可在所選照片上預覽。在你自己的範本上按右鍵可更新、重新命名、匯出或刪除。",+ "Import Slideshow Templates": "匯入幻燈片秀範本",+ "Export Slideshow Template": "匯出幻燈片秀範本",+ "Slideshow Templates": "幻燈片秀範本",+ "Plain Black": "純黑",+ "Gallery Wall": "畫廊牆",+ "Edge to Edge": "滿版",+ "Cinema Wide": "寬銀幕",+ "Shooting Data": "拍攝資料",+ "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "每張照片盡可能大地顯示在黑色背景上,帶短暫交叉淡化。上面不繪製任何內容。",+ "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "淺灰色牆面、白色卡紙和柔和陰影;照片下方顯示說明和星級。",+ "Every photo cropped to fill the whole screen, with slow crossfades.": "每張照片裁切以填滿整個螢幕,帶緩慢交叉淡化。",+ "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "16:9 畫面,上下黑邊,標題在角落,經黑色淡入淡出,並有結尾卡。",+ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "深石板色背景,每張照片下方顯示曝光、ISO 和焦距,再下面是相機和鏡頭。"}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 65057d7e8..fec622092 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -154,6 +154,10 @@ pub struct Services {pub pick_curve_preset_files: Option<PickFiles>,/// Save dialog for an exported `.lccurve` file.pub save_curve_preset_file: Option<SaveFile>,+ /// Open dialog for slideshow template files (`.json`; Settings ▸ Slideshow ▸ Templates ▸ Import…).+ pub pick_slideshow_templates: Option<PickFiles>,+ /// Save dialog for an exported slideshow template (`.json`).+ pub save_slideshow_template: Option<SaveFile>,pub write: Option<WriteFn>,/// Thread-safe writer: with it, UI-started exports run in the background (desktop only).pub write_shared: Option<SharedWrite>,diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex 363c53651..f205da3d7 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -29,6 +29,7 @@ pub mod second;pub mod settings;pub mod slide_layout;pub mod slide_overlays;+pub mod slide_templates;pub mod slide_titles;pub mod slideshow;pub mod strip;diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rsindex ce87d94cb..3f59df629 100644--- a/crates/ui-egui/src/panels/settings.rs+++ b/crates/ui-egui/src/panels/settings.rs@@ -654,6 +654,8 @@ fn slideshow_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {ui.allocate_ui_with_layout(egui::vec2(SLIDESHOW_COLUMN_W, tall), top_down, |ui| {ui.set_width(SLIDESHOW_COLUMN_W);egui::ScrollArea::vertical().id_salt("settingsSlideshowScroll").max_height(tall).auto_shrink([false, true]).show(ui, |ui| {+ super::slide_templates::section(app, ui, t);+ ui.add_space(6.0);playback_section(app, ui, t);ui.add_space(6.0);super::slide_layout::sections(app, ui, t);diff --git a/crates/ui-egui/src/panels/slide_layout.rs b/crates/ui-egui/src/panels/slide_layout.rsindex 4a5bde3fa..62f7626c3 100644--- a/crates/ui-egui/src/panels/slide_layout.rs+++ b/crates/ui-egui/src/panels/slide_layout.rs@@ -10,6 +10,7 @@use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};use lightcraft_engine::slide::{Aspect, SlideSettings};+use lightcraft_engine::slide_template::SlideLook;use lightcraft_slideshow::{MARGIN_MAX, SHADOW_OFFSET_MAX, SHADOW_RADIUS_MAX, STROKE_MAX};use serde_json::{Value, json};@@ -164,7 +165,11 @@ fn screen_aspect(ctx: &egui::Context) -> f64 {/// The small composed slide of the active photo, with the margin guides when they are on.pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {heading(ui, t, "Preview");- let s = app.session.slide_layout.clone();+ // the template the pointer is over in the Template Browser, else the settings+ let template = super::slide_templates::hovered(ui.ctx()).and_then(|id| app.session.slide_template(&id).ok());+ let look = template.as_ref().map_or_else(|| SlideLook::of(&app.session), |t| t.look.clone());+ let s = look.layout.clone();+ let overlays = look.overlays.clone();let ratio = s.aspect.ratio(screen_aspect(ui.ctx())) as f32;let h = (PREVIEW_W / ratio).clamp(80.0, 320.0);let (rect, _) = ui.allocate_exact_size(vec2(PREVIEW_W, h), Sense::hover());@@ -172,8 +177,15 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {let p = ui.painter_at(rect.expand(1.0));p.rect_stroke(rect, 0.0, Stroke::new(1.0, t.text_dim.gamma_multiply(0.5)), egui::StrokeKind::Outside);super::slide_titles::preview_choice(ui);+ if let Some(tpl) = &template {+ let name = if tpl.builtin { crate::i18n::tr(&tpl.name).to_string() } else { tpl.name.clone() };+ ui.label(egui::RichText::new(crate::i18n::tr_format!("Template preview: {name}", name = name)).size(11.0).color(t.accent));+ if !tpl.description.is_empty() {+ hint(ui, t, &tpl.description);+ }+ }if let Some(title) = super::slide_titles::preview_shows(ui.ctx()) {- title_preview(app, ui, t, rect, title);+ title_preview(app, ui, t, rect, title, &look);return;}let Some(id) = app.session.active() else {@@ -184,15 +196,15 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {let ppp = ui.ctx().pixels_per_point();let (pw, ph) = (((PREVIEW_W * ppp).round() as usize).max(16), ((h * ppp).round() as usize).max(16));// the overlays and what they show of the photo (its rating, its metadata) change it too- let shown = app.session.catalog.photo(id).filter(|_| app.session.slide_overlays.any()).map_or(0, |p| {+ let shown = app.session.catalog.photo(id).filter(|_| overlays.any()).map_or(0, |p| {use std::hash::{Hash, Hasher};let mut h = std::collections::hash_map::DefaultHasher::new();p.rating.hash(&mut h);serde_json::to_string(&p.meta).unwrap_or_default().hash(&mut h);h.finish()});- let overlays = if app.session.slide_overlays.any() { app.session.slide_overlays.pixel_key() ^ shown.rotate_left(5) } else { 0 };- let key = s.pixel_key() ^ id.0.rotate_left(17) ^ ((pw as u64) << 32 | ph as u64) ^ overlays.rotate_left(29);+ let overlay_key = if overlays.any() { overlays.pixel_key() ^ shown.rotate_left(5) } else { 0 };+ let key = s.pixel_key() ^ id.0.rotate_left(17) ^ ((pw as u64) << 32 | ph as u64) ^ overlay_key.rotate_left(29);let now = ui.input(|i| i.time);let mem = egui::Id::new("settingsSlideshowPreviewKey");let (last, since) = ui.ctx().data(|d| d.get_temp::<(u64, f64)>(mem)).unwrap_or((0, f64::NEG_INFINITY));@@ -205,7 +217,7 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {if current.is_none() || still >= DEBOUNCE {let side = super::detail::texture_side(ui.ctx());let edge = app.ui.settings.loupe_edge(pw.max(ph) as f32, usize::MAX, side);- if let Some(job) = app.session.slide_job_with(&s, id, pw, ph, Some(edge), false) {+ if let Some(job) = app.session.slide_job_look(&s, &overlays, id, pw, ph, Some(edge), false) {app.renderer.request(Slot::SlidePreview, job, 90);}} else {@@ -238,10 +250,10 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {/// The preview showing title screen `title` (composed off the UI thread like the photo's slide,/// once its settings have been still for [`DEBOUNCE`] seconds).-fn title_preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, rect: Rect, title: lightcraft_engine::slideshow::Title) {+fn title_preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, rect: Rect, title: lightcraft_engine::slideshow::Title, look: &SlideLook) {let ppp = ui.ctx().pixels_per_point();let (pw, ph) = (((rect.width() * ppp).round() as usize).max(16), ((rect.height() * ppp).round() as usize).max(16));- let compose = app.session.title_compose(title, pw, ph);+ let compose = std::sync::Arc::new(lightcraft_engine::slide_title::TitleCompose::new(&look.titles, &look.overlays, title, pw, ph));let key = compose.key();let now = ui.input(|i| i.time);let mem = egui::Id::new("settingsSlideshowTitlePreviewKey");@@ -264,12 +276,12 @@ fn title_preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, rect: Rp.image(tex.tex.id(), drawn, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);}None => {- let c = app.session.slide_titles.screen(title).color;+ let c = look.titles.screen(title).color;p.rect_filled(rect, 0.0, Color32::from_rgb(c[0], c[1], c[2]));p.text(rect.center(), Align2::CENTER_CENTER, crate::i18n::tr("Rendering…"), t.font(11.5), Color32::from_gray(200));}}- let hint_text = match (title, app.session.slide_titles.screen(title).enabled) {+ let hint_text = match (title, look.titles.screen(title).enabled) {(_, false) => "This screen is off: turn it on under Titles to play it.",(lightcraft_engine::slideshow::Title::Intro, true) => "The intro screen, before the first photo.",(lightcraft_engine::slideshow::Title::Ending, true) => "The ending screen, after the last photo.",diff --git a/crates/ui-egui/src/panels/slide_templates.rs b/crates/ui-egui/src/panels/slide_templates.rsnew file mode 100644index 000000000..591e3c82a--- /dev/null+++ b/crates/ui-egui/src/panels/slide_templates.rs@@ -0,0 +1,274 @@+//! Settings ▸ Slideshow ▸ Templates: the Template Browser (Lightroom Classic's, at the top of the+//! Slideshow tab until the Slideshow module view exists). Built-in templates (our own designs) and+//! the user's (files in `<settings>/slideshow-templates`), and "Previous settings" once one has been+//! applied (library preferences have no undo).+//!+//! Clicking a template applies it (`slideshow.templates.apply`); hovering one shows it on the+//! selected photo in the live preview beside it ([`hovered`], read by+//! [`super::slide_layout::preview`]) without changing anything. Right-click a user template to+//! update it with the current settings, rename, export or delete it; a built-in to export it.+//! Every action goes through a `slideshow.templates.*` command.++use egui::{RichText, Sense, Stroke, vec2};+use lightcraft_engine::slide_template::{PREVIOUS, SlideLook, Template};+use serde_json::json;++use super::settings::{heading, hint};+use crate::LightcraftApp;+use crate::text_field::TextField;+use crate::theme::Tokens;+use crate::widgets::register;++/// The user templates list is at most this tall (it scrolls past it).+const USER_LIST_H: f32 = 180.0;++fn hovered_key() -> egui::Id {+ egui::Id::new("settingsSlideshowTemplateHovered")+}++/// The template the pointer is over in the browser (its id), which the preview shows.+pub fn hovered(ctx: &egui::Context) -> Option<String> {+ ctx.data(|d| d.get_temp::<Option<String>>(hovered_key())).flatten()+}++fn set_hovered(ctx: &egui::Context, id: Option<String>) {+ ctx.data_mut(|d| d.insert_temp(hovered_key(), id));+}++/// What a row is doing: being renamed (with the text so far), or waiting for a delete to be confirmed.+#[derive(Clone, Debug, PartialEq)]+enum Pending {+ Rename(String, String),+ Delete(String),+}++fn pending_key() -> egui::Id {+ egui::Id::new("settingsSlideshowTemplatePending")+}++fn pending(ctx: &egui::Context) -> Option<Pending> {+ ctx.data(|d| d.get_temp::<Option<Pending>>(pending_key())).flatten()+}++fn set_pending(ctx: &egui::Context, p: Option<Pending>) {+ ctx.data_mut(|d| d.insert_temp(pending_key(), p));+}++/// The name shown for a template: a built-in's in the interface language.+fn shown_name(t: &Template) -> String {+ if t.builtin || t.id == PREVIOUS { crate::i18n::tr(&t.name).to_string() } else { t.name.clone() }+}++/// Is `look` what the settings are now (prepare previews aside: templates don't set it)?+fn is_current(look: &SlideLook, now: &SlideLook) -> bool {+ look.layout == now.layout && look.overlays == now.overlays && look.titles == now.titles && {+ let mut p = look.playback.clone();+ p.prepare_previews = now.playback.prepare_previews;+ p == now.playback+ }+}++/// Run a template command; tell the user how it went.+fn act(app: &mut LightcraftApp, ctx: &egui::Context, cmd: &str, p: serde_json::Value, done: impl FnOnce(&serde_json::Value) -> String) {+ match app.run(cmd, p) {+ Ok(r) => {+ let mut msg = done(&r);+ let warnings: Vec<&str> = r["warnings"].as_array().map(|w| w.iter().filter_map(|w| w.as_str()).collect()).unwrap_or_default();+ if !warnings.is_empty() {+ msg = format!("{msg} · {}", warnings.join(" · "));+ }+ if !msg.is_empty() {+ app.toast(ctx, msg);+ }+ }+ Err(e) => app.toast(ctx, e),+ }+}++fn apply(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, name: &str) {+ let name = name.to_string();+ act(app, ctx, "slideshow.templates.apply", json!({"id": id}), |_| crate::i18n::tr_format!("Applied {name}", name = name));+}++/// One template row (`template:{id}`): click applies, hover previews, right-click for its menu.+fn template_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, tpl: &Template, current: bool, hovered: &mut Option<String>) {+ let ctx = ui.ctx().clone();+ let name = shown_name(tpl);+ if let Some(Pending::Rename(id, mut text)) = pending(&ctx).filter(|p| matches!(p, Pending::Rename(id, _) if *id == tpl.id)) {+ let r = TextField::singleline("field:slideshowTemplateRename", &mut text)+ .width(ui.available_width().clamp(80.0, 260.0))+ .select_on_focus(true)+ .show(ui);+ if !r.editing && r.ending.is_none() {+ r.response.request_focus();+ }+ if r.committed() {+ set_pending(&ctx, None);+ if text.trim() != tpl.name {+ act(app, &ctx, "slideshow.templates.rename", json!({"id": id, "name": text}), |_| String::new());+ }+ } else if r.cancelled() {+ set_pending(&ctx, None);+ } else {+ set_pending(&ctx, Some(Pending::Rename(id, text)));+ }+ return;+ }+ if pending(&ctx) == Some(Pending::Delete(tpl.id.clone())) {+ ui.horizontal(|ui| {+ ui.label(RichText::new(crate::i18n::tr_format!("Delete “{name}”?", name = name)).color(t.caution));+ if crate::widgets::text_button(ui, "slideshowTemplateDeleteConfirm", "Delete", false).clicked() {+ set_pending(&ctx, None);+ act(app, &ctx, "slideshow.templates.delete", json!({"id": tpl.id}), |_| String::new());+ }+ if crate::widgets::text_button(ui, "slideshowTemplateDeleteCancel", "Cancel", false).clicked() {+ set_pending(&ctx, None);+ }+ });+ return;+ }+ let w = ui.available_width();+ let (rect, resp) = ui.allocate_exact_size(vec2(w, 22.0), Sense::click());+ register(&ctx, format!("template:{}", tpl.id), rect);+ if resp.hovered() || resp.context_menu_opened() {+ *hovered = Some(tpl.id.clone());+ }+ let p = ui.painter();+ if resp.hovered() {+ p.rect_filled(rect, 3.0, t.hover);+ }+ if current {+ p.rect_stroke(rect.shrink(0.5), 3.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside);+ }+ let colour = if current { t.text } else { t.text_label };+ p.text(rect.left_center() + vec2(8.0, 0.0), egui::Align2::LEFT_CENTER, &name, t.font(12.0), colour);+ if resp.clicked() {+ apply(app, &ctx, &tpl.id, &name);+ }+ resp.context_menu(|ui| menu(app, ui, tpl, &name));+}++/// A menu entry registered as `button:{id}`.+fn item(ui: &mut egui::Ui, id: &str, label: &str, enabled: bool) -> bool {+ let r = ui.add_enabled(enabled, egui::Button::new(crate::i18n::tr(label)));+ register(ui.ctx(), format!("button:{id}"), r.rect);+ r.clicked()+}++fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, tpl: &Template, name: &str) {+ let ctx = ui.ctx().clone();+ if item(ui, "slideshowTemplateApply", "Apply", true) {+ apply(app, &ctx, &tpl.id, name);+ ui.close();+ }+ let user = !tpl.builtin && tpl.id != PREVIOUS;+ if user {+ if item(ui, "slideshowTemplateUpdate", "Update with Current Settings", true) {+ let n = name.to_string();+ act(app, &ctx, "slideshow.templates.update", json!({"id": tpl.id}), |_| crate::i18n::tr_format!("Updated {name}", name = n));+ ui.close();+ }+ if item(ui, "slideshowTemplateRename", "Rename…", true) {+ set_pending(&ctx, Some(Pending::Rename(tpl.id.clone(), tpl.name.clone())));+ ui.close();+ }+ }+ if tpl.id != PREVIOUS && item(ui, "slideshowTemplateExport", "Export…", app.services.save_slideshow_template.is_some()) {+ let file = format!("{}.json", lightcraft_engine::slide_template::file_stem(&tpl.name).unwrap_or_else(|| "Slideshow Template".into()));+ if let Some(path) = app.services.save_slideshow_template.as_mut().and_then(|save| save(&file)) {+ act(app, &ctx, "slideshow.templates.export", json!({"id": tpl.id, "path": path}), |r| {+ crate::i18n::tr_format!("Exported to {path}", path = r["path"].as_str().unwrap_or_default())+ });+ }+ ui.close();+ }+ if user {+ ui.separator();+ if item(ui, "slideshowTemplateDelete", "Delete", true) {+ set_pending(&ctx, Some(Pending::Delete(tpl.id.clone())));+ ui.close();+ }+ }+}++/// A group heading inside the browser.+fn group(ui: &mut egui::Ui, t: &Tokens, text: &str) {+ ui.add_space(2.0);+ ui.label(RichText::new(crate::i18n::tr(text)).size(11.0).color(t.text_dim));+}++/// The Templates section.+pub fn section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {+ let ctx = ui.ctx().clone();+ heading(ui, t, "Templates");+ let listing = app.session.slide_templates();+ let now = SlideLook::of(&app.session);+ let mut over: Option<String> = None;+ group(ui, t, "Built-in");+ for tpl in listing.templates.iter().filter(|t| t.builtin) {+ template_row(app, ui, t, tpl, is_current(&tpl.look, &now), &mut over);+ }+ group(ui, t, "Your templates");+ let user: Vec<_> = listing.templates.iter().filter(|t| !t.builtin).cloned().collect();+ if user.is_empty() {+ hint(ui, t, "None yet: save the current settings as a template below.");+ } else {+ egui::ScrollArea::vertical().id_salt("settingsSlideshowTemplatesUser").max_height(USER_LIST_H).auto_shrink([false, true]).show(ui, |ui| {+ for tpl in &user {+ template_row(app, ui, t, tpl, is_current(&tpl.look, &now), &mut over);+ }+ });+ }+ if let Ok(prev) = app.session.slide_template(PREVIOUS) {+ group(ui, t, "Before the last template");+ template_row(app, ui, t, &prev, false, &mut over);+ }+ set_hovered(&ctx, over);++ // save the current settings as a new template+ ui.add_space(4.0);+ ui.horizontal(|ui| {+ let mem = egui::Id::new("settingsSlideshowTemplateNewName");+ let mut name: String = ui.data(|d| d.get_temp(mem)).unwrap_or_default();+ let r = TextField::singleline("field:slideshowTemplateName", &mut name).hint(crate::i18n::tr("New template name")).width(180.0).show(ui);+ let save = crate::widgets::text_button(ui, "slideshowTemplateSave", "Save as Template", false).clicked()+ || (r.ending == Some(crate::text_field::Ending::Return) && !name.trim().is_empty());+ if save {+ let n = name.trim().to_string();+ match app.run("slideshow.templates.save", json!({"name": n})) {+ Ok(_) => {+ app.toast(&ctx, crate::i18n::tr_format!("Saved template {name}", name = n));+ name.clear();+ }+ Err(e) => app.toast(&ctx, e),+ }+ }+ ui.data_mut(|d| d.insert_temp(mem, name));+ if app.services.pick_slideshow_templates.is_some() && crate::widgets::text_button(ui, "slideshowTemplateImport", "Import…", false).clicked()+ {+ let paths = app.services.pick_slideshow_templates.as_mut().map(|pick| pick()).unwrap_or_default();+ for path in paths {+ act(app, &ctx, "slideshow.templates.import", json!({"path": path}), |r| {+ crate::i18n::tr_format!("Imported {name}", name = r["name"].as_str().unwrap_or_default())+ });+ }+ }+ });+ if app.session.slide_templates_dir.is_none() {+ hint(ui, t, "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.");+ } else {+ hint(+ ui,+ t,+ "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.",+ );+ }+ // files that couldn't be read+ for p in listing.problems.iter().take(4) {+ ui.label(RichText::new(crate::i18n::tr_format!("Skipped {problem}", problem = p)).size(11.0).color(t.caution));+ }+ if listing.problems.len() > 4 {+ let more = listing.problems.len() - 4;+ ui.label(RichText::new(crate::i18n::tr_format!("…and {more} more", more = more)).size(11.0).color(t.caution));+ }+}diff --git a/crates/ui-egui/src/tests_slideshow.rs b/crates/ui-egui/src/tests_slideshow.rsindex e11d33158..24aa0d728 100644--- a/crates/ui-egui/src/tests_slideshow.rs+++ b/crates/ui-egui/src/tests_slideshow.rs@@ -233,6 +233,8 @@ fn playback_settings_drive_the_slideshow_and_bad_ones_are_refused() {run(&mut h, "view.slideshowOptions", json!({}));h.step();assert!(h.app.widgets.iter().any(|(w, _)| w == "check:settings.slideshowRandom"));+ // (below the Templates at the top of the tab)+ reveal(&mut h, "check:settings.slideshowRandom");let r = h.request("ui.clickWidget", json!({"id": "check:settings.slideshowRandom"}), T);assert_eq!(r["ok"], true, "{r}");h.step();@@ -609,3 +611,115 @@ fn settings_shows_the_titles_and_the_preview_shows_a_title_screen() {assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::SlidePreview).is_some_and(|t| t.photo == first)));h.settle(SETTLE);}++/// Settings ▸ Slideshow ▸ Templates: built-ins listed, hover previews on the selected photo+/// without changing anything, a click applies, and the user's own templates are saved, updated,+/// renamed and deleted from the browser.+#[test]+fn template_browser_previews_on_hover_applies_and_manages_user_templates() {+ use lightcraft_engine::slide_template::SlideLook;+ let mut h = grid();+ let dir = std::env::temp_dir().join(format!("lc-ui-sstpl-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ h.app.session.slide_templates_dir = Some(dir.clone());+ let first = h.app.session.visible_cloned()[0];+ run(&mut h, "library.select", json!({"ids": [first.0]}));+ run(&mut h, "view.slideshowOptions", json!({}));+ assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::SlidePreview).is_some_and(|t| t.photo == first)));+ let has = |h: &Headless, w: &str| h.app.widgets.iter().any(|(id, _)| id == w);+ let rect = |h: &Headless, w: &str| h.app.widgets.iter().find(|(id, _)| id == w).map(|(_, r)| *r).unwrap();+ for w in [+ "template:builtin:plain-black",+ "template:builtin:gallery-wall",+ "template:builtin:edge-to-edge",+ "template:builtin:cinema-wide",+ "template:builtin:shooting-data",+ "field:slideshowTemplateName",+ "button:slideshowTemplateSave",+ ] {+ assert!(has(&h, w), "{w}");+ }+ // hover: the preview shows Gallery Wall (its light grey wall in the margin), nothing changes+ let before = SlideLook::of(&h.app.session);+ let r = h.request("ui.hoverWidget", json!({"id": "template:builtin:gallery-wall"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ assert_eq!(crate::panels::slide_templates::hovered(&h.view.ctx).as_deref(), Some("builtin:gallery-wall"));+ let grey = |h: &Headless| {+ let r = rect(h, "slideshow:preview");+ let img = h.paint();+ let c = painted(&img, (r.left() + 3.0) as usize, r.center().y as usize);+ c.iter().all(|v| (200..=230).contains(v))+ };+ assert!(h.step_until(SETTLE, grey), "the hovered template on the selected photo");+ assert_eq!(SlideLook::of(&h.app.session), before, "hovering changes nothing");+ assert!(h.app.session.slide_templates_previous.is_none());+ // a click applies it+ let r = h.request("ui.clickWidget", json!({"id": "template:builtin:gallery-wall"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ assert!(h.app.session.slide_overlays.rating_stars.enabled && h.app.session.slide_layout.stroke_border);+ assert!(has(&h, "template:previous"), "Previous settings appear");+ // save as a template of our own+ let r = h.request("ui.clickWidget", json!({"id": "field:slideshowTemplateName"}), T);+ assert_eq!(r["ok"], true, "{r}");+ let r = h.request("ui.text", json!({"text": "Holiday / 2026"}), T);+ assert_eq!(r["ok"], true, "{r}");+ let r = h.request("ui.clickWidget", json!({"id": "button:slideshowTemplateSave"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ assert!(dir.join("Holiday _ 2026.json").exists(), "the separator never makes a folder");+ h.step();+ assert!(has(&h, "template:user:Holiday _ 2026"));+ // update it from its menu with changed settings+ run(&mut h, "slideshow.layout", json!({"backdropColor": "#123456"}));+ let r = h.request("ui.clickWidget", json!({"id": "template:user:Holiday _ 2026", "button": "right"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ for w in ["button:slideshowTemplateUpdate", "button:slideshowTemplateRename", "button:slideshowTemplateExport", "button:slideshowTemplateDelete"]+ {+ assert!(has(&h, w), "{w}");+ }+ let r = h.request("ui.clickWidget", json!({"id": "button:slideshowTemplateUpdate"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ assert_eq!(h.app.session.slide_template("user:Holiday _ 2026").unwrap().look.layout.backdrop_color, [0x12, 0x34, 0x56]);+ // rename it in place+ let r = h.request("ui.clickWidget", json!({"id": "template:user:Holiday _ 2026", "button": "right"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ let r = h.request("ui.clickWidget", json!({"id": "button:slideshowTemplateRename"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ h.step();+ assert!(has(&h, "field:slideshowTemplateRename"));+ let r = h.request("ui.key", json!({"key": "a", "cmd": true}), T);+ assert_eq!(r["ok"], true, "{r}");+ let r = h.request("ui.text", json!({"text": "Summer"}), T);+ assert_eq!(r["ok"], true, "{r}");+ let r = h.request("ui.key", json!({"key": "enter"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ h.step();+ assert!(has(&h, "template:user:Summer"), "{:?}", h.app.session.slide_templates().templates.iter().map(|t| t.id.clone()).collect::<Vec<_>>());+ // delete it (after confirming)+ let r = h.request("ui.clickWidget", json!({"id": "template:user:Summer", "button": "right"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ let r = h.request("ui.clickWidget", json!({"id": "button:slideshowTemplateDelete"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ h.step();+ assert!(dir.join("Summer.json").exists(), "not before it is confirmed");+ let r = h.request("ui.clickWidget", json!({"id": "button:slideshowTemplateDeleteConfirm"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ assert!(!dir.join("Summer.json").exists());+ // back to the settings before Gallery Wall+ let r = h.request("ui.clickWidget", json!({"id": "template:previous"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ assert_eq!(SlideLook::of(&h.app.session).overlays, before.overlays);+ h.settle(SETTLE);+ let _ = std::fs::remove_dir_all(dir);+}diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex efe960c43..bee1fa1d9 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -80,7 +80,11 @@ filmstrip is visible.| `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes || `engine.execute {command: "slideshow.overlays"}` | `{identityPlate?: {enabled?, text?, image?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, behind?}, ratingStars?: {enabled?, color?, size?, anchor?, …}, texts?: [{text?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, shadow?, shadowOpacity?, shadowOffset?, shadowRadius?, shadowAngle?}], addText?, removeText?, showWatermark?, watermark?}` (see `engine.commands`) | The overlays drawn on every slide, saved with the library: sizes and offsets are fractions of the slide's shorter side, anchors `topLeft`…`bottomRight` of the `slide` or the `photo`; text overlays expand tokens (`{caption}`, `{exposure}`, `{date}`, the file-naming tokens…; unknown tags show as typed); `watermark` takes the export watermark's keys. Replies with the settings and `warnings` || `engine.execute {command: "slideshow.titles"}` | `{intro?: screen, ending?: screen}`, a screen being `{enabled?, color?, content?: "none"\|"identityPlate"\|"text", text?, overrideColor?, textColor?, scale?, duration?: seconds\|null}` | The intro and ending screens, saved with the library: a background colour and, centred, the Overlays identity plate or the screen's own text, in the plate's colour or `textColor` when `overrideColor` is on, `scale` = its height as a fraction of the slide's shorter side; `duration` null = the slide duration. The intro plays once before the first photo, the ending after the last when repeat is off. Replies with the settings and `warnings` |-| `engine.execute {command: "slideshow.preview"}` | `{id?, title?, width?, height?, path?}` | One slide composed with the layout and overlays, as the slideshow plays it (with `title: "intro"\|"ending"`, that title screen instead → `{title, enabled, width, height, plate}`): a PNG written to `path`, or returned base64 in `png` without one; `{id, width, height, cell, photo, overlays}` (`cell` and `photo` are `[x0, y0, x1, y1]` in slide pixels; `overlays` lists `{kind, box}` for each drawn overlay). Sides 16–4096; one side given takes the other from the aspect preview |+| `engine.execute {command: "slideshow.preview"}` | `{id?, title?, template?, width?, height?, path?}` | One slide composed with the layout and overlays, as the slideshow plays it (with `template: id`, with that template's settings instead, leaving the library's alone: the Template Browser's hover preview) (with `title: "intro"\|"ending"`, that title screen instead → `{title, enabled, width, height, plate}`): a PNG written to `path`, or returned base64 in `png` without one; `{id, width, height, cell, photo, overlays}` (`cell` and `photo` are `[x0, y0, x1, y1]` in slide pixels; `overlays` lists `{kind, box}` for each drawn overlay). Sides 16–4096; one side given takes the other from the aspect preview |+| `engine.execute {command: "slideshow.templates.list"}` | `{}` | The Template Browser: `{templates: [{id, name, builtin, group, description?, path?}], previous, folder, problems}` — built-ins (`builtin:…`, our own designs) then user templates (`user:<file>`, files in `<settings>/slideshow-templates`, at most 1000); `problems` lists files skipped and why |+| `engine.execute {command: "slideshow.templates.apply"}` | `{id}` or `{name}`; `{id: "previous"}` | Replaces the playback (prepare previews kept), layout, overlays and titles settings with the template's, saved with the library. No undo: the replaced settings become `previous` for the session → `{applied, name, warnings, previous, settings}` (`warnings`: a background photo not in this library, an unreadable plate or watermark image…) |+| `engine.execute {command: "slideshow.templates.save"}` / `update` / `rename` / `delete` | `{name, replace?}` / `{id}` / `{id, name}` / `{id}` | Save the current settings as a user template (`<name>.json`; path separators and reserved characters become `_`, a taken or built-in name is refused unless `replace`), update one with the current settings, rename (its file follows), delete. Built-ins can't change |+| `engine.execute {command: "slideshow.templates.import"}` / `export` | `{path}` / `{id, path}` | Import a template `.json` (at most 256 KB; format, version and every setting checked; a taken name gets " (2)") → `{id, name, renamed, warnings}`; export any template as `.json` || `app.quit` | — | Close the app |Image navigation is also available directly as the UI command `view.navigate`, withdiff --git a/docs/mcp.md b/docs/mcp.mdindex 3cb3586a8..b3b50f808 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -205,7 +205,11 @@ overlays drawn on every slide (identity plate text or image, rating stars, text`{caption}` or `{exposure}`, the export watermark); its reply lists `warnings` (an unreadable plate image, tags thataren't tokens), and `cmd_slideshow_preview` returns each overlay's box. `cmd_slideshow_titles` sets the intro and endingscreens (colour, the identity plate or a line of text, scale, duration), and `cmd_slideshow_preview {title: "intro"}`-renders one.+renders one. Templates bundle all four: `cmd_slideshow_templates_list` lists the built-in and user templates (and files+it skipped), `cmd_slideshow_templates_apply {id}` replaces the settings with one (the replaced ones stay available as+`{id: "previous"}` for the session), `cmd_slideshow_preview {template: id}` previews one without applying it, and+`cmd_slideshow_templates_save` / `update` / `rename` / `delete` / `import` / `export` manage the user's own (JSON files+in `<settings>/slideshow-templates`).## Resourcesdiff --git a/docs/parity-checklist.md b/docs/parity-checklist.mdindex f9e4678cc..fd417806b 100644--- a/docs/parity-checklist.md+++ b/docs/parity-checklist.md@@ -52,10 +52,10 @@ cited here still exists. Formerly docs/parity.md.| X. Cross-cutting behaviours (BEHAV) | 18 | 6 | 1 | 1 | 8/8 (100%) | 6/9 (67%) || Y. Menus | 82 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) || Z. Keyboard shortcuts (desktop) | 75 | 3 | 3 | 1 | 49/52 (94%) | 23/24 (96%) |-| Lightroom Classic extras | 35 | 19 | 29 | 9 | — | 23/25 (92%) |-| **Total** | 399 | 53 | 67 | 36 | 192/200 (96%) | 143/155 (92%) |+| Lightroom Classic extras | 35 | 20 | 28 | 9 | — | 23/25 (92%) |+| **Total** | 399 | 54 | 66 | 36 | 192/200 (96%) | 143/155 (92%) |-Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **82.0%** of 519 in-scope rows — P0 98.0% of 200 · P1 95.2% of 155 · P2 49.7% of 163.+Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **82.1%** of 519 in-scope rows — P0 98.0% of 200 · P1 95.2% of 155 · P2 50.0% of 163.<!-- /parity:summary -->## Top gaps and shortcut notes@@ -727,7 +727,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-| LRC-BOOK-BG | Book backgrounds | P2 | ⬜ | | || LRC-BOOK-VIEWS | Book views | P2 | ⬜ | | || LRC-BOOK-EXPORT | Book export (PDF/JPEG) | P2 | ⬜ | | |-| LRC-SS-TEMPLATES | Slideshow templates | P2 | ⬜ | | |+| LRC-SS-TEMPLATES | Slideshow templates | P2 | 🟡 | `cmd:slideshow.templates.list`, `cmd:slideshow.templates.apply`, `cmd:slideshow.templates.save`, `cmd:slideshow.templates.update`, `cmd:slideshow.templates.rename`, `cmd:slideshow.templates.delete`, `cmd:slideshow.templates.import`, `cmd:slideshow.templates.export`, `cmd:slideshow.preview`, `path:crates/engine/src/slide_template.rs`, `path:crates/ui-egui/src/panels/slide_templates.rs` | Template Browser at the top of Settings ▸ Slideshow: a template is the Playback (not "prepare previews"), Layout / Options / Backdrop, Overlays and Titles settings as one versioned JSON document. Five built-ins of our own (Plain Black, Gallery Wall, Edge to Edge, Cinema Wide, Shooting Data; no Lightroom names or designs, no image or font files) and the user's own, saved as files in `<settings>/slideshow-templates` (machine-wide, like Classic's): save current settings, Update with Current Settings, rename, delete (confirmed), import / export `.json`. Click applies (one step, saved with the library); pointing at one previews it on the selected photo (or the intro / ending) in the live preview without changing anything (`slideshow.preview {template}`). No undo for library preferences: the settings a template replaced stay as "Previous settings" for the session (applying it again goes forward). Every section is read through its settings' own validation (out-of-range values clamped, wrong types or unknown keys refused), files are capped (256 KB, 1000 listed), a newer format version is refused with a message, a bad file is listed as skipped, names are sanitised into file names that can't leave the folder, a missing plate / watermark image or background photo applies with a warning. Missing: the Slideshow module's left-panel browser (it lives in Settings until the module view exists), template folders (New Folder, moving templates between folders), saving a slideshow with a collection, a preview thumbnail inside the browser itself || LRC-SS-OPTIONS | Slideshow options | P2 | ✅ | `cmd:slideshow.layout`, `cmd:slideshow.preview`, `path:crates/slideshow/src/compose.rs` | Zoom to Fill Frame (the photo covers its image cell, cropped to it; off: fits inside), Stroke Border (colour, width as a share of the slide's shorter side, drawn around the photo), Cast Shadow (opacity, offset, radius, angle; a blurred offset rectangle under the photo and its stroke). Composed by `lightcraft-slideshow` (CPU, no UI) for playback, the Settings ▸ Slideshow preview and `slideshow.preview`; edited in Settings ▸ Slideshow until the Slideshow module view exists || LRC-SS-LAYOUT | Slideshow layout | P2 | 🟡 | `cmd:slideshow.layout`, `cmd:slideshow.preview`, `path:crates/ui-egui/src/panels/slide_layout.rs` | Margins left / right / top / bottom (linked or each on its own; shares of the slide's shorter side, so any screen or output size looks the same), Show Guides, Aspect Preview (Screen, 16:9, 4:3). Missing: the Slideshow module's slide editor — guides are drawn only in the Settings ▸ Slideshow preview and can't be dragged to set the margins; the aspect preview applies to that preview and `slideshow.preview` (playback always fills the screen, as in Classic) || LRC-SS-OVERLAYS | Slideshow overlays | P2 | 🟡 | `cmd:slideshow.overlays`, `cmd:slideshow.preview`, `path:crates/engine/src/slide_overlay.rs`, `path:crates/ui-egui/src/panels/slide_overlays.rs` | Identity plate (text with size / colour / opacity, or a PNG / JPEG file with its transparency; render behind image), rating stars (our own vector stars, colour, size), text overlays (up to 16) with tokens (`{file}`, `{caption}`, `{title}`, `{date}`, `{exposure}`, `{shutter}`, `{aperture}`, `{focal}`, `{iso}`, `{camera}`, `{lens}`, `{rating}`, `{copyright}` and the other rename tokens; unknown tags show as typed and are reported), size / colour / opacity and a drop shadow (opacity, offset, radius, angle); each at one of nine anchors of the slide or the photo plus an offset, kept on the slide; the export watermark on the photo. Sizes relative to the slide; drawn by the engine over the composed slide (Inter + craft-fonts CJK, the export watermark's text renderer) for playback, the Settings ▸ Slideshow preview and `slideshow.preview`. Missing: dragging overlays on the slide in a Slideshow module editor, font family / style choice (Inter SemiBold only), the Identity Plate Editor's styled multi-run text, right-to-left reordering (Arabic / Hebrew draw in logical order, and without glyphs in Inter) |diff --git a/docs/whats-new.md b/docs/whats-new.mdindex 07d178b25..2dfb22884 100644--- a/docs/whats-new.md+++ b/docs/whats-new.md@@ -1,5 +1,26 @@# What's new in LightCraft+## 2026-10-11++### Slideshow templates+- Settings ▸ Slideshow now opens with a template browser, like Lightroom Classic's Template Browser. A template holds+ everything about how a slideshow looks and plays: the playback timing and fades, the layout, options and backdrop,+ the overlays and the intro and ending screens. Click one to apply it; point at one to see it on the selected photo in+ the preview beside it without changing anything.+- Five built-in templates of our own: Plain Black (the photo on black), Gallery Wall (a light wall, a white mat and a+ soft shadow, with the caption and rating under the photo), Edge to Edge (photos cropped to fill the screen), Cinema+ Wide (16:9 with black bars, the title in the corner, fades through black and a closing card) and Shooting Data (the+ exposure, ISO, focal length, camera and lens under each photo on a dark backdrop).+- Save the current settings as a template of your own; right-click it to update it with the current settings, rename,+ export or delete it, and import templates others share with you. Your templates are `.json` files in the settings+ folder's `slideshow-templates` folder, shared by all your libraries.+- Applying a template can't be undone with Edit ▸ Undo (slideshow settings are library preferences), so the settings it+ replaced are listed as "Previous settings" until you quit: click that to go back.+- A template file that can't be used (damaged, from a newer LightCraft, too large) is listed as skipped instead of+ stopping the others, and a template whose identity plate image or background photo isn't there still applies, with a+ note saying what is missing. Agents use `slideshow.templates.*`, and `slideshow.preview {template}` renders a template+ without applying it.+## 2026-10-10### Slideshow intro and ending screens