Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

LRC-PRINT-LAYOUTSTYLE: print.* commands for the layout styles, cells, templates and PDF

Atmik Shetty3b32f82e9e87
diff --git a/apps/lightcraft-cli/tests/cli.rs b/apps/lightcraft-cli/tests/cli.rs
index 9aafc9310..fe29704b1 100644
--- a/apps/lightcraft-cli/tests/cli.rs
+++ b/apps/lightcraft-cli/tests/cli.rs
@@ -47,6 +47,45 @@ fn contact_sheet_exports_pdf_and_protects_originals() {
assert_eq!(std::fs::read(&out).unwrap(), prior, "failed export changed prior output");
}
+#[test]
+fn print_commands_chain_into_a_picture_package_pdf() {
+ let input = tmp("print-input.png");
+ gradient_png(&input);
+ let out = tmp("print.pdf");
+ let (ok, lines, err) = run_cli(
+ &[
+ "--import",
+ input.to_str().unwrap(),
+ "print.set",
+ r#"layout={"style":"picturePackage","page":{"paper":"4x6","orientation":"landscape"}}"#,
+ r#"image={"zoomToFill":true,"borderEnabled":true,"borderWidth":0.05}"#,
+ "job={\"ppi\":72}",
+ "print.cell.add",
+ "width=1.5",
+ "height=1",
+ "print.cell.add",
+ "width=1.5",
+ "height=1",
+ "print.layout.autoLayout",
+ "print.exportPdf",
+ &format!("path={}", out.display()),
+ ],
+ None,
+ );
+ assert!(ok, "{err}: {lines:?}");
+ let export = lines.last().unwrap();
+ assert_eq!((export["result"]["pages"].as_u64(), export["result"]["photos"].as_u64()), (Some(1), Some(1)));
+ let bytes = std::fs::read(&out).unwrap();
+ assert!(bytes.starts_with(b"%PDF-1.4"));
+ assert!(String::from_utf8_lossy(&bytes).contains("/MediaBox [0 0 432.00 288.00]"), "6 x 4 in");
+ // a bad setting fails the run and writes nothing new
+ let before = std::fs::read(&out).unwrap();
+ let (ok, _, _) =
+ run_cli(&["--import", input.to_str().unwrap(), "print.set", "job={\"ppi\":5}", "print.exportPdf", &format!("path={}", out.display())], None);
+ assert!(!ok);
+ assert_eq!(std::fs::read(&out).unwrap(), before);
+}
+
fn tmp(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lightcraft-cli-test-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 4de460761..5718d6546 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -32,6 +32,7 @@ mod organize;
mod prefs;
mod preset_files;
pub mod previews;
+mod print;
mod query;
mod sync;
mod xmp;
@@ -154,6 +155,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(preset_files::specs());
v.extend(prefs::specs());
v.extend(export::specs());
+ v.extend(print::specs());
v.extend(before::specs());
v.extend(browse::specs());
v.extend(missing::specs());
diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs
new file mode 100644
index 000000000..4fa77df86
--- /dev/null
+++ b/crates/engine/src/cmd/print.rs
@@ -0,0 +1,351 @@
+//! `print.*`: the Print module as commands.
+//!
+//! The module's state is [`Session::print`] (layout, image settings, page, guides, job), so the
+//! app, CLI, control channel and MCP share one print. Lengths are inches in page space (origin at
+//! the top-left of the page as printed); cell ids and photo ids are numbers. Nothing here touches
+//! the catalog, so none of it is journaled or undoable; saved templates live in prefs.json.
+//!
+//! * `print.get`, `print.set {layout?, image?, page?, guides?, job?}`, `print.reset`
+//! * `print.cell.add|move|resize|delete|stack|photo|page`, `print.layout.autoLayout|newPage|clear`
+//! * `print.exportPdf {path, ids?}`
+//! * `print.template.list|save|apply|delete`
+use serde_json::{Value, json};
+
+use super::{CommandSpec, always, bad, cmd, f64_req};
+use crate::print::layout::{Layout, MAX_PAGES, Rect, Snap, Stack, paper_names, paper_size};
+use crate::print::template::{MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_name};
+use crate::{Result, Session};
+
+fn rect_json(r: &Rect) -> Value {
+ json!({"x": r.x, "y": r.y, "w": r.w, "h": r.h})
+}
+
+/// The state, with what a front end needs to draw it (page size, printable area, grid cells).
+fn state(s: &Session, photos: usize) -> Value {
+ let l = &s.print.layout;
+ let mut out = json!({
+ "settings": s.print,
+ "papers": paper_names().filter_map(|n| paper_size(n).map(|(w, h)| json!({"name": n, "width": w, "height": h}))).collect::<Vec<_>>(),
+ "overlaps": l.has_overlaps(),
+ "photos": photos,
+ });
+ if let (Ok((w, h)), Ok(area), Some(o)) = (l.page_size(), l.printable(), out.as_object_mut()) {
+ o.insert("pageWidth".into(), json!(w));
+ o.insert("pageHeight".into(), json!(h));
+ o.insert("printable".into(), rect_json(&area));
+ o.insert("pageCount".into(), json!(l.page_count(photos)));
+ o.insert("cellsPerPage".into(), json!(l.cells_per_page()));
+ if !l.style.is_package() {
+ o.insert("gridCells".into(), json!(l.grid_rects().unwrap_or_default().iter().map(rect_json).collect::<Vec<_>>()));
+ }
+ }
+ out
+}
+
+fn reply(s: &Session) -> Result<Value> {
+ Ok(state(s, s.targets(&Value::Null).len()))
+}
+
+/// Applies `patch` over `dst`: objects merge key by key, anything else replaces.
+fn merge(dst: &mut Value, patch: &Value, depth: usize) {
+ match (dst, patch) {
+ (Value::Object(d), Value::Object(p)) if depth < 8 => {
+ for (k, v) in p {
+ match d.get_mut(k) {
+ Some(slot) => merge(slot, v, depth + 1),
+ None => {
+ d.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ }
+ (d, p) => *d = p.clone(),
+ }
+}
+
+fn get(s: &mut Session, p: &Value) -> Result<Value> {
+ Ok(state(s, s.targets(p).len()))
+}
+
+fn set(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.set";
+ let patch = p.as_object().ok_or_else(|| bad(ID, "params must be an object"))?;
+ if let Some(k) = patch.keys().find(|k| !matches!(k.as_str(), "layout" | "image" | "page" | "guides" | "job")) {
+ return Err(bad(ID, format!("unknown parameter `{k}` (one of layout, image, page, guides, job)")));
+ }
+ if let Some(l) = patch.get("layout").and_then(Value::as_object)
+ && let Some(k) = l.keys().find(|k| matches!(k.as_str(), "cells" | "pages" | "nextId"))
+ {
+ return Err(bad(ID, format!("`layout.{k}` is changed with the print.cell.* and print.layout.* commands")));
+ }
+ let mut value = serde_json::to_value(&s.print).map_err(|e| bad(ID, e.to_string()))?;
+ merge(&mut value, p, 0);
+ let mut next: PrintSettings = serde_json::from_value(value).map_err(|e| bad(ID, e.to_string()))?;
+ // A new paper, orientation or margin may leave cells outside the page: pull them back.
+ if next.layout.page.printable().is_ok() {
+ next.layout.fit_cells().map_err(|e| bad(ID, e))?;
+ }
+ next.validate().map_err(|e| bad(ID, e))?;
+ s.print = next;
+ reply(s)
+}
+
+fn reset(s: &mut Session, _: &Value) -> Result<Value> {
+ s.print = PrintSettings::default();
+ reply(s)
+}
+
+fn cell_id(p: &Value, id: &str) -> Result<u32> {
+ p.get("id").and_then(Value::as_u64).and_then(|v| u32::try_from(v).ok()).ok_or_else(|| bad(id, "missing cell `id`"))
+}
+
+fn opt_f64(p: &Value, key: &str, id: &str) -> Result<Option<f64>> {
+ match p.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(v) => v.as_f64().map(Some).ok_or_else(|| bad(id, format!("`{key}` must be a number"))),
+ }
+}
+
+/// Snaps `r` (a cell being moved or resized) when the call asks for it.
+fn snapped(l: &Layout, guides: &crate::print::layout::Guides, id: u32, r: Rect, p: &Value, resize: bool, cmd: &str) -> Result<Rect> {
+ let on = match p.get("snap") {
+ None | Some(Value::Null) => false,
+ Some(Value::Bool(b)) => *b,
+ Some(_) => return Err(bad(cmd, "`snap` must be true or false")),
+ };
+ if !on || guides.snap == Snap::Off {
+ return Ok(r);
+ }
+ let threshold = opt_f64(p, "threshold", cmd)?.unwrap_or(0.1);
+ let f = if resize { Layout::snap_resize } else { Layout::snap_move };
+ f(l, id, r, guides.snap, guides.grid_size, threshold).map_err(|e| bad(cmd, e))
+}
+
+fn cell_add(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.cell.add";
+ let (w, h) = (f64_req(p, "width", ID)?, f64_req(p, "height", ID)?);
+ let mut next = s.print.layout.clone();
+ let id = next.add_cell(w, h).map_err(|e| bad(ID, e))?;
+ if let (Some(x), Some(y)) = (opt_f64(p, "x", ID)?, opt_f64(p, "y", ID)?) {
+ if let Some(page) = p.get("page").and_then(Value::as_u64) {
+ let page = u32::try_from(page).map_err(|_| bad(ID, "`page` is too large"))?;
+ next.set_cell_page(id, page).map_err(|e| bad(ID, e))?;
+ }
+ next.move_cell(id, x, y).map_err(|e| bad(ID, e))?;
+ }
+ if let Some(v) = p.get("photo").filter(|v| !v.is_null()) {
+ let photo = v.as_u64().ok_or_else(|| bad(ID, "`photo` must be a photo id"))?;
+ next.set_cell_photo(id, Some(photo)).map_err(|e| bad(ID, e))?;
+ }
+ s.print.layout = next;
+ let cell = s.print.layout.cell(id).cloned();
+ Ok(json!({"id": id, "cell": cell, "pages": s.print.layout.pages}))
+}
+
+fn cell_move(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.cell.move";
+ let id = cell_id(p, ID)?;
+ let (x, y) = (f64_req(p, "x", ID)?, f64_req(p, "y", ID)?);
+ let mut next = s.print.layout.clone();
+ let size = next.cell(id).map(|c| c.rect).ok_or_else(|| bad(ID, format!("no cell {id}")))?;
+ let target = snapped(&next, &s.print.guides, id, Rect::new(x, y, size.w, size.h), p, false, ID)?;
+ let r = next.move_cell(id, target.x, target.y).map_err(|e| bad(ID, e))?;
+ s.print.layout = next;
+ Ok(json!({"id": id, "rect": r}))
+}
+
+fn cell_resize(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.cell.resize";
+ let id = cell_id(p, ID)?;
+ let mut next = s.print.layout.clone();
+ let cur = next.cell(id).map(|c| c.rect).ok_or_else(|| bad(ID, format!("no cell {id}")))?;
+ let want = Rect::new(
+ opt_f64(p, "x", ID)?.unwrap_or(cur.x),
+ opt_f64(p, "y", ID)?.unwrap_or(cur.y),
+ opt_f64(p, "width", ID)?.unwrap_or(cur.w),
+ opt_f64(p, "height", ID)?.unwrap_or(cur.h),
+ );
+ let target = snapped(&next, &s.print.guides, id, want, p, true, ID)?;
+ let r = next.resize_cell(id, target).map_err(|e| bad(ID, e))?;
+ s.print.layout = next;
+ Ok(json!({"id": id, "rect": r}))
+}
+
+fn cell_delete(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.cell.delete";
+ let id = cell_id(p, ID)?;
+ s.print.layout.delete_cell(id).map_err(|e| bad(ID, e))?;
+ Ok(json!({"deleted": id, "cells": s.print.layout.cells.len()}))
+}
+
+fn cell_stack(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.cell.stack";
+ let id = cell_id(p, ID)?;
+ let how = match p.get("order").and_then(Value::as_str) {
+ Some("toBack") => Stack::ToBack,
+ Some("backward") => Stack::Backward,
+ Some("forward") => Stack::Forward,
+ Some("toFront") => Stack::ToFront,
+ _ => return Err(bad(ID, "`order` must be toBack, backward, forward or toFront")),
+ };
+ s.print.layout.restack(id, how).map_err(|e| bad(ID, e))?;
+ Ok(json!({"order": s.print.layout.cells.iter().map(|c| c.id).collect::<Vec<_>>()}))
+}
+
+fn cell_photo(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.cell.photo";
+ let id = cell_id(p, ID)?;
+ let photo = match p.get("photo") {
+ None | Some(Value::Null) => None,
+ Some(v) => {
+ let n = v.as_u64().ok_or_else(|| bad(ID, "`photo` must be a photo id or null"))?;
+ if s.catalog.photo(lightcraft_catalog::PhotoId(n)).is_none() {
+ return Err(bad(ID, format!("no photo {n}")));
+ }
+ Some(n)
+ }
+ };
+ s.print.layout.set_cell_photo(id, photo).map_err(|e| bad(ID, e))?;
+ Ok(json!({"id": id, "photo": photo}))
+}
+
+fn cell_page(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.cell.page";
+ let id = cell_id(p, ID)?;
+ let page = p.get("page").and_then(Value::as_u64).and_then(|v| u32::try_from(v).ok()).ok_or_else(|| bad(ID, "missing zero-based `page`"))?;
+ s.print.layout.set_cell_page(id, page).map_err(|e| bad(ID, e))?;
+ Ok(json!({"id": id, "page": page}))
+}
+
+fn auto_layout(s: &mut Session, _: &Value) -> Result<Value> {
+ s.print.layout.auto_layout().map_err(|e| bad("print.layout.autoLayout", e))?;
+ Ok(json!({"pages": s.print.layout.pages, "cells": s.print.layout.cells}))
+}
+
+fn new_page(s: &mut Session, _: &Value) -> Result<Value> {
+ let page = s.print.layout.new_page().map_err(|e| bad("print.layout.newPage", e))?;
+ Ok(json!({"page": page, "pages": s.print.layout.pages, "max": MAX_PAGES}))
+}
+
+fn clear(s: &mut Session, _: &Value) -> Result<Value> {
+ s.print.layout.clear();
+ Ok(json!({"pages": 1, "cells": 0}))
+}
+
+fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.exportPdf";
+ let path = p.get("path").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(ID, "missing path"))?;
+ if let Some(k) = p.as_object().and_then(|o| o.keys().find(|k| !matches!(k.as_str(), "path" | "ids" | "id"))) {
+ return Err(bad(ID, format!("unknown parameter `{k}` (one of path, ids; change the print with print.set)")));
+ }
+ if p.get("ids").is_some_and(|v| v.as_array().is_none_or(|a| a.iter().any(|v| v.as_u64().is_none()))) {
+ return Err(bad(ID, "ids must be an array of photo ids"));
+ }
+ if p.get("id").is_some_and(|v| v.as_u64().is_none()) {
+ return Err(bad(ID, "id must be a photo id"));
+ }
+ s.check_write_target(path).map_err(|e| bad(ID, e))?;
+ let ids = s.targets(p);
+ let settings = s.print.clone();
+ let title = std::path::Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("Print").to_string();
+ let work = crate::print::compose::prepare(s, &settings, &ids).map_err(|e| bad(ID, e))?;
+ let total = work.len() as u64;
+ let row = s.activity.start("export", "Printing to PDF", crate::activity::Cancel::No);
+ row.progress(0, total);
+ let pages = work
+ .run(&mut |done, name| {
+ row.progress(done as u64, total);
+ row.detail(name);
+ true
+ })
+ .map_err(|e| bad(ID, e))?;
+ let bytes = crate::print::output::write(&pages, &settings.job, &title).map_err(|e| bad(ID, e))?;
+ s.check_write_target(path).map_err(|e| bad(ID, e))?;
+ crate::export::write_file(path, &bytes).map_err(|e| bad(ID, e))?;
+ Ok(json!({"path": path, "pages": pages.len(), "photos": ids.len(), "bytes": bytes.len()}))
+}
+
+// ---- templates ------------------------------------------------------------------------------
+
+fn template_list(s: &Session) -> Value {
+ json!({"templates": s.print_templates.iter().map(|t| json!({"name": t.name, "style": t.settings.pointer("/layout/style"), "settings": t.settings})).collect::<Vec<_>>()})
+}
+
+fn template_name(p: &Value, id: &str) -> Result<String> {
+ clean_name(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(id, "missing `name`"))?).map_err(|e| bad(id, e))
+}
+
+fn template_save(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.template.save";
+ let name = template_name(p, ID)?;
+ let t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?;
+ match s.print_templates.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
+ Some(x) => *x = t,
+ None => {
+ if s.print_templates.len() >= MAX_TEMPLATES {
+ return Err(bad(ID, format!("at most {MAX_TEMPLATES} templates; delete one first")));
+ }
+ s.print_templates.push(t);
+ }
+ }
+ s.save_prefs()?;
+ Ok(template_list(s))
+}
+
+fn template_apply(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.template.apply";
+ let name = template_name(p, ID)?;
+ let t = s
+ .print_templates
+ .iter()
+ .find(|x| x.name.eq_ignore_ascii_case(&name))
+ .ok_or_else(|| bad(ID, format!("no print template `{name}` (see print.template.list)")))?;
+ s.print = t.settings(&s.print.guides).map_err(|e| bad(ID, e))?;
+ reply(s)
+}
+
+fn template_delete(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "print.template.delete";
+ let name = template_name(p, ID)?;
+ let before = s.print_templates.len();
+ s.print_templates.retain(|x| !x.name.eq_ignore_ascii_case(&name));
+ if s.print_templates.len() == before {
+ return Err(bad(ID, format!("no print template `{name}`")));
+ }
+ s.save_prefs()?;
+ Ok(template_list(s))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(query "print.get", "Print Settings", [], None,
+ "{ids?} → {settings: {layout, image, page, guides, job}, papers, pageWidth, pageHeight, printable, pageCount, cellsPerPage, gridCells?, overlaps}; lengths are inches",
+ always, get),
+ cmd!(query "print.set", "Set Print Settings", [], None,
+ "{layout?: {style: singleImage|contactSheet|picturePackage|customPackage, page: {paper, customWidth, customHeight, orientation: portrait|landscape, margins: {top,right,bottom,left}}, grid: {columns, rows, spacingX, spacingY, keepSquare}, spacing}, image?: {zoomToFill, rotateToFit, borderEnabled, borderWidth, borderColor: [r,g,b], strokeEnabled, strokeWidthPt, strokeColor}, page?: {background: [r,g,b]}, guides?: {showRulers, units: in|cm|mm|pt, snap: off|cells|grid, gridSize, showMargins, showBleed, showPageGrid, showCells, showDimensions}, job?: {ppi: 72..720}} — merges into the current print; cells and pages change with print.cell.* / print.layout.*; → print.get",
+ always, set),
+ cmd!(query "print.reset", "Reset Print Settings", [], None, "{} → print.get", always, reset),
+ cmd!(query "print.cell.add", "Add Print Cell", [], None,
+ "{width, height, x?, y?, page?, photo?} inches; picture/custom package → {id, cell, pages}; the cell goes to the first free spot unless x and y are given",
+ always, cell_add),
+ cmd!(query "print.cell.move", "Move Print Cell", [], None, "{id, x, y, snap?: bool, threshold?: inches} → {id, rect}; snap uses the guides' snap mode", always, cell_move),
+ cmd!(query "print.cell.resize", "Resize Print Cell", [], None,
+ "{id, width?, height?, x?, y?, snap?: bool, threshold?} → {id, rect}", always, cell_resize),
+ cmd!(query "print.cell.delete", "Delete Print Cell", [], None, "{id}", always, cell_delete),
+ cmd!(query "print.cell.stack", "Arrange Print Cell", [], None, "{id, order: toBack|backward|forward|toFront} → {order: cell ids back to front}", always, cell_stack),
+ cmd!(query "print.cell.photo", "Set Print Cell Photo", [], None, "{id, photo: photo id | null} (custom package: the photo printed in the cell)", always, cell_photo),
+ cmd!(query "print.cell.page", "Move Print Cell to Page", [], None, "{id, page: zero-based}", always, cell_page),
+ cmd!(query "print.layout.autoLayout", "Auto Layout", [], None, "{} — packs the package's cells onto as few pages as possible → {pages, cells}", always, auto_layout),
+ cmd!(query "print.layout.newPage", "New Print Page", [], None, "{} → {page, pages}", always, new_page),
+ cmd!(query "print.layout.clear", "Clear Print Layout", [], None, "{} — removes every cell and extra page", always, clear),
+ cmd!(query "print.exportPdf", "Print to PDF", [], None,
+ "{path, ids?: photo ids (default selection)} → {path, pages, photos, bytes}; prints the current print.get settings; replaces an existing output, never an original",
+ always, export_pdf),
+ cmd!(query "print.template.list", "Print Templates", [], None, "{} → {templates: [{name, style, settings}]}", always, |s, _| Ok(template_list(s))),
+ cmd!(query "print.template.save", "Save Print Template", [], None,
+ "{name} — saves the layout, image settings, page and job (not the cells' photos or the guides); an existing name (any case) is replaced → print.template.list",
+ always, template_save),
+ cmd!(query "print.template.apply", "Apply Print Template", [], None, "{name} → print.get", always, template_apply),
+ cmd!(query "print.template.delete", "Delete Print Template", [], None, "{name} → print.template.list", always, template_delete),
+ ]
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 21fc30e46..4cce1d8df 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -251,6 +251,11 @@ pub struct Session {
pub last_export: Option<serde_json::Value>,
/// The user's export presets (built-ins: [`export::builtin_presets`]), persisted in prefs.json.
pub export_presets: Vec<export::ExportPreset>,
+ /// The Print module's current layout, image settings, page, guides and job (`print.*`). Lives
+ /// with the session, so the app, CLI, control channel and MCP all see the same print.
+ pub print: print::template::PrintSettings,
+ /// Saved print templates (`print.template.*`), persisted in prefs.json.
+ pub print_templates: Vec<print::template::PrintTemplate>,
/// Metadata presets (`metadata.*`), persisted in prefs.json.
pub metadata_presets: Vec<cmd::metadata::MetadataPreset>,
/// Saved filter-bar settings (`filter.*`), persisted in prefs.json.
@@ -371,6 +376,8 @@ impl Session {
xmp: sidecar::XmpPrefs::default(),
last_export: None,
export_presets: Vec::new(),
+ print: Default::default(),
+ print_templates: Vec::new(),
metadata_presets: Vec::new(),
filter_presets: Vec::new(),
curve_presets: Vec::new(),
@@ -1020,6 +1027,8 @@ mod tests_persist;
#[cfg(test)]
mod tests_prefs;
#[cfg(test)]
+mod tests_print;
+#[cfg(test)]
mod tests_process;
#[cfg(test)]
mod tests_segment;
diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs
index 2bb5511c2..5e4da681e 100644
--- a/crates/engine/src/library.rs
+++ b/crates/engine/src/library.rs
@@ -161,6 +161,8 @@ struct PrefsFile {
last_export: Option<serde_json::Value>,
/// The user's export presets.
export_presets: Vec<crate::export::ExportPreset>,
+ /// Print templates.
+ print_templates: Vec<crate::print::template::PrintTemplate>,
/// Metadata presets.
metadata_presets: Vec<crate::cmd::metadata::MetadataPreset>,
/// Filter presets.
@@ -393,6 +395,7 @@ impl Session {
self.xmp = prefs.xmp;
self.last_export = prefs.last_export;
self.export_presets = prefs.export_presets;
+ self.print_templates = prefs.print_templates;
self.metadata_presets = prefs.metadata_presets;
self.filter_presets = prefs.filter_presets;
self.curve_presets = prefs.curve_presets;
@@ -628,6 +631,7 @@ impl Session {
xmp: self.xmp,
last_export: self.last_export.clone(),
export_presets: self.export_presets.clone(),
+ print_templates: self.print_templates.clone(),
metadata_presets: self.metadata_presets.clone(),
filter_presets: self.filter_presets.clone(),
curve_presets: self.curve_presets.clone(),
diff --git a/crates/engine/src/print/layout.rs b/crates/engine/src/print/layout.rs
index 8a9e1a027..26d1818e5 100644
--- a/crates/engine/src/print/layout.rs
+++ b/crates/engine/src/print/layout.rs
@@ -819,6 +819,23 @@ impl Layout {
Ok(())
}
+ /// Pulls every cell back inside the printable area (shrinking one that is bigger than it), for
+ /// after the paper, orientation or margins changed.
+ pub fn fit_cells(&mut self) -> Result<(), String> {
+ let area = self.printable()?;
+ for c in &mut self.cells {
+ let r = &mut c.rect;
+ if !r.is_finite() {
+ continue;
+ }
+ r.w = r.w.min(area.w);
+ r.h = r.h.min(area.h);
+ r.x = r.x.clamp(area.x, (area.right() - r.w).max(area.x));
+ r.y = r.y.clamp(area.y, (area.bottom() - r.h).max(area.y));
+ }
+ Ok(())
+ }
+
/// Whether two cells on the same page overlap.
pub fn has_overlaps(&self) -> bool {
self.cells.iter().enumerate().any(|(i, a)| self.cells.iter().skip(i + 1).any(|b| a.page == b.page && a.rect.overlaps(&b.rect)))
@@ -1271,6 +1288,21 @@ mod tests {
assert!(l.snap_move(b, Rect::new(0.0, 0.0, 1.0, 1.0), Snap::Grid, f64::NAN, 0.1).is_err());
}
+ #[test]
+ fn fit_cells_follows_the_margins() {
+ let mut l = package();
+ let id = l.add_cell(7.0, 10.0).unwrap();
+ l.page.margins = Margins::uniform(1.0);
+ assert!(l.validate().is_err(), "the cell no longer fits");
+ l.fit_cells().unwrap();
+ l.validate().unwrap();
+ let r = l.cell(id).unwrap().rect;
+ assert!(l.printable().unwrap().contains(&r));
+ assert!((r.w - 6.5).abs() < 1e-9 && (r.h - 9.0).abs() < 1e-9);
+ l.page.paper = "poster".into();
+ assert!(l.fit_cells().is_err());
+ }
+
#[test]
fn cell_aspect_survives_auto_layout() {
let mut l = package();
diff --git a/crates/engine/src/print/template.rs b/crates/engine/src/print/template.rs
index 2fd74ca60..2465c123a 100644
--- a/crates/engine/src/print/template.rs
+++ b/crates/engine/src/print/template.rs
@@ -25,3 +25,100 @@ impl PrintSettings {
self.job.validate()
}
}
+
+/// Longest template name, characters.
+pub const MAX_NAME: usize = 80;
+/// Most templates kept.
+pub const MAX_TEMPLATES: usize = 200;
+
+/// A saved print template: the layout, image settings, page and job of a print, without the
+/// photos assigned to cells and without the guides (a view preference). The settings are kept as
+/// JSON so a template written by another version never makes the preferences file unreadable;
+/// [`PrintTemplate::settings`] checks them when they are used.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PrintTemplate {
+ pub name: String,
+ pub settings: serde_json::Value,
+}
+
+/// A template name: trimmed, 1 to [`MAX_NAME`] characters, no control characters.
+pub fn clean_name(name: &str) -> Result<String, String> {
+ let name = name.trim();
+ if name.is_empty() || name.chars().count() > MAX_NAME || name.chars().any(char::is_control) {
+ return Err(format!("a template name is 1 to {MAX_NAME} characters without control characters"));
+ }
+ Ok(name.to_string())
+}
+
+impl PrintTemplate {
+ /// A template of `settings` (validated first) named `name`.
+ pub fn new(name: &str, settings: &PrintSettings) -> Result<Self, String> {
+ let mut s = settings.clone();
+ s.validate()?;
+ for c in &mut s.layout.cells {
+ c.photo = None;
+ }
+ let mut value = serde_json::to_value(&s).map_err(|e| e.to_string())?;
+ if let Some(o) = value.as_object_mut() {
+ o.remove("guides");
+ }
+ Ok(Self { name: clean_name(name)?, settings: value })
+ }
+
+ /// The settings, checked: unknown fields, hostile numbers and inconsistent layouts are errors.
+ /// `guides` are those of the print the template is applied to.
+ pub fn settings(&self, guides: &Guides) -> Result<PrintSettings, String> {
+ let mut s: PrintSettings = serde_json::from_value(self.settings.clone()).map_err(|e| format!("template `{}`: {e}", self.name))?;
+ s.guides = *guides;
+ s.validate().map_err(|e| format!("template `{}`: {e}", self.name))?;
+ Ok(s)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::print::layout::Style;
+ use serde_json::json;
+
+ #[test]
+ fn a_template_keeps_the_look_not_the_photos_or_guides() {
+ let mut s = PrintSettings::default();
+ s.layout.style = Style::CustomPackage;
+ let id = s.layout.add_cell(3.0, 2.0).unwrap();
+ s.layout.set_cell_photo(id, Some(77)).unwrap();
+ s.image.zoom_to_fill = true;
+ s.page.background = [10, 20, 30];
+ s.job.ppi = 300.0;
+ s.guides.grid_size = 1.0;
+ let t = PrintTemplate::new(" Proof sheet ", &s).unwrap();
+ assert_eq!(t.name, "Proof sheet");
+ assert!(t.settings.get("guides").is_none());
+ let back = t.settings(&Guides::default()).unwrap();
+ assert_eq!(back.layout.cells.len(), 1);
+ assert_eq!(back.layout.cells[0].photo, None);
+ assert!(back.image.zoom_to_fill);
+ assert_eq!((back.page.background, back.job.ppi), ([10, 20, 30], 300.0));
+ assert_eq!(back.guides, Guides::default(), "the guides are the caller's");
+ }
+
+ #[test]
+ fn hostile_templates_are_rejected() {
+ for name in ["", " ", "a\nb", &"x".repeat(MAX_NAME + 1)] {
+ assert!(PrintTemplate::new(name, &PrintSettings::default()).is_err(), "{name:?}");
+ }
+ let bad = |v: serde_json::Value| PrintTemplate { name: "t".into(), settings: v }.settings(&Guides::default()).is_err();
+ assert!(bad(json!("text")));
+ assert!(bad(json!({"surprise": 1})));
+ assert!(bad(json!({"job": {"ppi": 1e30}})));
+ assert!(bad(json!({"layout": {"pages": 0}})));
+ assert!(bad(json!({"layout": {"page": {"paper": "custom", "customWidth": -3}}})));
+ assert!(bad(json!({"layout": {"cells": [{"id": 1, "rect": {"x": 0, "y": 0, "w": 1e9, "h": 1}}]}})));
+ assert!(bad(json!({"image": {"borderWidth": -1}})));
+ assert!(!bad(json!({})));
+ let mut s = PrintSettings::default();
+ s.job.ppi = f32::NAN;
+ assert!(PrintTemplate::new("t", &s).is_err());
+ }
+}
diff --git a/crates/engine/src/tests_print.rs b/crates/engine/src/tests_print.rs
new file mode 100644
index 000000000..261d47d52
--- /dev/null
+++ b/crates/engine/src/tests_print.rs
@@ -0,0 +1,307 @@
+//! The `print.*` commands: state, cells, templates and the PDF.
+
+use lightcraft_catalog::MemStore;
+use serde_json::{Value, json};
+
+use crate::Session;
+use crate::library::LibraryStores;
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+fn fails(s: &mut Session, id: &str, p: Value) -> String {
+ s.execute(id, &p).expect_err(&format!("{id} {p} should fail")).to_string()
+}
+
+fn package(s: &mut Session) {
+ run(s, "print.set", json!({"layout": {"style": "customPackage", "page": {"paper": "letter"}}}));
+}
+
+#[test]
+fn get_set_and_reset() {
+ let mut s = Session::with_demo();
+ let g = run(&mut s, "print.get", json!({}));
+ assert_eq!(g["settings"]["layout"]["style"], "singleImage");
+ assert_eq!(g["pageWidth"], 8.5);
+ assert_eq!(g["printable"]["x"], 0.25);
+ assert_eq!(g["settings"]["job"]["ppi"], 240.0);
+ assert!(g["papers"].as_array().unwrap().iter().any(|p| p["name"] == "a4"));
+ assert_eq!(g["gridCells"].as_array().unwrap().len(), 1);
+
+ let g = run(
+ &mut s,
+ "print.set",
+ json!({"layout": {"style": "contactSheet", "grid": {"columns": 2, "rows": 3}, "page": {"paper": "a4", "orientation": "landscape", "margins": {"left": 1.0}}}, "image": {"zoomToFill": true}, "job": {"ppi": 300.0}}),
+ );
+ assert_eq!(g["settings"]["layout"]["page"]["margins"]["left"], 1.0);
+ assert_eq!(g["settings"]["layout"]["page"]["margins"]["top"], 0.25, "a patch merges");
+ assert_eq!(g["gridCells"].as_array().unwrap().len(), 6);
+ assert!((g["pageWidth"].as_f64().unwrap() - 11.693).abs() < 1e-3);
+ assert_eq!(g["settings"]["image"]["zoomToFill"], true);
+ // the page count follows the photos: 6 cells per page
+ let g = run(&mut s, "print.get", json!({"ids": vec![1; 7]}));
+ assert_eq!(g["pageCount"], 2);
+
+ let g = run(&mut s, "print.reset", json!({}));
+ assert_eq!(g["settings"]["job"]["ppi"], 240.0);
+}
+
+#[test]
+fn bad_settings_are_refused_and_change_nothing() {
+ let mut s = Session::with_demo();
+ let before = run(&mut s, "print.get", json!({}));
+ for p in [
+ json!({"typo": 1}),
+ json!({"layout": {"typo": 1}}),
+ json!({"layout": {"style": "poster"}}),
+ json!({"layout": {"cells": []}}),
+ json!({"layout": {"pages": 3}}),
+ json!({"layout": {"page": {"paper": "poster"}}}),
+ json!({"layout": {"page": {"paper": "custom", "customWidth": -1}}}),
+ json!({"layout": {"page": {"margins": {"top": 1e9}}}}),
+ json!({"layout": {"page": {"margins": {"top": 6.0, "bottom": 5.0}}}}),
+ json!({"layout": {"grid": {"columns": 0}}}),
+ json!({"layout": {"grid": {"columns": 9999}}}),
+ json!({"layout": {"spacing": -1}}),
+ json!({"image": {"borderWidth": 99}}),
+ json!({"image": {"strokeWidthPt": -2}}),
+ json!({"image": {"borderColor": [1, 2]}}),
+ json!({"image": {"zoomToFill": "yes"}}),
+ json!({"guides": {"gridSize": 0}}),
+ json!({"guides": {"units": "furlong"}}),
+ json!({"job": {"ppi": 1e30}}),
+ json!({"job": {"ppi": 10}}),
+ json!({"job": null}),
+ ] {
+ fails(&mut s, "print.set", p);
+ }
+ assert_eq!(run(&mut s, "print.get", json!({})), before);
+ assert!(s.execute("print.set", &json!([1])).is_err());
+}
+
+#[test]
+fn cells_are_commands() {
+ let mut s = Session::with_demo();
+ // grid styles have no cells
+ fails(&mut s, "print.cell.add", json!({"width": 2, "height": 2}));
+ package(&mut s);
+ let a = run(&mut s, "print.cell.add", json!({"width": 3.0, "height": 2.0}))["id"].as_u64().unwrap();
+ let b = run(&mut s, "print.cell.add", json!({"width": 3.0, "height": 2.0, "x": 5.0, "y": 5.0}))["id"].as_u64().unwrap();
+ let g = run(&mut s, "print.get", json!({}));
+ assert_eq!(g["settings"]["layout"]["cells"].as_array().unwrap().len(), 2);
+ assert_eq!(g["overlaps"], false);
+ // move, clamped inside the margins
+ let r = run(&mut s, "print.cell.move", json!({"id": a, "x": 99.0, "y": 0.0}));
+ assert_eq!(r["rect"]["x"], 8.25 - 3.0);
+ assert_eq!(r["rect"]["y"], 0.25);
+ // resize keeps what is not given
+ let r = run(&mut s, "print.cell.resize", json!({"id": b, "width": 4.0}));
+ assert_eq!((r["rect"]["w"].as_f64().unwrap(), r["rect"]["h"].as_f64().unwrap()), (4.0, 2.0));
+ // snapping to the other cell's edge
+ let ra = run(&mut s, "print.get", json!({}))["settings"]["layout"]["cells"][0]["rect"].clone();
+ let left = ra["x"].as_f64().unwrap();
+ let r = run(&mut s, "print.cell.move", json!({"id": b, "x": left - 4.0 - 0.04, "y": 5.0, "snap": true}));
+ assert!((r["rect"]["x"].as_f64().unwrap() - (left - 4.0)).abs() < 1e-9, "{r}");
+ let r = run(&mut s, "print.cell.move", json!({"id": b, "x": left - 4.0 - 0.04, "y": 5.0}));
+ assert!((r["rect"]["x"].as_f64().unwrap() - (left - 4.04)).abs() < 1e-9, "no snap unless asked: {r}");
+ run(&mut s, "print.set", json!({"guides": {"snap": "off"}}));
+ let r = run(&mut s, "print.cell.move", json!({"id": b, "x": left - 4.0 - 0.04, "y": 5.0, "snap": true}));
+ assert!((r["rect"]["x"].as_f64().unwrap() - (left - 4.04)).abs() < 1e-9, "snap off");
+ // stacking
+ let r = run(&mut s, "print.cell.stack", json!({"id": a, "order": "toFront"}));
+ assert_eq!(r["order"], json!([b, a]));
+ fails(&mut s, "print.cell.stack", json!({"id": a, "order": "sideways"}));
+ // photos and pages
+ let photo = s.catalog.photos().next().unwrap().id.0;
+ run(&mut s, "print.cell.photo", json!({"id": a, "photo": photo}));
+ fails(&mut s, "print.cell.photo", json!({"id": a, "photo": 999_999}));
+ run(&mut s, "print.layout.newPage", json!({}));
+ run(&mut s, "print.cell.page", json!({"id": b, "page": 1}));
+ fails(&mut s, "print.cell.page", json!({"id": b, "page": 7}));
+ let g = run(&mut s, "print.get", json!({}));
+ assert_eq!(g["pageCount"], 2);
+ // delete, clear
+ run(&mut s, "print.cell.delete", json!({"id": b}));
+ fails(&mut s, "print.cell.delete", json!({"id": b}));
+ fails(&mut s, "print.cell.move", json!({"id": 99, "x": 0, "y": 0}));
+ fails(&mut s, "print.cell.move", json!({"x": 0, "y": 0}));
+ run(&mut s, "print.layout.clear", json!({}));
+ let g = run(&mut s, "print.get", json!({}));
+ assert_eq!((g["settings"]["layout"]["cells"].as_array().unwrap().len(), g["pageCount"].as_u64()), (0, Some(1)));
+}
+
+#[test]
+fn hostile_cell_numbers_are_refused() {
+ let mut s = Session::with_demo();
+ package(&mut s);
+ for (w, h) in [(0.0, 2.0), (-1.0, 2.0), (1e12, 1e12), (2.0, 1e-9), (50.0, 50.0)] {
+ fails(&mut s, "print.cell.add", json!({"width": w, "height": h}));
+ }
+ fails(&mut s, "print.cell.add", json!({"width": "wide", "height": 2}));
+ fails(&mut s, "print.cell.add", json!({"width": 2}));
+ let id = run(&mut s, "print.cell.add", json!({"width": 2, "height": 2}))["id"].as_u64().unwrap();
+ fails(&mut s, "print.cell.move", json!({"id": id, "x": "left", "y": 0}));
+ fails(&mut s, "print.cell.resize", json!({"id": id, "width": -4}));
+ fails(&mut s, "print.cell.resize", json!({"id": id, "width": "x"}));
+ fails(&mut s, "print.cell.move", json!({"id": id, "x": 1, "y": 1, "snap": "yes"}));
+ fails(&mut s, "print.cell.move", json!({"id": u64::MAX, "x": 1, "y": 1}));
+ let r = run(&mut s, "print.cell.move", json!({"id": id, "x": -1e300, "y": 1e300}));
+ assert_eq!(r["rect"]["x"], 0.25);
+}
+
+#[test]
+fn auto_layout_fills_pages_without_overlap() {
+ let mut s = Session::with_demo();
+ run(&mut s, "print.set", json!({"layout": {"style": "picturePackage"}}));
+ for (w, h) in [(4.0, 6.0), (4.0, 6.0), (5.0, 7.0), (2.5, 3.5), (2.5, 3.5), (2.5, 3.5), (2.5, 3.5), (8.0, 10.0)] {
+ run(&mut s, "print.cell.add", json!({"width": w, "height": h}));
+ }
+ let r = run(&mut s, "print.layout.autoLayout", json!({}));
+ assert!(r["pages"].as_u64().unwrap() >= 2);
+ let g = run(&mut s, "print.get", json!({}));
+ assert_eq!(g["overlaps"], false);
+ let again = run(&mut s, "print.layout.autoLayout", json!({}));
+ assert_eq!(again["cells"], r["cells"], "deterministic");
+ // an oversize cell that arrived by a paper change is pulled in, not left outside the page
+ run(&mut s, "print.set", json!({"layout": {"page": {"paper": "4x6"}}}));
+ let g = run(&mut s, "print.get", json!({}));
+ for c in g["settings"]["layout"]["cells"].as_array().unwrap() {
+ assert!(c["rect"]["x"].as_f64().unwrap() + c["rect"]["w"].as_f64().unwrap() <= 4.0 - 0.25 + 1e-9);
+ }
+}
+
+fn temp_pdf(name: &str) -> String {
+ std::env::temp_dir().join(format!("lightcraft-print-{name}-{}.pdf", std::process::id())).to_string_lossy().to_string()
+}
+
+#[test]
+fn export_pdf_prints_the_current_settings() {
+ let mut s = Session::with_demo();
+ let ids: Vec<u64> = s.catalog.photos().take(3).map(|p| p.id.0).collect();
+ run(
+ &mut s,
+ "print.set",
+ json!({"layout": {"style": "contactSheet", "grid": {"columns": 1, "rows": 2}, "page": {"paper": "a5"}}, "job": {"ppi": 100.0}}),
+ );
+ let path = temp_pdf("export");
+ let r = run(&mut s, "print.exportPdf", json!({"path": path, "ids": ids}));
+ assert_eq!((r["pages"].as_u64(), r["photos"].as_u64()), (Some(2), Some(3)));
+ let bytes = std::fs::read(&path).unwrap();
+ assert_eq!(bytes.len() as u64, r["bytes"].as_u64().unwrap());
+ let text = String::from_utf8_lossy(&bytes);
+ assert!(text.starts_with("%PDF-1.4") && text.contains("/Count 2"));
+ // A5 is 148 x 210 mm = 419.53 x 595.28 pt, rounded to whole pixels at 100 ppi (583 x 827)
+ assert!(text.contains("/MediaBox [0 0 419.76 595.44]"), "{}", &text[..text.len().min(400)]);
+ // the row in the activity stack is gone when the print is done
+ assert!(s.activity.list().is_empty());
+ fails(&mut s, "print.exportPdf", json!({}));
+ fails(&mut s, "print.exportPdf", json!({"path": path, "typo": 1}));
+ fails(&mut s, "print.exportPdf", json!({"path": path, "ids": ["x"]}));
+ fails(&mut s, "print.exportPdf", json!({"path": path, "ids": [999_999]}));
+ // a package with no cells has nothing to print
+ run(&mut s, "print.set", json!({"layout": {"style": "picturePackage"}}));
+ fails(&mut s, "print.exportPdf", json!({"path": path, "ids": ids}));
+}
+
+#[test]
+fn custom_package_prints_each_cells_photo() {
+ let mut s = Session::with_demo();
+ let ids: Vec<u64> = s.catalog.photos().take(2).map(|p| p.id.0).collect();
+ run(&mut s, "print.set", json!({"layout": {"style": "customPackage", "page": {"paper": "4x6"}}, "job": {"ppi": 72.0}}));
+ let a = run(&mut s, "print.cell.add", json!({"width": 3.0, "height": 2.0}))["id"].as_u64().unwrap();
+ let b = run(&mut s, "print.cell.add", json!({"width": 3.0, "height": 2.0}))["id"].as_u64().unwrap();
+ run(&mut s, "print.cell.photo", json!({"id": a, "photo": ids[0]}));
+ run(&mut s, "print.cell.photo", json!({"id": b, "photo": ids[1]}));
+ let r = run(&mut s, "print.exportPdf", json!({"path": temp_pdf("custom"), "ids": [ids[0]]}));
+ assert_eq!(r["pages"], 1);
+}
+
+#[test]
+fn templates_save_apply_delete_and_persist() {
+ let files = MemStore::new();
+ let open = |files: &MemStore| {
+ let mut s = Session::with_demo();
+ let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false };
+ s.open_library_in(stores, false).unwrap();
+ s
+ };
+ let mut s = open(&files);
+ run(
+ &mut s,
+ "print.set",
+ json!({"layout": {"style": "contactSheet", "grid": {"columns": 4, "rows": 5}}, "page": {"background": [10, 20, 30]}, "guides": {"gridSize": 1.0}}),
+ );
+ let r = run(&mut s, "print.template.save", json!({"name": "Proofs"}));
+ assert_eq!(r["templates"][0]["name"], "Proofs");
+ assert!(r["templates"][0]["settings"].get("guides").is_none());
+ run(&mut s, "print.template.save", json!({"name": "proofs"}));
+ assert_eq!(run(&mut s, "print.template.list", json!({}))["templates"].as_array().unwrap().len(), 1, "the same name in another case replaces");
+
+ run(&mut s, "print.reset", json!({}));
+ run(&mut s, "print.set", json!({"guides": {"gridSize": 0.5}}));
+ let g = run(&mut s, "print.template.apply", json!({"name": "PROOFS"}));
+ assert_eq!(g["settings"]["layout"]["grid"]["columns"], 4);
+ assert_eq!(g["settings"]["page"]["background"], json!([10, 20, 30]));
+ assert_eq!(g["settings"]["guides"]["gridSize"], 0.5, "guides stay as they were");
+
+ // it survives reopening the library
+ let mut again = open(&files);
+ assert_eq!(run(&mut again, "print.template.list", json!({}))["templates"][0]["name"], "proofs");
+ run(&mut again, "print.template.apply", json!({"name": "Proofs"}));
+
+ fails(&mut s, "print.template.save", json!({"name": " "}));
+ fails(&mut s, "print.template.save", json!({}));
+ fails(&mut s, "print.template.apply", json!({"name": "Nope"}));
+ fails(&mut s, "print.template.delete", json!({"name": "Nope"}));
+ run(&mut s, "print.template.delete", json!({"name": "proofs"}));
+ assert!(run(&mut s, "print.template.list", json!({}))["templates"].as_array().unwrap().is_empty());
+ assert!(run(&mut open(&files), "print.template.list", json!({}))["templates"].as_array().unwrap().is_empty());
+}
+
+#[test]
+fn a_hostile_template_in_the_preferences_does_not_break_the_library() {
+ let files = MemStore::new();
+ let hostile = json!({"printTemplates": [
+ {"name": "Bad", "settings": {"layout": {"pages": 0}, "extra": true}},
+ {"name": "Huge", "settings": {"job": {"ppi": 1e300}}},
+ {"name": "Fine", "settings": {"layout": {"style": "contactSheet"}}}
+ ], "cacheMb": 123});
+ files.set("prefs.json", serde_json::to_vec(&hostile).unwrap());
+ let mut s = Session::with_demo();
+ let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false };
+ s.open_library_in(stores, false).unwrap();
+ assert!(s.take_library_warnings().is_empty(), "the preferences are not damaged");
+ assert_eq!(s.cache_mb, 123);
+ assert_eq!(run(&mut s, "print.template.list", json!({}))["templates"].as_array().unwrap().len(), 3);
+ fails(&mut s, "print.template.apply", json!({"name": "Bad"}));
+ fails(&mut s, "print.template.apply", json!({"name": "Huge"}));
+ run(&mut s, "print.template.apply", json!({"name": "Fine"}));
+}
+
+#[test]
+fn every_print_command_is_registered_with_a_description() {
+ for id in [
+ "print.get",
+ "print.set",
+ "print.reset",
+ "print.cell.add",
+ "print.cell.move",
+ "print.cell.resize",
+ "print.cell.delete",
+ "print.cell.stack",
+ "print.cell.photo",
+ "print.cell.page",
+ "print.layout.autoLayout",
+ "print.layout.newPage",
+ "print.layout.clear",
+ "print.exportPdf",
+ "print.template.list",
+ "print.template.save",
+ "print.template.apply",
+ "print.template.delete",
+ ] {
+ let c = crate::find_command(id).unwrap_or_else(|| panic!("{id} missing"));
+ assert!(c.params.len() > 3, "{id}");
+ }
+}
diff --git a/docs/gaps.md b/docs/gaps.md
index 4c3a84ef0..72649a5bc 100644
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@ -29,7 +29,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app
| 12 | **Content-aware / generative remove, detect distractions, reflections removal** | REM rows 75%; patch synthesis missing | cleanup work goes back to Photoshop | 25–45 (+ generative model) | [target-app-parity](target-app-parity.md#ai) |
| 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) |
| 14 | **HDR display** (EDR / Windows HDR); HLG; the headroom limit and SDR rendition from `crs` XMP (the HDR switch, `HDREditMode`, is read) | HDR rows 70%; LR-VIEW-HDR-DISPLAY ⬜ | HDR editing works blind on HDR monitors | 12–25 | [hardware-parity](hardware-parity.md) |
-| 15 | **Print module**: custom packages, printer colour management (contact-sheet PDF only) | LRC-PRINT rows | Classic users who print | 25–40 | [target-app-parity](target-app-parity.md#features) |
+| 15 | **Print module**: no Print view (layouts, cells, image settings and templates exist as `print.*` commands only), printer colour management, identity plate / watermark / page numbers / crop marks / photo info, Custom Package Auto Layout | LRC-PRINT rows | Classic users who print | 25–40 | [target-app-parity](target-app-parity.md#features) |
| 16 | **Map view, Book, Slideshow module, publish services** | LRC-MAP / BOOK / SS rows ⬜ | Classic users; publish services matter for Flickr / SmugMug workflows | 60–100 | [target-app-parity](target-app-parity.md#features) |
| 17 | **Tethered capture** | ⬜ | studio photographers | 25–45 + cameras | [hardware-parity](hardware-parity.md) |
| 18 | **Video**: playback, trim, global edits, export | VID rows 0% | users who mix stills and clips | 25–45 | [target-app-parity](target-app-parity.md#features) |
@@ -72,6 +72,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w
| Date | Change | Summary |
|---|---|---|
+| 2026-10-12 | minor | Gap 15: the Print module's layout styles, cells, image settings, templates and PDF are `print.*` commands (CLI, control, MCP); the Print view, printer colour management and page overlays remain |
| 2026-10-12 | minor | Gap 15: print pages compose in the engine (fit / Zoom to Fill, Rotate to Fit, border, stroke, background) with an interim PDF writer; commands and UI still to land |
| 2026-10-12 | minor | Gap 15: the Print layout model (paper sizes, margins, grid, package cells, Auto Layout packer, snapping) is in the engine; commands, composition and UI still to land |
| 2026-10-11 | minor | Reviewed against main after 0.6.0: CR3 entry names the CRX variants `crx.rs` still refuses and the R7 / R6 Mark II C-RAW state (decoding, not verified, so the measured numbers don't move); CI and Windows / Linux entries note the riscv64 release build (#844); R7 fix added to Closed recently. Panel docking (UI.9, #869) closes no listed gap |
diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md
index e984542c8..75dc988ae 100644
--- a/docs/parity-checklist.md
+++ b/docs/parity-checklist.md
@@ -1,6 +1,6 @@
# Lightroom parity checklist
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (LRC-PRINT-IMAGESETTINGS: print page composition (fit / Zoom to Fill, Rotate to Fit, border, stroke, background); LRC-PRINT-LAYOUT: print layout model; rapid slider entry; LR-PROF-CAMERACOLOR: tone curve from black-and-white camera JPEGs; LR-VIEW-ZOOM, LR-VIEW-COMPARE: Compare and Reference zoom windows; LR-IMP-FORMATS, LR-IMP-CAMERA-COVERAGE: EOS R5 Mark II CR3 decodes; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md; filesystem history retry/Undo/Redo evidence; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (LRC-PRINT-LAYOUTSTYLE, LRC-PRINT-CELLS, LRC-PRINT-TEMPLATES and the other print rows: `print.*` commands; LRC-PRINT-IMAGESETTINGS: print page composition (fit / Zoom to Fill, Rotate to Fit, border, stroke, background); LRC-PRINT-LAYOUT: print layout model; rapid slider entry; LR-PROF-CAMERACOLOR: tone curve from black-and-white camera JPEGs; LR-VIEW-ZOOM, LR-VIEW-COMPARE: Compare and Reference zoom windows; LR-IMP-FORMATS, LR-IMP-CAMERA-COVERAGE: EOS R5 Mark II CR3 decodes; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md; filesystem history retry/Undo/Redo evidence; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we
have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good
@@ -52,10 +52,10 @@ cited here still exists. Formerly docs/parity.md.
| X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) |
| Y. Menus | 84 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) |
| Z. Keyboard shortcuts (desktop) | 76 | 3 | 3 | 1 | 49/52 (94%) | 23/24 (96%) |
-| Lightroom Classic extras | 34 | 16 | 35 | 8 | — | 24/26 (92%) |
-| **Total** | 407 | 50 | 73 | 35 | 192/200 (96%) | 145/157 (92%) |
+| Lightroom Classic extras | 34 | 19 | 32 | 8 | — | 24/26 (92%) |
+| **Total** | 408 | 54 | 69 | 35 | 193/201 (96%) | 145/157 (92%) |
-Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **81.5%** of 530 in-scope rows — P0 98.0% of 200 · P1 95.2% of 157 · P2 49.7% of 172.
+Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **81.9%** of 531 in-scope rows — P0 98.0% of 201 · P1 95.2% of 157 · P2 50.9% of 172.
<!-- /parity:summary -->
## Top gaps and shortcut notes
@@ -747,14 +747,14 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-
| LRC-SS-MUSIC | Slideshow music | P2 | ⬜ | | |
| LRC-SS-PLAYBACK | Slideshow playback | P2 | ⬜ | | |
| LRC-SS-EXPORT | Slideshow export | P2 | ⬜ | | |
-| LRC-PRINT-LAYOUTSTYLE | Print layout styles | P2 | 🟡 | `cmd:dialog.contactSheet`, `cmd:export.contactSheet`, `crates/engine/src/contact_sheet.rs` | paginated contact sheets; single-image/custom package layouts missing |
-| LRC-PRINT-IMAGESETTINGS | Print image settings | P2 | ⬜ | `crates/engine/src/print/compose.rs` | Zoom to Fill, Rotate to Fit, Photo Border (package styles), Inner Stroke and page background compose in the engine (16-bit Rec. 2020 pages, tested on pixels); no command or UI yet |
-| LRC-PRINT-LAYOUT | Print layout | P2 | 🟡 | `cmd:export.contactSheet`, `crates/ui-egui/src/panels/dialogs.rs`, `crates/engine/src/print/layout.rs` | A4/Letter, portrait/landscape, 1–8 columns and 1–10 rows; fixed margins and spacing. The new layout model (ten paper sizes + custom, orientation, margins, grid with spacing and square cells, package cells with Auto Layout packing) is in the engine but not yet reachable from a command or the UI |
-| LRC-PRINT-GUIDES | Print guides | P2 | ⬜ | | |
-| LRC-PRINT-CELLS | Picture-package cells | P2 | ⬜ | `crates/engine/src/print/layout.rs` | cell model, deterministic packer, stacking order and snapping exist in the engine; no command or UI yet |
-| LRC-PRINT-PAGE | Print page options | P2 | 🟡 | `cmd:export.contactSheet`, `crates/engine/src/contact_sheet.rs`, `crates/engine/src/print/compose.rs` | optional filename captions; page background colour composes in the engine (no command or UI yet); no identity plates |
+| LRC-PRINT-LAYOUTSTYLE | Print layout styles | P2 | 🟡 | `cmd:print.set`, `cmd:print.get`, `cmd:print.exportPdf`, `cmd:export.contactSheet`, `crates/engine/src/print/layout.rs` | Single Image, Contact Sheet, Picture Package and Custom Package are print layout styles reachable from commands, the CLI, control channel and MCP; no Print module UI yet (File → Contact Sheet PDF still the only dialog) |
+| LRC-PRINT-IMAGESETTINGS | Print image settings | P2 | 🟡 | `cmd:print.set`, `crates/engine/src/print/compose.rs` | Zoom to Fill, Rotate to Fit, Photo Border (package styles), Inner Stroke (width in points, colour) through `print.set {image}`; pixel-tested; no panel yet |
+| LRC-PRINT-LAYOUT | Print layout | P2 | 🟡 | `cmd:print.set`, `cmd:print.layout.autoLayout`, `cmd:print.layout.newPage`, `cmd:print.layout.clear`, `cmd:export.contactSheet`, `crates/engine/src/print/layout.rs` | A3/A4/A5/Letter/Legal/Tabloid/4x6/5x7/8x10/13x19 and custom paper, portrait/landscape, per-side margins, grid with column/row spacing and square cells, 72–720 ppi; commands only, no panel yet |
+| LRC-PRINT-GUIDES | Print guides | P2 | ⬜ | `cmd:print.set` | guide options (ruler units in/cm/mm/pt, snap off/cells/grid, grid size, show margins/bleed/page grid/cells/dimensions) are stored and used by snapping in `print.cell.move`/`resize`; nothing is drawn until the Print UI lands |
+| LRC-PRINT-CELLS | Picture-package cells | P2 | 🟡 | `cmd:print.cell.add`, `cmd:print.cell.move`, `cmd:print.cell.resize`, `cmd:print.cell.delete`, `cmd:print.cell.stack`, `cmd:print.cell.photo`, `cmd:print.cell.page`, `cmd:print.layout.autoLayout` | add/move/resize/delete cells of any size, stacking order, per-cell photos (Custom Package), deterministic Auto Layout packer, snapping to cells or grid; no UI (drag placement) yet |
+| LRC-PRINT-PAGE | Print page options | P2 | 🟡 | `cmd:print.set`, `cmd:export.contactSheet`, `crates/engine/src/contact_sheet.rs` | page background colour and margins through `print.set`; optional filename captions in the contact-sheet PDF; no identity plates, watermarks, page numbers or crop marks |
| LRC-PRINT-JOB | Print job & colour management | P2 | 🟡 | `cmd:export.contactSheet`, `cmd:app.contactSheet`, `crates/ui-egui/src/export_task.rs` | PDF export at fixed 150 dpi in sRGB, current edits, background progress/cancel and original protection; no native printer integration, ICC soft proof/print profiles or selectable resolution |
-| LRC-PRINT-TEMPLATES | Print templates | P2 | ⬜ | | |
+| LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete` | named templates of layout, image settings, page and job saved with the library (prefs.json); no built-in templates, no UI, no template import/export |
| LRC-WEB-LAYOUT | Web gallery layouts | OOS | 🚫 | | |
| LRC-WEB-SITEINFO | Web gallery site info | OOS | 🚫 | | |
| LRC-WEB-COLOR | Web gallery colours | OOS | 🚫 | | |
@@ -787,6 +787,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| Date | Change | Summary |
|---|---|---|
+| 2026-10-12 | minor | LRC-PRINT-LAYOUTSTYLE, LRC-PRINT-IMAGESETTINGS, LRC-PRINT-LAYOUT, LRC-PRINT-CELLS, LRC-PRINT-PAGE, LRC-PRINT-TEMPLATES: the Print module is reachable as 18 `print.*` commands (settings, cells, Auto Layout, PDF, templates saved in prefs.json) from the CLI, control channel and MCP; 🟡 until the Print UI lands, LRC-PRINT-GUIDES stays ⬜ |
| 2026-10-12 | minor | LRC-PRINT-IMAGESETTINGS: `print/compose.rs` composes pages (Zoom to Fill, Rotate to Fit, Photo Border, Inner Stroke, background) from the layout model into 16-bit Rec. 2020 `PageRaster`s, with an interim sRGB PDF writer in `print/output.rs`; rows stay until commands and UI reach them |
| 2026-10-12 | minor | LRC-PRINT-LAYOUT: the Print layout model (paper, margins, grid, package cells, Auto Layout packer, snapping) lands in `print/layout.rs`; no row changes status until commands and UI follow |
| 2026-10-11 | minor | KEY-SLIDER-TYPE: honor immediate Return/Escape and keep typed keys in the value editor; add regression references |