Skip to content

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

Merge PR #2890: Export: note when LZW is picked for TIFF, 16-bit ZIP size test (#2882)

aiongg1765d19c2022
diff --cc crates/engine/src/export/tests.rs
index 139939a1d,000000000..b8482a7df
mode 100644,000000..100644
--- a/crates/engine/src/export/tests.rs
+++ b/crates/engine/src/export/tests.rs
@@@ -1,1480 -1,0 +1,1525 @@@
+use super::*;
+use serde_json::json;
+
+fn test_image() -> Rgba8 {
+ let mut img = Rgba8::new(96, 64);
+ for (i, p) in img.data.iter_mut().enumerate() {
+ let (x, y) = (i % 96, i / 96);
+ *p = [(x * 2) as u8, (y * 3) as u8, ((x * y) % 255) as u8, 255];
+ }
+ img
+}
+
+/// Issue #1670: removing a redundant alpha channel preserves samples and metadata.
+#[test]
+fn opaque_eight_bit_exports_are_rgb() {
+ let img = test_image();
+ let metadata = Metadata { copyright: Some("Synthetic export test".into()), ..Default::default() };
+ for format in [ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp] {
+ for compression in [TiffCompression::None, TiffCompression::Lzw, TiffCompression::Deflate, TiffCompression::PackBits] {
+ let options = ExportOptions { format, tiff_compression: compression, ..Default::default() };
+ let bytes = encode_with_metadata(&img, &options, Some(&metadata)).unwrap();
+ let decoded = lightcraft_codecs::decode(&bytes, Default::default()).unwrap();
+ assert!(!decoded.has_alpha, "{format:?}/{compression:?} must be RGB");
+ assert_eq!((decoded.width, decoded.height, decoded.bit_depth), (96, 64, 8));
+ assert_eq!(decoded.to_srgb8().data, img.data, "{format:?}/{compression:?} pixels");
+ assert_eq!(decoded.icc.as_deref(), Some(icc::write_named(NamedSpace::Srgb).as_slice()));
+ assert!(decoded.xmp.as_deref().unwrap_or_default().contains("Synthetic export test"));
+ if format == ExportFormat::Png {
+ assert_eq!(bytes[25], 2, "PNG IHDR declares RGB");
+ }
+ if format != ExportFormat::Tiff {
+ break;
+ }
+ }
+ }
+}
+
+#[test]
+fn eight_bit_exports_preserve_real_alpha() {
+ let mut img = test_image();
+ img.data[0][3] = 128;
+ for format in [ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp] {
+ let bytes = encode_image(&img, &ExportOptions { format, ..Default::default() }).unwrap();
+ let decoded = lightcraft_codecs::decode(&bytes, Default::default()).unwrap();
+ assert!(decoded.has_alpha, "{format:?} must retain real alpha");
+ assert_eq!(decoded.to_srgb8().data, img.data, "{format:?} samples");
+ }
+}
+
+#[test]
+fn formats_have_magic() {
+ let img = test_image();
+ for (f, magic) in
+ [(ExportFormat::Jpeg, &b"\xFF\xD8"[..]), (ExportFormat::Png, b"\x89PNG"), (ExportFormat::Tiff, b"II"), (ExportFormat::Webp, b"RIFF")]
+ {
+ let b = encode_image(&img, &ExportOptions { format: f, ..Default::default() }).unwrap();
+ assert!(b.starts_with(magic), "{f:?}");
+ }
+}
+
+#[test]
+fn size_limit_respected() {
+ let img = test_image();
+ let full = encode_image(&img, &ExportOptions { quality: 100, ..Default::default() }).unwrap();
+ let kb = (full.len() / 1024 / 2).max(2) as u32;
+ let b = encode_image(&img, &ExportOptions { quality: 100, limit_kb: Some(kb), ..Default::default() }).unwrap();
+ assert!(b.len() <= kb as usize * 1024);
+}
+
+#[test]
+fn hdr_jpeg_size_limit_respected() {
+ let img = Rgba8::from_fn(256, 192, |x, y| {
+ let n = (x as u32).wrapping_mul(73856093) ^ (y as u32).wrapping_mul(19349663);
+ [n as u8, (n >> 8) as u8, (n >> 16) as u8, 255]
+ });
+ let hdr = DeepImage {
+ width: img.width,
+ height: img.height,
+ space: OutputSpace::Srgb,
+ samples: DeepSamples::F32(img.data.iter().flat_map(|p| p[..3].iter().map(|v| lightcraft_color::transfer::decode_srgb8(*v) * 4.0)).collect()),
+ };
+ let opts = ExportOptions { hdr: true, quality: 100, limit_kb: Some(u32::MAX), ..Default::default() };
+ let full = encode_gain_map_jpeg(&img, &hdr, &opts, None).unwrap();
+ let kb = (full.len() / 2048) as u32;
+ let limited = encode_gain_map_jpeg(&img, &hdr, &ExportOptions { limit_kb: Some(kb), ..opts.clone() }, None).unwrap();
+ assert!(limited.len() <= kb as usize * 1024, "{} bytes exceeds {kb} KB", limited.len());
+ let decoded = lightcraft_codecs::gainmap::read_jpeg(&limited).unwrap();
+ assert!(decoded.meta.alternate_headroom > 1.0, "the gain map must survive size limiting");
+ let impossible = encode_gain_map_jpeg(&img, &hdr, &ExportOptions { limit_kb: Some(1), ..opts }, None);
+ assert!(impossible.is_err_and(|e| e.contains("cannot fit within 1 KB")));
+}
+
+#[test]
+fn graphic_watermark_honours_exif_orientation() {
+ let dir = std::env::temp_dir().join(format!("lc-wm-orientation-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let logo = Rgba8::from_fn(40, 20, |x, _| if x < 20 { [255, 0, 0, 255] } else { [0, 0, 255, 255] });
+ for orientation in [2, 6] {
+ let meta = Metadata { orientation: Some(lightcraft_geom::Orientation::from_exif(orientation)), ..Default::default() };
+ let exif = lightcraft_meta::write_exif(&meta);
+ let bytes = lightcraft_codecs::encode_jpeg(
+ &EncodeImage::rgba8(&logo),
+ 100,
+ ChromaSubsampling::S444,
+ &EncodeMeta { exif: Some(&exif), ..Default::default() },
+ )
+ .unwrap();
+ let path = dir.join(format!("oriented-{orientation}.jpg"));
+ std::fs::write(&path, bytes).unwrap();
+ let wm = Watermark {
+ image: path.to_string_lossy().into(),
+ image_width: if orientation == 6 { 0.25 } else { 0.5 },
+ opacity: 1.0,
+ inset_x: 0.0,
+ inset_y: 0.0,
+ ..Default::default()
+ };
+ let mut img = Rgba8::from_fn(80, 80, |_, _| [0, 0, 0, 255]);
+ draw_watermark(&mut img, &wm);
+ if orientation == 6 {
+ assert!(img.get(70, 45)[0] > 240 && img.get(70, 75)[2] > 240, "EXIF 6: red above blue");
+ } else {
+ assert!(img.get(45, 70)[2] > 240 && img.get(75, 70)[0] > 240, "EXIF 2: blue left of red");
+ }
+ }
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[test]
+fn graphic_watermark_keeps_aspect_when_fitted_and_rotated() {
+ let dir = std::env::temp_dir().join(format!("lc-wm-aspect-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("tall.png");
+ let logo = Rgba8::from_fn(40, 160, |_, _| [255, 0, 0, 255]);
+ std::fs::write(&path, lightcraft_codecs::encode_png(&EncodeImage::rgba8(&logo), &EncodeMeta::default()).unwrap()).unwrap();
+ for (rotation, expected) in [(0, (20, 80)), (90, (120, 30)), (180, (20, 80)), (270, (120, 30))] {
+ let wm = Watermark {
+ image: path.to_string_lossy().into(),
+ image_width: 0.5,
+ opacity: 1.0,
+ inset_x: 0.0,
+ inset_y: 0.0,
+ rotation,
+ ..Default::default()
+ };
+ let mut img = Rgba8::from_fn(120, 80, |_, _| [0, 0, 0, 255]);
+ draw_watermark(&mut img, &wm);
+ let lit: Vec<_> = img.data.iter().enumerate().filter(|(_, p)| p[0] > 200).map(|(i, _)| (i % 120, i / 120)).collect();
+ let bounds = (
+ lit.iter().map(|p| p.0).max().unwrap() - lit.iter().map(|p| p.0).min().unwrap() + 1,
+ lit.iter().map(|p| p.1).max().unwrap() - lit.iter().map(|p| p.1).min().unwrap() + 1,
+ );
+ assert_eq!(bounds, expected, "{rotation} degrees: fitting must preserve the logo's aspect ratio");
+ }
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[test]
+fn graphic_watermark_fit_preserves_anchor_insets() {
+ let dir = std::env::temp_dir().join(format!("lc-wm-insets-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("tall.png");
+ let logo = Rgba8::from_fn(40, 160, |_, _| [255, 0, 0, 255]);
+ std::fs::write(&path, lightcraft_codecs::encode_png(&EncodeImage::rgba8(&logo), &EncodeMeta::default()).unwrap()).unwrap();
+ use Anchor::*;
+ for (anchor, rotation, expected) in [
+ (BottomRight, 90, (0, 44, 111, 71)),
+ (TopLeft, 270, (8, 8, 119, 35)),
+ (Right, 90, (0, 26, 111, 53)),
+ (BottomRight, 0, (94, 0, 111, 71)),
+ (TopLeft, 180, (8, 8, 25, 79)),
+ (Bottom, 0, (51, 0, 68, 71)),
+ // Centered axes ignore their inset rather than shrinking the image unnecessarily.
+ (Center, 90, (0, 25, 119, 54)),
+ (Top, 90, (0, 8, 119, 37)),
+ ] {
+ let wm = Watermark {
+ image: path.to_string_lossy().into(),
+ image_width: 0.5,
+ opacity: 1.0,
+ inset_x: 0.1,
+ inset_y: 0.1,
+ rotation,
+ anchor,
+ ..Default::default()
+ };
+ let mut img = Rgba8::from_fn(120, 80, |_, _| [0, 0, 0, 255]);
+ draw_watermark(&mut img, &wm);
+ let lit: Vec<_> = img.data.iter().enumerate().filter(|(_, p)| p[0] > 200).map(|(i, _)| (i % 120, i / 120)).collect();
+ let bounds = (
+ lit.iter().map(|p| p.0).min().unwrap(),
+ lit.iter().map(|p| p.1).min().unwrap(),
+ lit.iter().map(|p| p.0).max().unwrap(),
+ lit.iter().map(|p| p.1).max().unwrap(),
+ );
+ assert_eq!(bounds, expected, "{anchor:?}, {rotation} degrees");
+ }
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[test]
+fn sharpen_increases_edge_contrast() {
+ let mut img = Rgba8::new(8, 8);
+ for (i, p) in img.data.iter_mut().enumerate() {
+ let v = if i % 8 < 4 { 80 } else { 170 };
+ *p = [v, v, v, 255];
+ }
+ output_sharpen(&mut img, SharpenFor::Matte, SharpenAmount::High);
+ assert!(img.data[3][0] < 80 && img.data[4][0] > 170);
+}
+
+/// Output sharpening's pixels for every target and amount, pinned (its box blurs run row-parallel, which must not
+/// change a bit), on 8- and 16-bit images; with no target the image is left as it is.
+#[test]
+fn sharpened_pixels_are_pinned() {
+ let fnv = |b: &[u8]| b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3));
+ let mut got = Vec::new();
+ for target in [SharpenFor::Screen, SharpenFor::Matte, SharpenFor::Glossy] {
+ for amount in [SharpenAmount::Low, SharpenAmount::High] {
+ let mut img = test_image();
+ output_sharpen(&mut img, target, amount);
+ got.push(fnv(img.data.as_flattened()));
+ }
+ let src = test_image();
+ let samples = src.data.iter().flat_map(|p| [p[0], p[1], p[2]].map(|v| u16::from(v) * 257)).collect();
+ let mut deep = DeepImage { width: src.width, height: src.height, samples: DeepSamples::U16(samples), space: OutputSpace::Srgb };
+ output_sharpen_deep(&mut deep, target, SharpenAmount::Standard);
+ let DeepSamples::U16(v) = &deep.samples else { unreachable!() };
+ got.push(fnv(&v.iter().flat_map(|s| s.to_le_bytes()).collect::<Vec<u8>>()));
+ }
+ assert_eq!(got, SHARPENED, "{got:#x?}");
+ let mut img = test_image();
+ output_sharpen(&mut img, SharpenFor::None, SharpenAmount::High);
+ assert_eq!(img, test_image());
+}
+const SHARPENED: [u64; 9] = [
+ 0x1494_273e_0bdc_a61c,
+ 0x3fbb_40c4_74f4_b0c3,
+ 0xa27f_8ff5_82a0_99f9,
+ 0x6550_6571_a38d_4d9f,
+ 0x5e28_f4f3_fc8a_9685,
+ 0xdc2b_6f65_9138_3b1d,
+ 0x8ce6_f0b8_d8ed_8026,
+ 0x92d8_12e7_4b2e_81fe,
+ 0x139f_6d78_b1f2_a910,
+];
+
+/// Exported files carry keywords as Lightroom Classic writes them: names flat in `dc:subject`
+/// (with the keywords containing them), full paths in `lr:hierarchicalSubject`, and nothing of
+/// a keyword left out of export. They used to carry the `a|b` paths in `dc:subject`.
+#[test]
+fn exported_keywords_follow_their_options() {
+ use lightcraft_catalog::{Catalog, Op, Photo, PhotoId, Source, keywords::KeywordInfo};
+ let mut c = Catalog::new();
+ c.apply(Op::SetKeyword { path: "Places".into(), info: Some(KeywordInfo { include_on_export: false, ..KeywordInfo::default() }) }).unwrap();
+ c.apply(Op::SetKeyword { path: "draft".into(), info: Some(KeywordInfo { include_on_export: false, ..KeywordInfo::default() }) }).unwrap();
+ let mut p = Photo::new(PhotoId(1), Source::Demo { scene: 0 }, "a.jpg", "jpeg", 10, 10, "2026-09-30T00:00:00");
+ p.meta.keywords = vec!["Places|Lisbon".into(), "travel|Italy".into(), "draft".into()];
+ let m = export_metadata(&p, &c, &ExportOptions::default()).unwrap();
+ assert_eq!(m.keywords, ["Lisbon", "Italy", "travel"]);
+ assert_eq!(m.hierarchical_keywords, ["Places|Lisbon", "travel|Italy"]);
+ let jpg = encode_with_metadata(&test_image(), &ExportOptions::default(), Some(&m)).unwrap();
+ let back = lightcraft_meta::extract(&jpg);
+ assert_eq!((back.keywords, back.hierarchical_keywords), (m.keywords.clone(), m.hierarchical_keywords.clone()));
+}
+
+#[test]
+fn metadata_policies() {
+ use lightcraft_catalog::{Catalog, Photo, PhotoId, Source};
+ let mut p = Photo::new(PhotoId(1), Source::Demo { scene: 0 }, "a.jpg", "jpeg", 10, 10, "2026-09-30T00:00:00");
+ p.meta.camera = "Synthetic X2".into();
+ p.meta.copyright = "(c) Me".into();
+ p.meta.copyright_status = lightcraft_catalog::CopyrightStatus::Copyrighted;
+ p.meta.usage_terms = "Editorial use only".into();
+ p.meta.copyright_url = "https://example.com/rights".into();
+ p.meta.shutter = "1/250".into();
+ p.meta.gps = Some((43.0, -110.0));
+ let all = export_metadata(&p, &Catalog::new(), &ExportOptions::default()).unwrap();
+ assert_eq!(all.model.as_deref(), Some("Synthetic X2"));
+ assert!((all.exposure_time.unwrap() - 0.004).abs() < 1e-9);
+ assert!(all.gps.is_some());
+ let o = ExportOptions { metadata: MetadataPolicy::AllExceptCamera, remove_location: true, ..Default::default() };
+ let m = export_metadata(&p, &Catalog::new(), &o).unwrap();
+ assert!(m.model.is_none() && m.gps.is_none() && m.copyright.is_some());
+ let c = export_metadata(&p, &Catalog::new(), &ExportOptions { metadata: MetadataPolicy::Copyright, ..Default::default() }).unwrap();
+ assert!(c.model.is_none() && c.gps.is_none() && c.copyright.as_deref() == Some("(c) Me"));
+ // "copyright only" keeps all the copyright info: status, usage terms, info URL
+ assert_eq!(
+ (c.copyright_marked, c.usage_terms.as_deref(), c.copyright_url.as_deref()),
+ (Some(true), Some("Editorial use only"), Some("https://example.com/rights"))
+ );
+ assert!(export_metadata(&p, &Catalog::new(), &ExportOptions { metadata: MetadataPolicy::None, ..Default::default() }).is_none());
+ // embedded and readable back from the JPEG
+ let jpg = encode_with_metadata(&test_image(), &ExportOptions::default(), Some(&all)).unwrap();
+ let back = lightcraft_meta::extract(&jpg);
+ assert_eq!(back.model.as_deref(), Some("Synthetic X2"));
+ assert_eq!(back.copyright.as_deref(), Some("(c) Me"));
+ assert_eq!((back.copyright_marked, back.usage_terms.as_deref()), (Some(true), Some("Editorial use only")));
+ assert_eq!(back.copyright_url.as_deref(), Some("https://example.com/rights"));
+ assert!(back.gps.is_some());
+}
+
+#[test]
+fn watermark_draws_in_the_anchored_corner_only() {
+ let mut img = Rgba8::new(400, 300);
+ for p in img.data.iter_mut() {
+ *p = [0, 0, 0, 255];
+ }
+ let o = ExportOptions::from_json(&serde_json::json!({"watermark": {"text": "LightCraft", "size": 0.08, "opacity": 1.0, "shadow": false}}));
+ let wm = o.watermark.clone().unwrap();
+ draw_watermark(&mut img, &wm);
+ let lit = |x0: usize, x1: usize, y0: usize, y1: usize| {
+ (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|&(x, y)| img.get(x, y)[0] > 128).count()
+ };
+ assert!(lit(200, 400, 225, 300) > 100, "bottom-right has text");
+ assert!(lit(0, 200, 0, 150) == 0, "top-left untouched");
+ // string shorthand
+ assert_eq!(ExportOptions::from_json(&serde_json::json!({"watermark": "© Me"})).watermark.unwrap().text, "© Me");
+ assert!(ExportOptions::from_json(&serde_json::json!({"watermark": ""})).watermark.is_none());
+}
+
+/// Horizontal and vertical margins move a text watermark separately; settings saved with one
+/// `inset` (before the two margins) read as both, and either new key overrides it.
+#[test]
+fn watermark_insets_are_horizontal_and_vertical() {
+ // gaps between the drawn text and the right and bottom edges of a 400 × 300 image
+ let gaps = |wm: &Watermark| {
+ let mut img = Rgba8::new(400, 300);
+ draw_watermark(&mut img, wm);
+ let lit: Vec<(usize, usize)> = (0..300).flat_map(|y| (0..400).map(move |x| (x, y))).filter(|&(x, y)| img.get(x, y)[0] > 128).collect();
+ let right = lit.iter().map(|p| p.0).max().unwrap();
+ let bottom = lit.iter().map(|p| p.1).max().unwrap();
+ (399 - right as i64, 299 - bottom as i64)
+ };
+ let base = Watermark { text: "LC".into(), size: 0.1, opacity: 1.0, shadow: false, inset_x: 0.0, inset_y: 0.0, ..Default::default() };
+ let (r0, b0) = gaps(&base);
+ // 0.2 and 0.1 of the 300 px short edge
+ let (r1, b1) = gaps(&Watermark { inset_x: 0.2, ..base.clone() });
+ assert!((r1 - r0 - 60).abs() <= 1 && (b1 - b0).abs() <= 1, "horizontal: {r0},{b0} → {r1},{b1}");
+ let (r2, b2) = gaps(&Watermark { inset_y: 0.1, ..base.clone() });
+ assert!((r2 - r0).abs() <= 1 && (b2 - b0 - 30).abs() <= 1, "vertical: {r0},{b0} → {r2},{b2}");
+ // the old single margin
+ let wm = |w: serde_json::Value| ExportOptions::from_json(&json!({"watermark": w})).watermark.unwrap();
+ let old = wm(json!({"text": "LC", "inset": 0.1}));
+ assert_eq!((old.inset_x, old.inset_y), (0.1, 0.1));
+ let mixed = wm(json!({"text": "LC", "inset": 0.1, "insetY": 0.3}));
+ assert_eq!((mixed.inset_x, mixed.inset_y), (0.1, 0.3));
+ assert!(ExportOptions::from_params(&json!({"watermark": {"text": "LC", "inset": 0.1}})).is_ok());
+ // saved and read back as the two margins
+ let o = ExportOptions { watermark: Some(Watermark { inset_x: 0.05, inset_y: 0.15, ..base }), ..Default::default() };
+ let saved = o.to_json();
+ assert!(saved["watermark"].get("inset").is_none(), "{saved}");
+ assert_eq!(ExportOptions::from_json(&saved).watermark.map(|w| (w.inset_x, w.inset_y)), Some((0.05, 0.15)));
+}
+
+/// A turned text watermark is placed by its turned box: taller than wide at 90° and 270°, the
+/// same corner and insets, and an unknown angle draws it unturned.
+#[test]
+fn watermark_rotation_turns_the_text_in_its_corner() {
+ let lit = |wm: &Watermark| {
+ let mut img = Rgba8::new(400, 300);
+ draw_watermark(&mut img, wm);
+ let on: Vec<(usize, usize)> = (0..300).flat_map(|y| (0..400).map(move |x| (x, y))).filter(|&(x, y)| img.get(x, y)[0] > 128).collect();
+ let (x0, x1) = (on.iter().map(|p| p.0).min().unwrap(), on.iter().map(|p| p.0).max().unwrap());
+ let (y0, y1) = (on.iter().map(|p| p.1).min().unwrap(), on.iter().map(|p| p.1).max().unwrap());
+ (x0, x1, y0, y1, img)
+ };
+ let base = Watermark { text: "LightCraft".into(), size: 0.08, opacity: 1.0, shadow: false, inset_x: 0.0, inset_y: 0.0, ..Default::default() };
+ let (a0, a1, b0, b1, flat) = lit(&base);
+ assert!(a1 - a0 > 2 * (b1 - b0), "unturned text is wide");
+ for rotation in [90, 270] {
+ let (x0, x1, y0, y1, _) = lit(&Watermark { rotation, ..base.clone() });
+ assert!(y1 - y0 > 2 * (x1 - x0), "{rotation}°: tall");
+ assert!(x1 >= 390 && y1 >= 290, "{rotation}°: still in the bottom-right corner ({x1}, {y1})");
+ // 0.1 × 300 px further from the right edge
+ let (_, moved, ..) = lit(&Watermark { rotation, inset_x: 0.1, ..base.clone() });
+ assert!((x1 as i64 - moved as i64 - 30).abs() <= 1, "{rotation}°: {x1} → {moved}");
+ }
+ let (x0, x1, y0, y1, _) = lit(&Watermark { rotation: 180, ..base.clone() });
+ assert!(((x1 - x0) as i64 - (a1 - a0) as i64).abs() <= 2 && ((y1 - y0) as i64 - (b1 - b0) as i64).abs() <= 2, "180°: same size");
+ assert!(x1 >= 390 && y1 >= 290, "180°: same corner");
+ let (.., odd) = lit(&Watermark { rotation: 45, ..base.clone() });
+ assert_eq!(odd.data, flat.data, "an angle that isn't a quarter turn draws unturned");
+ // saved and read back; older settings have none
+ let o = ExportOptions { watermark: Some(Watermark { rotation: 270, ..base }), ..Default::default() };
+ assert_eq!(ExportOptions::from_json(&o.to_json()).watermark.map(|w| w.rotation), Some(270));
+ assert_eq!(ExportOptions::from_json(&json!({"watermark": {"text": "x"}})).watermark.map(|w| w.rotation), Some(0));
+}
+
+/// A preview keeps the export's 6 px minimum text size as a share of the photo: a watermark
+/// clamped to 6 px in a 150 px export covers the same share of a 600 px preview.
+#[test]
+fn watermark_preview_scales_the_minimum_text_size() {
+ let wm = Watermark { text: "LightCraft".into(), size: 0.01, opacity: 1.0, shadow: false, ..Default::default() };
+ let rows = |img: &Rgba8| (0..img.height).filter(|&y| (0..img.width).any(|x| img.get(x, y)[0] > 64)).count() as f32;
+ let mut export = Rgba8::new(200, 150);
+ draw_watermark(&mut export, &wm);
+ let mut preview = Rgba8::new(800, 600);
+ draw_watermark_preview(&mut preview, &wm, 150);
+ let mut unscaled = Rgba8::new(800, 600);
+ draw_watermark(&mut unscaled, &wm);
+ let (export_share, preview_share) = (rows(&export) / 150.0, rows(&preview) / 600.0);
+ assert!((preview_share - export_share).abs() < 0.02, "export {export_share}, preview {preview_share}");
+ assert!(rows(&unscaled) < rows(&preview) / 2.0, "the unscaled 6 px floor would draw it too small");
+ // drawn at the export's own size, the preview is the export
+ let mut same = Rgba8::new(200, 150);
+ draw_watermark_preview(&mut same, &wm, 150);
+ assert_eq!(same.data, export.data);
+}
+
+fn vertical_japanese() -> Watermark {
+ let options = ExportOptions::from_json(&json!({"watermark": {"text": "日本語", "vertical": true, "size": 0.1, "shadow": false, "opacity": 1.0}}));
+ options.watermark.unwrap()
+}
+
+#[test]
+fn japanese_watermark_options_and_legacy_defaults() {
+ let old = ExportOptions::from_json(&json!({"watermark": {"text": "日本語"}}));
+ assert!(!old.watermark.unwrap().vertical);
+ let wm = vertical_japanese();
+ assert!(wm.vertical);
+ let round: Watermark = serde_json::from_value(serde_json::to_value(&wm).unwrap()).unwrap();
+ assert!(round.vertical);
+}
+
+/// Built without craft-fonts, a Japanese watermark still lays out and draws (Inter's
+/// missing-glyph boxes), and Latin text is unaffected.
+#[test]
+fn watermarks_work_without_craft_fonts() {
+ assert_eq!(watermark_fonts(&[]).len(), 1, "Inter only");
+ for wm in [vertical_japanese(), Watermark { text: "LightCraft 日本語".into(), ..Watermark::default() }] {
+ let mut covered = 0usize;
+ watermark_coverage(400, 300, &wm, &[], 1.0, |_, _, k, _| covered += usize::from(k > 0.0));
+ assert!(covered > 0, "{:?} draws something", wm.text);
+ }
+}
+
+#[test]
+fn biz_ud_vertical_watermarks_place_punctuation_at_the_top_right() {
+ use ab_glyph::Font;
+ let Some(entry) = crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "BIZ UDMincho") else {
+ lightcraft_testkit::skip!(Fonts, "built without BIZ UDMincho from craft-fonts");
+ return;
+ };
+ let font = ab_glyph::FontRef::try_from_slice(entry.bytes).unwrap();
+ // BIZ UDMincho has no Unicode presentation-form characters: the old fallback drew 、。.
+ assert_eq!(font.glyph_id('︑').0, 0);
+ assert_eq!(font.glyph_id('︒').0, 0);
+ let data = harfrust::ShaperData::new(&harfrust::FontRef::new(entry.bytes).unwrap());
+ for ch in ['、', '。'] {
+ let glyph = watermark_cell_glyphs(&font, &data, &ch.to_string(), true, 100.0, 0.0, 0.0).unwrap().remove(0);
+ assert_ne!(glyph.id, font.glyph_id(ch), "the font's vertical alternate for {ch}");
+ let rect = font.outline_glyph(glyph).unwrap().px_bounds();
+ assert!(rect.min.x > 50.0 && rect.max.y < 50.0, "{ch} in the upper right: {rect:?}");
+ }
+ let craft = Box::leak(
+ vec![crate::fonts::CraftFont { family: entry.family, style: entry.style, scripts: entry.scripts, bytes: entry.bytes }].into_boxed_slice(),
+ );
+ let wm = Watermark {
+ text: "、。".into(),
+ vertical: true,
+ size: 0.1,
+ anchor: Anchor::TopLeft,
+ inset_x: 0.0,
+ inset_y: 0.0,
+ shadow: false,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ let mut pixels = Vec::new();
+ watermark_coverage(400, 300, &wm, craft, 1.0, |x, y, k, _| {
+ if k > 0.5 {
+ pixels.push((x, y));
+ }
+ });
+ assert!(!pixels.is_empty());
+ for (x, y) in pixels {
+ assert!(x > 15 && y % 30 < 15, "actual export coverage at the upper right of the 30 px cell: {x}, {y}");
+ }
+}
+
+#[test]
+fn vertical_watermarks_keep_combining_marks_in_one_cell() {
+ let coverage = |text: &str, craft| {
+ let wm = Watermark {
+ text: text.into(),
+ vertical: true,
+ size: 0.1,
+ anchor: Anchor::Center,
+ inset_x: 0.0,
+ inset_y: 0.0,
+ shadow: false,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ let mut pixels = vec![0.0f32; 400 * 300];
+ watermark_coverage(400, 300, &wm, craft, 1.0, |x, y, k, _| pixels[y * 400 + x] = k);
+ assert!(pixels.iter().any(|&k| k > 0.0));
+ pixels
+ };
+ let compare = |a: &str, b: &str, craft| {
+ let (a_pixels, b_pixels) = (coverage(a, craft), coverage(b, craft));
+ let difference = a_pixels.iter().zip(&b_pixels).position(|(a, b)| a != b);
+ assert!(difference.is_none(), "{a:?} vs {b:?}: first differing pixel {difference:?}");
+ };
+ for (composed, decomposed) in [("éA", "e\u{301}A"), ("Å\nA", "A\u{30a}\nA"), ("A\nB", "A\r\nB"), ("日A", "日\u{e0100}A")] {
+ compare(composed, decomposed, &[]);
+ }
+ if crate::fonts::CRAFT_FONTS.iter().any(|f| f.family == "BIZ UDMincho") {
+ for (composed, decomposed) in [("が日", "か\u{3099}日"), ("ぱ\n日", "は\u{309a}\n日")] {
+ compare(composed, decomposed, crate::fonts::CRAFT_FONTS);
+ }
+ } else {
+ lightcraft_testkit::skip!(Fonts, "Japanese comparisons: built without BIZ UDMincho from craft-fonts");
+ }
+}
+
+#[test]
+fn upright_watermark_cell_retains_multiple_glyphs() {
+ use ab_glyph::{Font, ScaleFont};
+ let font = ab_glyph::FontRef::try_from_slice(WATERMARK_FONT).unwrap();
+ let data = harfrust::ShaperData::new(&harfrust::FontRef::new(WATERMARK_FONT).unwrap());
+ // There is no precomposed A with a combining long solidus overlay.
+ let glyphs = watermark_cell_glyphs(&font, &data, "A\u{338}", false, 30.0, 0.0, 0.0).unwrap();
+ assert_eq!(glyphs.len(), 2, "retain the base and the separately positioned combining glyph");
+ let baseline = font.as_scaled(30.0).ascent();
+ for glyph in glyphs {
+ assert!((glyph.position.y - baseline).abs() < 1.0, "no extra vertical cell for the mark");
+ assert!(font.outline_glyph(glyph).is_some(), "both glyphs have ink");
+ }
+}
+
+#[test]
+fn japanese_watermarks_support_vertical_columns() {
+ use ab_glyph::Font;
+ let fonts = watermark_fonts(crate::fonts::CRAFT_FONTS);
+ if fonts.len() < 2 {
+ lightcraft_testkit::skip!(Fonts, "built without CRAFT_FONTS_DIR, so there is no Japanese watermark face");
+ return;
+ }
+ for c in "日本語の文字".chars() {
+ assert!(fonts[1..].iter().any(|f| f.glyph_id(c).0 != 0), "a craft-fonts face has {c}");
+ }
+ let wm = vertical_japanese();
+ let mut img = Rgba8::new(400, 300);
+ img.data.fill([0, 0, 0, 255]);
+ draw_watermark(&mut img, &wm);
+ let lit: Vec<_> = (0..300).flat_map(|y| (0..400).map(move |x| (x, y))).filter(|&(x, y)| img.get(x, y)[0] > 64).collect();
+ assert!(lit.len() > 100);
+ let w = lit.iter().map(|p| p.0).max().unwrap() - lit.iter().map(|p| p.0).min().unwrap();
+ let h = lit.iter().map(|p| p.1).max().unwrap() - lit.iter().map(|p| p.1).min().unwrap();
+ assert!(h > w * 2, "vertical Japanese must extend down the column");
+ let two = Watermark { text: "日\n本".into(), anchor: Anchor::TopLeft, inset_x: 0.0, inset_y: 0.0, ..wm };
+ img.data.fill([0, 0, 0, 255]);
+ draw_watermark(&mut img, &two);
+ for (text, dx) in [("本", 0), ("日", 30)] {
+ let mut single = Rgba8::new(400, 300);
+ single.data.fill([0, 0, 0, 255]);
+ draw_watermark(&mut single, &Watermark { text: text.into(), ..two.clone() });
+ for y in 0..30 {
+ for x in 0..30 {
+ assert_eq!(img.get(x + dx, y), single.get(x, y), "newlines move columns left");
+ }
+ }
+ }
+}
+
+#[test]
+fn graphic_watermark_is_placed_scaled_and_blended() {
+ let dir = std::env::temp_dir().join(format!("lc-wm-logo-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let logo_path = dir.join("logo.png");
+ // 40×20: left half opaque red, right half fully transparent
+ let logo = Rgba8::from_fn(40, 20, |x, _| if x < 20 { [255, 0, 0, 255] } else { [0, 255, 0, 0] });
+ let png = lightcraft_codecs::encode_png(&EncodeImage::rgba8(&logo), &EncodeMeta::default()).unwrap();
+ std::fs::write(&logo_path, png).unwrap();
+ let mut img = Rgba8::new(400, 300);
+ img.data.iter_mut().for_each(|p| *p = [0, 0, 0, 255]);
+ let wm =
+ Watermark { image: logo_path.to_string_lossy().into(), image_width: 0.25, opacity: 1.0, inset_x: 0.0, inset_y: 0.0, ..Default::default() };
+ draw_watermark(&mut img, &wm);
+ // 100 px wide × 50 px high in the bottom-right corner
+ assert!(img.get(310, 280)[0] > 200, "opaque half: {:?}", img.get(310, 280));
+ assert_eq!(img.get(390, 280), [0, 0, 0, 255], "transparent half leaves the photo");
+ assert_eq!(img.get(310, 240), [0, 0, 0, 255], "above the logo");
+ assert_eq!(img.get(10, 10), [0, 0, 0, 255]);
+ // 30 px from the right edge and 15 px from the bottom: x 270..370, y 235..285
+ let mut img = Rgba8::new(400, 300);
+ img.data.iter_mut().for_each(|p| *p = [0, 0, 0, 255]);
+ draw_watermark(&mut img, &Watermark { inset_x: 0.1, inset_y: 0.05, ..wm.clone() });
+ assert!(img.get(272, 283)[0] > 200, "inside the moved logo: {:?}", img.get(272, 283));
+ assert_eq!(img.get(267, 283), [0, 0, 0, 255], "left of the logo");
+ assert_eq!(img.get(272, 288), [0, 0, 0, 255], "below the logo");
+ // turned: 180° puts the opaque half on the right; 90° clockwise puts it on top of a 50 × 100 box
+ let turned = |rotation: u16| {
+ let mut img = Rgba8::new(400, 300);
+ img.data.iter_mut().for_each(|p| *p = [0, 0, 0, 255]);
+ draw_watermark(&mut img, &Watermark { rotation, ..wm.clone() });
+ img
+ };
+ let half = turned(180);
+ assert!(half.get(390, 280)[0] > 200 && half.get(310, 280) == [0, 0, 0, 255]);
+ let quarter = turned(90);
+ assert!(quarter.get(375, 220)[0] > 200, "top half of the turned logo: {:?}", quarter.get(375, 220));
+ assert_eq!(quarter.get(375, 280), [0, 0, 0, 255], "its transparent half below");
+ assert_eq!(quarter.get(340, 220), [0, 0, 0, 255], "left of the 50 px wide box");
+ assert!(quarter.get(352, 202)[0] > 200 && quarter.get(398, 248)[0] > 200, "the whole box is covered");
+ // three quarter turns: the opaque half at the bottom
+ let three = turned(270);
+ assert!(three.get(375, 280)[0] > 200 && three.get(375, 220) == [0, 0, 0, 255]);
+ // an image-only watermark survives the params (no text needed)
+ let o = ExportOptions::from_json(&json!({"watermark": {"image": logo_path.to_string_lossy(), "imageWidth": 0.1}}));
+ assert_eq!(o.watermark.as_ref().map(|w| w.image_width), Some(0.1));
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn naming_and_params() {
+ let o = ExportOptions::from_json(&serde_json::json!({"format": "jpg", "quality": 150, "longEdge": 2048, "naming": "{name}-{seq}"}));
+ assert_eq!(o.format, ExportFormat::Jpeg);
+ assert_eq!(o.quality, 100);
+ assert_eq!(o.resize, Some(Resize { dont_enlarge: true, height: 0, ..Resize::long_edge(2048) }));
+ assert_eq!(o.file_name_for(&named("IMG/1.png"), 7), "IMG_1-007.jpg");
+ assert_eq!(o.ppi, 240);
+ let orig = ExportOptions { format: ExportFormat::Original, naming: "{name}-{seq}".into(), ..Default::default() };
+ assert_eq!(orig.file_name_for(&named("DSC_1.NEF"), 2), "DSC_1-002.NEF");
+ assert_eq!(orig.file_name_for(&named("noext"), 1), "noext-001");
+ assert_eq!(ExportOptions { format: ExportFormat::Dng, ..Default::default() }.file_name_for(&named("a.cr2"), 1), "a.dng");
+}
+
+fn named(file_name: &str) -> lightcraft_catalog::Photo {
+ use lightcraft_catalog::{Photo, PhotoId, Source};
+ Photo::new(PhotoId(1), Source::Demo { scene: 0 }, file_name, "", 1, 1, "2026-01-01T00:00:00")
+}
+
+/// Export naming takes the same tokens as Rename Photos and import renaming.
+#[test]
+fn naming_uses_the_rename_tokens() {
+ let mut p = named("DSC_0815.NEF");
+ p.captured = Some("2026-09-30T14:05:09".into());
+ p.meta.camera = "Model X/2".into();
+ p.meta.title = "Harbour".into();
+ p.rating = 5;
+ let o = |naming: &str| ExportOptions { naming: naming.into(), start_number: 9, ..Default::default() };
+ assert_eq!(o("{date:%Y-%m-%d}_{title}_{seq:2}").file_name_for(&p, 1), "2026-09-30_Harbour_09.jpg");
+ assert_eq!(o("{camera}-{num}-{rating}").file_name_for(&p, 1), "Model X_2-0815-5.jpg", "path separators become _");
+ assert_eq!(o("{name}-{seq}").file_name_for(&p, 3), "DSC_0815-011.jpg", "a bare {{seq}} keeps its 3 digits");
+ assert_eq!(o("{ext}_{name}").file_name_for(&p, 1), "NEF_DSC_0815.jpg");
+ // nothing left after expanding: the original name
+ p.meta.title.clear();
+ assert_eq!(o("{title}").file_name_for(&p, 1), "DSC_0815.jpg");
+}
+
+#[test]
+fn params_round_trip() {
+ let o = ExportOptions {
+ format: ExportFormat::Tiff,
+ quality: 70,
+ resize: Some(Resize { mode: ResizeMode::Megapixels, value: 12.5, height: 0, dont_enlarge: false }),
+ ppi: 300,
+ limit_kb: Some(500),
+ sharpen: SharpenFor::Glossy,
+ naming: "{date}-{name}-{seq}".into(),
+ start_number: 42,
+ subfolder: "Client".into(),
+ conflict: Conflict::Skip,
+ tiff_compression: TiffCompression::Lzw,
+ metadata: MetadataPolicy::Copyright,
+ remove_location: true,
+ watermark: Some(Watermark { text: "© LC".into(), ..Default::default() }),
+ color_space: OutputSpace::ProPhoto,
+ bit_depth: Some(16),
+ ..Default::default()
+ };
+ assert_eq!(ExportOptions::from_json(&o.to_json()), o);
+ let full = ExportOptions::default();
+ assert_eq!(ExportOptions::from_json(&full.to_json()), full);
+ assert!(ExportOptions::has_size_param(&full.to_json()), "full size is explicit");
+ let mut p = named("IMG.png");
+ p.captured = Some("2026-09-30T10:00:00".into());
+ assert_eq!(o.file_name_for(&p, 2), "20260930-IMG-043.tif");
+}
+
+#[test]
+fn resize_modes() {
+ let size = |p: serde_json::Value, w: f64, h: f64| ExportOptions::from_json(&p).resize.map(|r| r.apply(w, h));
+ // a 6000 × 4000 landscape and a 4000 × 6000 portrait
+ assert_eq!(size(json!({"longEdge": 1500}), 6000.0, 4000.0), Some((1500, 1000)));
+ assert_eq!(size(json!({"longEdge": 1500}), 4000.0, 6000.0), Some((1000, 1500)));
+ assert_eq!(size(json!({"shortEdge": 1080}), 6000.0, 4000.0), Some((1620, 1080)));
+ assert_eq!(size(json!({"width": 3000}), 4000.0, 6000.0), Some((3000, 4500)));
+ assert_eq!(size(json!({"height": 1000}), 6000.0, 4000.0), Some((1500, 1000)));
+ // W × H fits either orientation: the long edge gets the larger number
+ assert_eq!(size(json!({"width": 1000, "height": 800}), 6000.0, 4000.0), Some((1000, 667)));
+ assert_eq!(size(json!({"width": 1000, "height": 800}), 4000.0, 6000.0), Some((667, 1000)));
+ assert_eq!(size(json!({"width": 1000, "height": 500}), 6000.0, 4000.0), Some((750, 500)));
+ assert_eq!(size(json!({"width": 270, "height": 337, "fit": "dimensions"}), 480.0, 320.0), Some((337, 225)));
+ // Width & Height (`fit: widthHeight`) binds each edge to its own number: W limits the width, H the height (#1620)
+ assert_eq!(size(json!({"width": 270, "height": 337, "fit": "widthHeight"}), 480.0, 320.0), Some((270, 180)));
+ assert_eq!(size(json!({"width": 270, "height": 337, "fit": "widthHeight"}), 320.0, 480.0), Some((225, 337)));
+ assert_eq!(size(json!({"width": 240, "height": 300, "fit": "widthHeight"}), 480.0, 320.0), Some((240, 160)));
+ // `fit` only matters with both numbers
+ assert_eq!(size(json!({"width": 1000, "fit": "widthHeight"}), 6000.0, 4000.0), Some((1000, 667)));
+ let (w, h) = size(json!({"megapixels": 6}), 6000.0, 4000.0).unwrap();
+ assert!(((w * h) as f64 - 6e6).abs() < 6e6 * 0.002, "{w}×{h}");
+ assert_eq!(size(json!({"percent": 25}), 6000.0, 4000.0), Some((1500, 1000)));
+ // don't enlarge (default) vs enlarge
+ assert_eq!(size(json!({"longEdge": 8000}), 6000.0, 4000.0), Some((6000, 4000)));
+ assert_eq!(size(json!({"longEdge": 9000, "dontEnlarge": false}), 6000.0, 4000.0), Some((9000, 6000)));
+ // full size / absent
+ assert_eq!(size(json!({"longEdge": 0}), 6000.0, 4000.0), None);
+ assert_eq!(size(json!({}), 6000.0, 4000.0), None);
+ assert!(ExportOptions::has_size_param(&json!({"longEdge": 0})) && !ExportOptions::has_size_param(&json!({"quality": 3})));
+ // the `resize` object form round-trips (what the dialog and prefs store)
+ let r = Resize { mode: ResizeMode::ShortEdge, value: 720.0, height: 0, dont_enlarge: false };
+ let back = ExportOptions::from_json(&ExportOptions::resize_json(Some(&r))).resize;
+ assert_eq!(back, Some(r));
+ let r = Resize { mode: ResizeMode::WidthHeight, value: 270.0, height: 337, dont_enlarge: true };
+ assert_eq!(ExportOptions::from_json(&ExportOptions::resize_json(Some(&r))).resize, Some(r));
+ assert_eq!(ExportOptions::from_json(&ExportOptions::resize_json(None)).resize, None);
+ assert_eq!(ExportOptions::from_json(&json!({"ppi": 300})).ppi, 300);
+ // never larger than the encoders' limit, never empty
+ assert_eq!(size(json!({"percent": 10000, "dontEnlarge": false}), 6000.0, 4000.0), Some((27713, 18475)), "512 MP at most");
+ assert_eq!(size(json!({"width": 70000, "dontEnlarge": false}), 60000.0, 100.0), Some((65535, 109)), "65535 px an edge");
+ assert_eq!(size(json!({"width": 1}), 6000.0, 40.0).map(|s| s.1), Some(1));
+}
+
+/// Typing 20000 for 2000 (or percent 10000) with Don't Enlarge off asked for gigapixels: the
+/// render's first plane alone (34 GB at 65535 × 43690) failed to allocate, which aborts the
+/// process. An enlargement stops at 512 megapixels; full-size and smaller exports of photos
+/// larger than that are untouched.
+#[test]
+fn enlargements_stop_at_512_megapixels() {
+ let size = |p: serde_json::Value, w: f64, h: f64| ExportOptions::from_json(&p).resize.map(|r| r.apply(w, h)).unwrap();
+ for p in [json!({"longEdge": 60000, "dontEnlarge": false}), json!({"megapixels": 5000}), json!({"percent": 10000, "dontEnlarge": false})] {
+ let (w, h) = size(p.clone(), 6000.0, 4000.0);
+ assert!((w * h) as f64 <= MAX_ENLARGED_PIXELS * 1.001, "{p}: {w}×{h}");
+ assert!((w as f64 / h as f64 - 1.5).abs() < 0.001, "{p}: keeps the shape");
+ }
+ // below the ceiling an enlargement is as asked
+ assert_eq!(size(json!({"longEdge": 12000, "dontEnlarge": false}), 6000.0, 4000.0), (12000, 8000));
+ // a 600 MP panorama exports at full size, and smaller, as before; it is never enlarged
+ assert_eq!(size(json!({"percent": 100, "dontEnlarge": false}), 30000.0, 20000.0), (30000, 20000));
+ assert_eq!(size(json!({"percent": 50}), 30000.0, 20000.0), (15000, 10000));
+ assert_eq!(size(json!({"percent": 200, "dontEnlarge": false}), 30000.0, 20000.0), (30000, 20000));
+}
+
+/// An enlarged export that needs more memory than the computer has is refused with a message,
+/// before it starts; everything else goes ahead.
+#[test]
+fn enlarged_exports_must_fit_the_computers_memory() {
+ let gb = 1usize << 30;
+ let why = too_big_for_memory((27713, 18475), 24_000_000, 20 * gb, Some(16 * gb)).unwrap();
+ assert!(why.contains("27713 × 18475") && why.contains("20 GB") && why.contains("16 GB") && why.contains("smaller size"), "{why}");
+ assert_eq!(too_big_for_memory((27713, 18475), 24_000_000, 20 * gb, Some(32 * gb)), None, "fits");
+ assert_eq!(too_big_for_memory((6000, 4000), 24_000_000, 20 * gb, Some(gb)), None, "full size is never refused");
+ assert_eq!(too_big_for_memory((3000, 2000), 24_000_000, 20 * gb, Some(gb)), None, "nor a smaller export");
+ assert_eq!(too_big_for_memory((27713, 18475), 24_000_000, 20 * gb, None), None, "unknown memory");
+}
+
+#[test]
+fn resize_size_survives_the_render() {
+ // the render fits the photo into the size `apply` gives; that must not cost a pixel (#1312)
+ let cropped = |r: Resize, w: u32, h: u32, x1: f64| {
+ let mut p = named("IMG.ARW");
+ (p.width, p.height) = (w, h);
+ std::sync::Arc::make_mut(&mut p.develop).crop.geometry.rect = lightcraft_geom::Rect::new(0.0, 0.0, x1, 1.0);
+ let (bw, bh) = output_size(&p, &ExportOptions { resize: Some(r), ..Default::default() });
+ lightcraft_pipeline::output_size(w as usize, h as usize, &p.develop, &lightcraft_pipeline::RenderRequest::fit(bw, bh))
+ };
+ let rendered = |r: Resize, w: u32, h: u32| cropped(r, w, h, 1.0);
+ let mode = |mode: ResizeMode, value: f32, height: u32| Resize { mode, value, height, dont_enlarge: true };
+ // a frame a hair narrower than 3:2 (a raw's default crop in floats) puts 1333 × 1.5 just under 1999.5
+ let hair = 1.0 - 1e-9;
+ assert_eq!(cropped(Resize::long_edge(2000), 6000, 4000, hair), (2000, 1333));
+ assert_eq!(cropped(Resize::long_edge(2048), 6000, 4000, hair), (2048, 1365));
+ assert_eq!(cropped(mode(ResizeMode::Width, 2000.0, 0), 6000, 4000, hair), (2000, 1333));
+ assert_eq!(cropped(mode(ResizeMode::ShortEdge, 1333.0, 0), 6000, 4000, hair), (2000, 1333));
+ assert_eq!(cropped(mode(ResizeMode::Height, 1333.0, 0), 6000, 4000, hair), (2000, 1333));
+ assert_eq!(rendered(Resize::long_edge(2000), 4000, 6000), (1333, 2000));
+ // 3:2, 4:3, 16:9, 1:1 and their portraits, every mode: the render keeps what `apply` says
+ for (w, h) in [(6000u32, 4000u32), (6240, 4160), (4032, 3024), (5184, 3888), (3840, 2160), (6000, 3375), (4000, 4000)] {
+ for (w, h) in [(w, h), (h, w)] {
+ for value in [1000.0, 1080.0, 1333.0, 2000.0, 2048.0, 2500.0, 3000.0] {
+ for r in [
+ Resize::long_edge(value as u32),
+ mode(ResizeMode::ShortEdge, value, 0),
+ mode(ResizeMode::Width, value, 0),
+ mode(ResizeMode::Height, value, 0),
+ mode(ResizeMode::Dimensions, value, 1365),
+ mode(ResizeMode::WidthHeight, value, 1365),
+ mode(ResizeMode::Megapixels, value / 1000.0, 0),
+ mode(ResizeMode::Percent, value / 100.0, 0),
+ ] {
+ let want = r.apply(w.into(), h.into());
+ assert_eq!(rendered(r, w, h), want, "{r:?} on {w}×{h}");
+ }
+ }
+ }
+ }
+}
+
+/// A photo more than 65535 times as long as it is short (a 70000 × 1 strip) made `scale`
+/// clamp with its lower bound above its upper one, which panics, in the export and in the
+/// Export dialog's preview on the UI thread. The encoders' limit wins, the short edge keeps a
+/// pixel.
+#[test]
+fn resize_survives_photos_too_long_for_the_encoders() {
+ let modes = [
+ json!({"longEdge": 2000}),
+ json!({"shortEdge": 1}),
+ json!({"width": 500, "height": 500}),
+ json!({"megapixels": 1}),
+ json!({"percent": 50}),
+ json!({"percent": 1000, "dontEnlarge": false}),
+ ];
+ for p in modes {
+ for (w, h) in [(70_000.0, 1.0), (1.0, 70_000.0), (1e9, 3.0), (65_536.0, 1.0)] {
+ let r = ExportOptions::from_json(&p).resize.unwrap();
+ let (ow, oh) = r.apply(w, h);
+ assert!((1..=65_535).contains(&ow) && (1..=65_535).contains(&oh), "{p} on {w}×{h}: {ow}×{oh}");
+ assert!(r.scale(w, h).is_finite());
+ }
+ }
+ // (a short edge under a pixel would be scaled up to one, which the limit then caps)
+ assert_eq!(Resize::long_edge(2000).apply(70_000.0, 1.0), (65_535, 1));
+ assert_eq!(Resize::long_edge(2000).apply(1.0, 70_000.0), (1, 65_535));
+}
+
+/// A flat field of a saturated green inside Display P3 but outside sRGB, rendered into `space`.
+fn p3_green(space: OutputSpace) -> Rgba8 {
+ use lightcraft_color::{DISPLAY_P3, REC2020};
+ let c = DISPLAY_P3.to_space(&REC2020).apply_f32([0.04, 0.45, 0.04]);
+ let src = lightcraft_raster::Rgb32f::filled(16, 16, c);
+ let req = lightcraft_pipeline::RenderRequest { space, ..lightcraft_pipeline::RenderRequest::fit(16, 16) };
+ lightcraft_pipeline::render(&src, &Default::default(), &Default::default(), &req).image
+}
+
+/// Decode `bytes` and return the centre pixel in linear sRGB primaries (unclamped), plus the
+/// recognised space of the embedded profile.
+fn decoded_in_srgb(bytes: &[u8]) -> ([f32; 3], Option<NamedSpace>) {
+ let d = lightcraft_codecs::decode(bytes, Default::default()).expect("decodes");
+ let m = d.space.to_space(&lightcraft_color::SRGB);
+ (m.apply_f32(d.image.get(8, 8)), d.space.named)
+}
+
+#[test]
+fn p3_colour_survives_a_p3_export_and_is_clipped_in_srgb() {
+ let o = |space| ExportOptions { format: ExportFormat::Png, color_space: space, ..Default::default() };
+ let (p3, named) = decoded_in_srgb(&encode_image(&p3_green(OutputSpace::DisplayP3), &o(OutputSpace::DisplayP3)).unwrap());
+ assert_eq!(named, Some(NamedSpace::DisplayP3));
+ assert!(p3[0] < -0.03 || p3[2] < -0.03, "outside sRGB after a P3 round trip: {p3:?}");
+ let (s, named) = decoded_in_srgb(&encode_image(&p3_green(OutputSpace::Srgb), &o(OutputSpace::Srgb)).unwrap());
+ assert_eq!(named, Some(NamedSpace::Srgb));
+ assert!(s.iter().all(|v| *v > -0.002), "{s:?}");
+ // the green itself is about the same brightness either way
+ assert!((p3[1] - s[1]).abs() < 0.15, "{p3:?} {s:?}");
+}
+
+#[test]
+fn every_space_embeds_its_own_profile_and_round_trips() {
+ let grey = {
+ let src = lightcraft_raster::Rgb32f::filled(16, 16, [0.18; 3]);
+ let base = lightcraft_pipeline::RenderRequest::fit(16, 16);
+ move |space| {
+ lightcraft_pipeline::render(&src, &Default::default(), &Default::default(), &lightcraft_pipeline::RenderRequest { space, ..base }).image
+ }
+ };
+ let reference =
+ decoded_in_srgb(&encode_image(&grey(OutputSpace::Srgb), &ExportOptions { format: ExportFormat::Tiff, ..Default::default() }).unwrap()).0;
+ for space in OutputSpace::ALL {
+ for format in [ExportFormat::Jpeg, ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp] {
+ let o = ExportOptions { format, color_space: space, ..Default::default() };
+ let bytes = encode_image(&grey(space), &o).unwrap();
+ let (px, named) = decoded_in_srgb(&bytes);
+ assert_eq!(named, Some(named_space(space)), "{space:?} {format:?}");
+ // a neutral grey decodes to the same linear value whatever the output space
+ for c in 0..3 {
+ assert!((px[c] - reference[c]).abs() < 0.01, "{space:?} {format:?}: {px:?} vs {reference:?}");
+ }
+ }
+ let icc = icc::write_named(named_space(space));
+ let info = icc::parse(&icc).expect("our profile parses");
+ assert_eq!(info.named, Some(named_space(space)));
+ assert!(info.description.as_deref().is_some_and(|d| !d.is_empty()));
+ }
+ let o = ExportOptions { format: ExportFormat::Avif, color_space: OutputSpace::ProPhoto, ..Default::default() };
+ assert_eq!(o.effective_space(), OutputSpace::Srgb);
+ let o = ExportOptions::from_json(&serde_json::json!({"colorSpace": "displayP3"}));
+ assert_eq!(o.color_space, OutputSpace::DisplayP3);
+ assert_eq!(ExportOptions::from_json(&serde_json::json!({"colorSpace": "Adobe RGB (1998) compatible"})).color_space, OutputSpace::AdobeRgb);
+}
+
+#[test]
+fn srgb_watermark_colour_is_converted() {
+ assert_eq!(srgb8_in(OutputSpace::Srgb, [10, 200, 30]), [10, 200, 30]);
+ for s in OutputSpace::ALL {
+ assert_eq!(srgb8_in(s, [255, 255, 255]), [255, 255, 255], "{s:?}");
+ assert_eq!(srgb8_in(s, [0, 0, 0]), [0, 0, 0], "{s:?}");
+ }
+ let p3 = srgb8_in(OutputSpace::DisplayP3, [255, 0, 0]);
+ assert!(p3[0] < 255 && p3[1] > 0, "{p3:?}");
+}
+
+/// A shallow horizontal grey ramp (few 8-bit levels), rendered at `depth`.
+fn ramp(depth: OutputDepth, space: OutputSpace) -> lightcraft_pipeline::Rendered {
+ let src = lightcraft_raster::Rgb32f::from_fn(1024, 4, |x, _| [0.10 + 0.03 * x as f32 / 1023.0; 3]);
+ let req = lightcraft_pipeline::RenderRequest { depth, space, ..lightcraft_pipeline::RenderRequest::fit(1024, 4) };
+ lightcraft_pipeline::render(&src, &Default::default(), &Default::default(), &req)
+}
+
+fn distinct_levels(bytes: &[u8]) -> (usize, lightcraft_codecs::Decoded) {
+ let d = lightcraft_codecs::decode(bytes, Default::default()).expect("decodes");
+ let mut v: Vec<u32> = (0..d.image.width).map(|x| d.image.get(x, 1)[1].to_bits()).collect();
+ v.dedup();
+ (v.len(), d)
+}
+
++/// A 16-bit render of a photo-like scene: smooth colour gradients plus sensor-like noise of
++/// `noise` (linear, about 0.002 to 0.03 for clean to high-ISO raws), the case where the low
++/// byte of every 16-bit sample is mostly noise.
++fn noisy_render(noise: f32) -> lightcraft_pipeline::Rendered {
++ let (w, h) = (512, 384);
++ // a hash of the position and channel: the same noise every run
++ let hash = |x: usize, y: usize, c: usize| {
++ let mut z = (x as u64) << 32 ^ (y as u64) << 2 ^ c as u64 ^ 0x2882;
++ z = (z ^ (z >> 33)).wrapping_mul(0xff51_afd7_ed55_8ccd);
++ z = (z ^ (z >> 33)).wrapping_mul(0xc4ce_b9fe_1a85_ec53);
++ (z ^ (z >> 33)) as f32 / u64::MAX as f32 - 0.5
++ };
++ let src = lightcraft_raster::Rgb32f::from_fn(w, h, |x, y| {
++ let (u, v) = (x as f32 / w as f32, y as f32 / h as f32);
++ let base = [0.05 + 0.4 * u, 0.1 + 0.3 * v, 0.2 + 0.2 * (u * v)];
++ [0, 1, 2].map(|c| (base[c] + noise * hash(x, y, c)).max(0.0))
++ });
++ let req = lightcraft_pipeline::RenderRequest { depth: OutputDepth::U16, ..lightcraft_pipeline::RenderRequest::fit(w, h) };
++ lightcraft_pipeline::render(&src, &Default::default(), &Default::default(), &req)
++}
++
++/// Issue #2882: a 16-bit TIFF with ZIP (the default) is never larger than the same render
++/// uncompressed, from smooth to noisy. (LZW can be: it is printed, not checked, and the export
++/// dialog says so when it is picked.)
++#[test]
++fn sixteen_bit_zip_tiff_is_never_larger_than_uncompressed() {
++ assert_eq!(ExportOptions::default().tiff_compression, TiffCompression::Deflate, "ZIP is the default");
++ for noise in [0.0, 0.002, 0.01, 0.03, 0.1] {
++ let r = noisy_render(noise);
++ assert!(matches!(r.deep.as_ref().unwrap().samples, DeepSamples::U16(_)));
++ let size = |tiff_compression| {
++ let o = ExportOptions { format: ExportFormat::Tiff, bit_depth: Some(16), tiff_compression, ..Default::default() };
++ assert_eq!(o.effective_depth(), OutputDepth::U16);
++ encode_rendered(&r, &o, None).unwrap().len()
++ };
++ let (none, zip, lzw) = (size(TiffCompression::None), size(TiffCompression::Deflate), size(TiffCompression::Lzw));
++ eprintln!(
++ "noise {noise}: none {none} B, ZIP {zip} B ({:+.1} %), LZW {lzw} B ({:+.1} %)",
++ 100.0 * (zip as f64 / none as f64 - 1.0),
++ 100.0 * (lzw as f64 / none as f64 - 1.0)
++ );
++ assert!(zip <= none, "noise {noise}: 16-bit ZIP {zip} B is larger than uncompressed {none} B");
++ }
++}
++
+#[test]
+fn sixteen_bit_tiff_and_png_have_no_banding() {
+ let tiff = |bit_depth| ExportOptions { format: ExportFormat::Tiff, bit_depth, ..Default::default() };
+ assert_eq!(tiff(None).effective_depth(), OutputDepth::U16, "TIFF defaults to 16-bit");
+ let r16 = ramp(OutputDepth::U16, OutputSpace::Srgb);
+ assert!(matches!(r16.deep.as_ref().unwrap().samples, DeepSamples::U16(_)));
+ let (levels16, d16) = distinct_levels(&encode_rendered(&r16, &tiff(None), None).unwrap());
+ let r8 = ramp(OutputDepth::U8, OutputSpace::Srgb);
+ let (levels8, _) = distinct_levels(&encode_rendered(&r8, &tiff(Some(8)), None).unwrap());
+ eprintln!("gradient levels: 16-bit TIFF {levels16}, 8-bit TIFF {levels8}");
+ assert!(levels8 < 40, "{levels8}");
+ assert!(levels16 > 10 * levels8, "16-bit: {levels16} levels vs 8-bit: {levels8}");
+ assert_eq!(d16.space.named, Some(NamedSpace::Srgb));
+ // the 8-bit preview of a deep render matches the 8-bit render
+ for (a, b) in r16.image.data.iter().zip(&r8.image.data) {
+ assert!(a[1].abs_diff(b[1]) <= 1, "{a:?} {b:?}");
+ }
+ let png = ExportOptions { format: ExportFormat::Png, bit_depth: Some(16), color_space: OutputSpace::DisplayP3, ..Default::default() };
+ let rp = ramp(OutputDepth::U16, OutputSpace::DisplayP3);
+ let bytes = encode_rendered(&rp, &png, None).unwrap();
+ assert_eq!(bytes[24], 16, "PNG IHDR bit depth");
+ let (levels, d) = distinct_levels(&bytes);
+ assert!(levels > 10 * levels8, "{levels}");
+ assert_eq!(d.space.named, Some(NamedSpace::DisplayP3));
+ // sharpening and watermarking work on deep images too
+ let o =
+ ExportOptions { sharpen: SharpenFor::Matte, watermark: Some(Watermark { text: "LC".into(), size: 0.5, ..Default::default() }), ..tiff(None) };
+ assert!(encode_rendered(&r16, &o, None).is_ok());
+}
+
+#[test]
+fn float_tiff_is_linear_with_a_linear_profile() {
+ let o = ExportOptions { format: ExportFormat::Tiff, bit_depth: Some(32), color_space: OutputSpace::ProPhoto, ..Default::default() };
+ assert_eq!(o.effective_depth(), OutputDepth::F32Linear);
+ let rf = ramp(OutputDepth::F32Linear, OutputSpace::ProPhoto);
+ let (levels, df) = distinct_levels(&encode_rendered(&rf, &o, None).unwrap());
+ assert!(levels > 500, "{levels}");
+ assert_eq!(df.space.named, Some(NamedSpace::ProPhoto));
+ assert!(df.space.trc.as_ref().is_some_and(|t| t[0].is_linear()), "{:?}", df.space.trc);
+ // decodes to the same light as the 16-bit gamma-encoded export
+ let o16 = ExportOptions { bit_depth: Some(16), ..o.clone() };
+ let (_, d16) = distinct_levels(&encode_rendered(&ramp(OutputDepth::U16, OutputSpace::ProPhoto), &o16, None).unwrap());
+ for x in [0, 300, 700, 1023] {
+ let (a, b) = (df.image.get(x, 1)[1], d16.image.get(x, 1)[1]);
+ assert!((a - b).abs() < 2e-4, "{x}: {a} vs {b}");
+ }
+}
+
+#[test]
+fn jxl_options() {
+ assert_eq!(ExportFormat::parse("JPEG-XL"), Some(ExportFormat::Jxl));
+ let o = ExportOptions::from_params(&json!({"format": "jxl", "jxlLossless": true, "jxlEffort": "fast", "jxlProgressive": true})).unwrap();
+ assert_eq!((o.format, o.jxl_lossless, o.jxl_effort, o.jxl_progressive), (ExportFormat::Jxl, true, JxlEffort::Fast, true));
+ assert_eq!(ExportOptions::from_json(&o.to_json()), o, "saved presets keep the JPEG XL settings");
+ assert!(ExportOptions::from_params(&json!({"jxlEffort": "best"})).is_err());
+ assert!(ExportOptions::from_params(&json!({"jxlLossless": "yes"})).is_err());
+ let space = |lossless, color_space, hdr| {
+ ExportOptions { format: ExportFormat::Jxl, jxl_lossless: lossless, color_space, hdr, ..Default::default() }.effective_space()
+ };
+ assert_eq!(space(false, OutputSpace::DisplayP3, false), OutputSpace::DisplayP3);
+ assert_eq!(space(false, OutputSpace::ProPhoto, false), OutputSpace::Rec2020, "lossy has no ProPhoto enum");
+ assert_eq!(space(true, OutputSpace::ProPhoto, false), OutputSpace::ProPhoto, "lossless keeps the profile");
+ assert_eq!(space(true, OutputSpace::Srgb, true), OutputSpace::Rec2020);
+ let o = ExportOptions { format: ExportFormat::Jxl, hdr: true, ..Default::default() };
+ assert!(o.hdr_output());
+ assert_eq!(o.effective_depth(), OutputDepth::F32Hdr);
+ assert_eq!(ExportFormat::Jxl.extension(), "jxl");
+}
+
+#[test]
+fn jxl_every_space_round_trips() {
+ // wide-gamut green stays outside sRGB in P3, Rec. 2020 and (lossless) ProPhoto files
+ for (lossless, space) in [
+ (false, OutputSpace::Srgb),
+ (false, OutputSpace::DisplayP3),
+ (false, OutputSpace::Rec2020),
+ (true, OutputSpace::DisplayP3),
+ (true, OutputSpace::AdobeRgb),
+ (true, OutputSpace::ProPhoto),
+ ] {
+ let o = ExportOptions { format: ExportFormat::Jxl, color_space: space, jxl_lossless: lossless, quality: 95, ..Default::default() };
+ let png = ExportOptions { format: ExportFormat::Png, color_space: space, ..Default::default() };
+ let img = p3_green(space);
+ let bytes = encode_image(&img, &o).unwrap();
+ assert_eq!(lightcraft_codecs::sniff(&bytes), Some(lightcraft_codecs::Format::Jxl));
+ let (got, _) = decoded_in_srgb(&bytes);
+ let (want, _) = decoded_in_srgb(&encode_image(&img, &png).unwrap());
+ for c in 0..3 {
+ assert!((got[c] - want[c]).abs() < 0.01, "{space:?} lossless={lossless}: {got:?} vs PNG {want:?}");
+ }
+ if space != OutputSpace::Srgb {
+ assert!(got[0] < -0.03 || got[2] < -0.03, "{space:?}: outside sRGB after the round trip: {got:?}");
+ }
+ }
+}
+
+#[test]
+fn jxl_sixteen_bit() {
+ let o = ExportOptions {
+ format: ExportFormat::Jxl,
+ bit_depth: Some(16),
+ jxl_lossless: true,
+ color_space: OutputSpace::DisplayP3,
+ ..Default::default()
+ };
+ assert_eq!(o.effective_depth(), OutputDepth::U16);
+ let (levels8, _) = distinct_levels(
+ &encode_rendered(&ramp(OutputDepth::U8, OutputSpace::DisplayP3), &ExportOptions { bit_depth: Some(8), ..o.clone() }, None).unwrap(),
+ );
+ let (levels, d) = distinct_levels(&encode_rendered(&ramp(OutputDepth::U16, OutputSpace::DisplayP3), &o, None).unwrap());
+ assert_eq!(d.bit_depth, 16);
+ assert!(levels > 10 * levels8, "{levels} vs {levels8}");
+ // lossy 16-bit encodes too
+ let lossy = ExportOptions { jxl_lossless: false, ..o };
+ assert!(encode_rendered(&ramp(OutputDepth::U16, OutputSpace::DisplayP3), &lossy, None).is_ok());
+}
+
+#[test]
+fn bit_depth_options_per_format() {
+ let d = |format, bit_depth| ExportOptions { format, bit_depth, ..Default::default() }.effective_depth();
+ assert_eq!(d(ExportFormat::Jpeg, Some(16)), OutputDepth::U8);
+ assert_eq!(d(ExportFormat::Webp, None), OutputDepth::U8);
+ assert_eq!(d(ExportFormat::Png, None), OutputDepth::U8);
+ assert_eq!(d(ExportFormat::Png, Some(16)), OutputDepth::U16);
+ assert_eq!(d(ExportFormat::Avif, Some(10)), OutputDepth::U16);
+ assert_eq!(ExportOptions::from_json(&serde_json::json!({"bitDepth": 16})).bit_depth, Some(16));
+ assert_eq!(ExportOptions::from_json(&serde_json::json!({"bitDepth": 12})).bit_depth, None);
+ assert_eq!(d(ExportFormat::Jxl, Some(16)), OutputDepth::U16);
+ assert_eq!(d(ExportFormat::Jxl, None), OutputDepth::U8);
+ for f in [ExportFormat::Jpeg, ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp, ExportFormat::Avif, ExportFormat::Jxl] {
+ let first = ExportOptions::bit_depths(f)[0].0;
+ let def = d(f, None);
+ assert_eq!(d(f, Some(first)), def, "{f:?}: the first choice is the default");
+ }
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn avif_ten_bit() {
+ let o = ExportOptions { format: ExportFormat::Avif, bit_depth: Some(10), quality: 60, ..Default::default() };
+ let r = ramp(OutputDepth::U16, OutputSpace::Srgb);
+ match encode_rendered(&r, &o, None) {
+ Ok(b) => assert_eq!(&b[4..8], b"ftyp"),
+ Err(e) => assert!(e.contains("not available"), "{e}"),
+ }
+}
+
+/// Issue #181: a command about to export refuses what `from_json` would silently default —
+/// unknown keys (naming the nearest known one) and values of the wrong kind or range.
+#[test]
+fn export_params_are_validated() {
+ assert_invalid_export_params();
+ assert_export_options_round_trip();
+}
+
+fn assert_invalid_export_params() {
+ use serde_json::json;
+ let err = |p: serde_json::Value| ExportOptions::from_params(&p).err().map(|e| e.to_string()).unwrap_or_default();
+ let e = err(json!({"longEdgee": 400}));
+ assert!(e.starts_with("invalid parameters for `app.export`: unknown parameter `longEdgee` (did you mean `longEdge`?)"), "{e}");
+ assert!(err(json!({"qualty": 5})).contains("did you mean `quality`"));
+ assert!(err(json!({"longEdge": "banana"})).contains("`longEdge` must be a number"));
+ assert!(err(json!({"quality": 0})).contains("`quality` must be an integer 1..100"));
+ assert!(err(json!({"quality": "5"})).contains("`quality` must be an integer"));
+ assert!(err(json!({"quality": 92.5})).contains("`quality` must be an integer"));
+ assert!(err(json!({"sharpen": "lots"})).contains("`sharpen` must be one of none|screen|matte|glossy"));
+ assert!(err(json!({"format": "bmp"})).contains("`format` must be one of"));
+ assert!(err(json!({"bitDepth": 12})).contains("`bitDepth` must be 8, 10, 16 or 32"));
+ assert!(err(json!({"colorSpace": "cmyk"})).contains("`colorSpace` must be one of"));
+ assert!(err(json!({"dontEnlarge": "no"})).contains("`dontEnlarge` must be true or false"));
+ assert!(err(json!({"fit": "sideways"})).contains("`fit` must be one of dimensions|widthHeight"));
+ assert!(err(json!({"resize": {"mode": "longEdge", "valeu": 10}})).contains("did you mean `value`"));
+ assert!(err(json!({"resize": {"mode": "diagonal", "value": 10}})).contains("`resize`:"));
+ assert!(err(json!({"ids": [1, "x"]})).contains("`ids` must be an array of photo ids"));
+ assert!(err(json!("jpeg")).contains("params must be an object"));
+ assert!(
+ ExportOptions::validate("export.savePreset", &json!({"qualty": 5}))
+ .unwrap_err()
+ .to_string()
+ .starts_with("invalid parameters for `export.savePreset`")
+ );
+}
+
+fn assert_export_options_round_trip() {
+ use serde_json::json;
+ let err = |p: serde_json::Value| ExportOptions::from_params(&p).err().map(|e| e.to_string()).unwrap_or_default();
+ // everything the presets, the dialog, Export with Previous and `render --opt` send passes
+ for p in builtin_presets() {
+ ExportOptions::from_params(&p.params).unwrap_or_else(|e| panic!("{}: {e}", p.name));
+ }
+ let full = ExportOptions {
+ resize: Some(Resize::default()),
+ limit_kb: Some(500),
+ watermark: Some(Watermark { text: "©".into(), ..Default::default() }),
+ format: ExportFormat::Png,
+ bit_depth: Some(16),
+ ..Default::default()
+ };
+ let mut j = full.to_json();
+ for (k, v) in [
+ ("dir", json!("/tmp/out")),
+ ("background", json!(true)),
+ ("preset", json!("x")),
+ ("ids", json!([1, 2])),
+ ("id", json!(1)),
+ ("path", json!("a.jpg")),
+ ] {
+ j[k] = v;
+ }
+ assert_eq!(ExportOptions::from_params(&j).unwrap(), full);
+ // Add to Apple Photos (issue #236): a switch and an album name; on only where Photos is
+ assert!(err(json!({"addToPhotos": "yes"})).contains("`addToPhotos` must be true or false"));
+ assert!(err(json!({"photosAlbum": 3})).contains("`photosAlbum` must be a string"));
+ assert!(err(json!({"photosAlbum": "a\0b"})).contains("NUL"));
+ assert!(err(json!({"photosAlbm": "x"})).contains("did you mean `photosAlbum`"));
+ let album = ExportOptions { photos_album: "Trip “2026” \\ \"x\"".into(), ..Default::default() };
+ assert_eq!(ExportOptions::from_params(&album.to_json()).unwrap(), album);
+ let on = ExportOptions { add_to_photos: true, ..album };
+ if cfg!(target_os = "macos") {
+ assert_eq!(ExportOptions::from_params(&on.to_json()).unwrap(), on);
+ } else {
+ assert!(err(on.to_json()).contains("Apple Photos is only available on macOS"));
+ // stored settings (a preset or Export with Previous made on a Mac) still read
+ assert!(ExportOptions::from_json(&on.to_json()).add_to_photos);
+ }
+ assert_eq!(ExportOptions::from_json(&json!({"photosAlbum": " Trip "})).photos_album, "Trip");
+ assert_eq!(ExportOptions::from_params(&ExportOptions::default().to_json()).unwrap(), ExportOptions::default());
+ // null is "not given", as a dropped key is
+ ExportOptions::from_params(&json!({"quality": 92, "longEdge": null, "watermark": null})).unwrap();
+}
+
+/// Issue #1952: a `bitDepth` the format doesn't have is refused (the Export dialog never offers
+/// it), not written at the format's own depth; the error names the depths the format takes.
+#[test]
+fn bit_depth_must_suit_the_format() {
+ use serde_json::json;
+ let err = |p: serde_json::Value| ExportOptions::from_params(&p).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(err(json!({"format": "jpeg", "bitDepth": 16})).contains("`bitDepth` must be 8 for jpeg"));
+ assert!(err(json!({"format": "png", "bitDepth": 10})).contains("`bitDepth` must be 8 or 16 for png"));
+ assert!(err(json!({"format": "tiff", "bitDepth": 10})).contains("`bitDepth` must be 8, 16 or 32 for tiff"));
+ // no `format`: the one `path` names, else the default (JPEG)
+ assert!(err(json!({"path": "/out/a.png", "bitDepth": 32})).contains("for png"));
+ assert!(err(json!({"bitDepth": 16})).contains("for jpeg"));
+ assert!(ExportOptions::from_params(&json!({"path": "/out/a.tif", "bitDepth": 32})).is_ok());
+ // a path naming no format, or a `null` format, exports the default too
+ assert!(err(json!({"path": "/out/output", "bitDepth": 10})).contains("for jpeg"));
+ assert!(err(json!({"path": "/out/output.xyz", "bitDepth": 10})).contains("for jpeg"));
+ assert!(err(json!({"format": null, "path": "/out/a.png", "bitDepth": 16})).contains("for jpeg"));
+ // or the caller's own format for such a path, which is the one returned
+ let png = |p: serde_json::Value| ExportOptions::from_params_or(&p, ExportFormat::Png);
+ assert!(png(json!({"path": "/out/output", "bitDepth": 10})).unwrap_err().to_string().contains("for png"));
+ assert_eq!(png(json!({"path": "/out/output.xyz", "bitDepth": 16})).unwrap().format, ExportFormat::Png);
+ assert_eq!(png(json!({"path": "/out/a.tif", "bitDepth": 32})).unwrap().format, ExportFormat::Tiff);
+ // stored settings (a preset, Export with Previous) lose such a depth instead of failing
+ let stored = ExportOptions::known_keys_only(&json!({"format": "jpeg", "bitDepth": 16}));
+ assert_eq!(stored.get("bitDepth"), None);
+ assert_eq!(ExportOptions::known_keys_only(&json!({"format": "tiff", "bitDepth": 32}))["bitDepth"], 32);
+ for f in [
+ ExportFormat::Jpeg,
+ ExportFormat::Png,
+ ExportFormat::Tiff,
+ ExportFormat::Psd,
+ ExportFormat::Webp,
+ ExportFormat::Avif,
+ ExportFormat::Jxl,
+ ExportFormat::Original,
+ ExportFormat::Dng,
+ ExportFormat::RenderedDng,
+ ] {
+ for &(b, _) in ExportOptions::bit_depths(f) {
+ let o = ExportOptions { format: f, bit_depth: Some(b), ..Default::default() };
+ assert_eq!(ExportOptions::from_params(&o.to_json()).ok(), Some(o), "{f:?} {b}");
+ }
+ }
+}
+
+/// Issue #956: `destinationMode` picks a specific folder (the default) or each photo's own
+/// folder; it is checked like the other params and kept in presets and Export with Previous.
+#[test]
+fn destination_mode_param() {
+ use serde_json::json;
+ assert_eq!(ExportOptions::default().destination_mode, DestinationMode::SpecificFolder);
+ for (v, want) in [
+ ("sameAsOriginal", DestinationMode::SameAsOriginal),
+ ("SameAsOriginal", DestinationMode::SameAsOriginal),
+ ("specificFolder", DestinationMode::SpecificFolder),
+ ] {
+ assert_eq!(ExportOptions::from_params(&json!({"destinationMode": v})).unwrap().destination_mode, want, "{v}");
+ }
+ let e = ExportOptions::from_params(&json!({"destinationMode": "nextToIt"})).unwrap_err().to_string();
+ assert!(e.contains("`destinationMode` must be one of specificFolder|sameAsOriginal"), "{e}");
+ assert!(ExportOptions::from_params(&json!({"destinationMode": 1})).is_err());
+ assert!(
+ ExportOptions::from_params(&json!({"destinationMod": "sameAsOriginal"})).unwrap_err().to_string().contains("did you mean `destinationMode`")
+ );
+ // saved (a preset, `lastExport`) and read back
+ let o = ExportOptions { destination_mode: DestinationMode::SameAsOriginal, subfolder: "Exports".into(), ..Default::default() };
+ let j = o.to_json();
+ assert_eq!(j["destinationMode"], "sameAsOriginal");
+ assert_eq!(ExportOptions::from_params(&ExportOptions::known_keys_only(&j)).unwrap(), o);
+}
+
+/// A choice the validation accepts is the one exported: `metadata: "NONE"` passed the
+/// case-insensitive check, then failed the exact-case read and fell back to `all`, so GPS and
+/// camera data went out in a file meant to carry none. `sharpen`, `sharpenAmount` and
+/// `conflict` had the same gap.
+#[test]
+fn accepted_choices_are_the_ones_exported() {
+ use serde_json::json;
+ let read = |k: &str, v: &str| ExportOptions::from_params(&json!({ k: v })).map_err(|e| e.to_string());
+ let metadata = [
+ ("all", MetadataPolicy::All),
+ ("allExceptCamera", MetadataPolicy::AllExceptCamera),
+ ("copyright", MetadataPolicy::Copyright),
+ ("none", MetadataPolicy::None),
+ ];
+ for (name, want) in metadata {
+ for v in [name.to_string(), name.to_ascii_uppercase(), name.to_ascii_lowercase()] {
+ assert_eq!(read("metadata", &v).unwrap().metadata, want, "metadata: {v}");
+ }
+ }
+ for (name, want) in [("none", SharpenFor::None), ("screen", SharpenFor::Screen), ("matte", SharpenFor::Matte), ("glossy", SharpenFor::Glossy)] {
+ assert_eq!(read("sharpen", &name.to_ascii_uppercase()).unwrap().sharpen, want);
+ }
+ for (name, want) in [("low", SharpenAmount::Low), ("standard", SharpenAmount::Standard), ("high", SharpenAmount::High)] {
+ assert_eq!(read("sharpenAmount", &name.to_ascii_uppercase()).unwrap().sharpen_amount, want);
+ }
+ for (name, want) in [("unique", Conflict::Unique), ("overwrite", Conflict::Overwrite), ("skip", Conflict::Skip)] {
+ assert_eq!(read("conflict", &name.to_ascii_uppercase()).unwrap().conflict, want);
+ }
+ // an explicit value nothing reads as is an error, never the permissive default
+ for v in ["", " none", "nothing", "all-except-camera"] {
+ let e = read("metadata", v).unwrap_err();
+ assert!(e.contains("`metadata` must be one of all|allExceptCamera|copyright|none"), "{v:?}: {e}");
+ }
+ assert!(read("sharpenAmount", "max").unwrap_err().contains("`sharpenAmount` must be one of low|standard|high"));
+ assert!(read("conflict", "replace").unwrap_err().contains("`conflict` must be one of unique|overwrite|skip"));
+ // absent (or null) keeps the defaults
+ let d = ExportOptions::from_params(&json!({"metadata": null})).unwrap();
+ assert_eq!(
+ (d.metadata, d.sharpen, d.sharpen_amount, d.conflict),
+ (MetadataPolicy::All, SharpenFor::None, SharpenAmount::Standard, Conflict::Unique)
+ );
+ // `removeLocation` stays independent of the policy's spelling
+ let o = ExportOptions::from_params(&json!({"metadata": "AllExceptCamera", "removeLocation": true})).unwrap();
+ assert_eq!((o.metadata, o.remove_location), (MetadataPolicy::AllExceptCamera, true));
+ // stored settings (lenient `from_json`) read the same spellings
+ assert_eq!(ExportOptions::from_json(&json!({"metadata": "None"})).metadata, MetadataPolicy::None);
+ // and `to_json` still writes what the MCP schema lists
+ let j = ExportOptions { metadata: MetadataPolicy::AllExceptCamera, conflict: Conflict::Skip, ..Default::default() }.to_json();
+ assert_eq!((j["metadata"].as_str(), j["conflict"].as_str()), (Some("allExceptCamera"), Some("skip")));
+}
+
+/// Issue #183: the `watermark` object's keys, kinds and ranges are checked (and documented in
+/// the `app.export` param string), instead of unknown keys passing and sizes clamping silently.
+#[test]
+fn watermark_params_are_validated() {
+ use serde_json::json;
+ let err = |w: serde_json::Value| ExportOptions::from_params(&json!({"watermark": w})).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(err(json!(5)).contains(
+ "`watermark` must be text or an object {text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}"
+ ));
+ assert!(err(json!({"text": "x", "bogus": 1})).contains(
+ "unknown watermark key `bogus` (one of text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth)"
+ ));
+ assert!(err(json!({"text": "x", "sizee": 0.1})).contains("did you mean `size`"));
+ for size in [json!(3), json!(0.5001), json!(0), json!("big")] {
+ let e = err(json!({"text": "x", "size": size}));
+ assert!(e.contains("`watermark.size` must be a number 0.005..0.5 (fraction of the short edge)"), "{size}: {e}");
+ }
+ assert!(err(json!({"text": "x", "opacity": 1.5})).contains("`watermark.opacity` must be a number 0..1"));
+ assert!(err(json!({"text": "x", "inset": -0.1})).contains("`watermark.inset` must be a number 0..0.4"));
+ assert!(err(json!({"text": "x", "insetX": 0.5})).contains("`watermark.insetX` must be a number 0..0.4"));
+ assert!(err(json!({"text": "x", "insetY": "far"})).contains("`watermark.insetY` must be a number 0..0.4"));
+ for rotation in [json!(45), json!(-90), json!(360), json!("90"), json!(90.5)] {
+ let e = err(json!({"text": "x", "rotation": rotation}));
+ assert!(e.contains("`watermark.rotation` must be 0, 90, 180 or 270 (degrees clockwise)"), "{rotation}: {e}");
+ }
+ assert!(ExportOptions::from_params(&json!({"watermark": {"text": "x", "rotation": 270}})).is_ok());
+ assert!(err(json!({"image": "logo.png", "imageWidth": 2})).contains("`watermark.imageWidth` must be a number 0.01..1"));
+ assert!(err(json!({"text": "x", "anchor": "middle"})).contains("`watermark.anchor` must be one of"));
+ assert!(err(json!({"text": "x", "color": [255, 255]})).contains("`watermark.color` must be [r, g, b]"));
+ assert!(err(json!({"text": "x", "color": [255, 255, 256]})).contains("`watermark.color`"));
+ assert!(err(json!({"text": "x", "vertical": "yes"})).contains("`watermark.vertical` must be true or false"));
+ assert!(err(json!({"text": 7})).contains("`watermark.text` must be a string"));
+ // the documented shapes pass and read as before
+ let o = ExportOptions::from_params(&json!({"watermark": "© me"})).unwrap();
+ assert_eq!(o.watermark.map(|w| w.text).as_deref(), Some("© me"));
+ let w = json!({"text": "日本語", "vertical": true, "size": 0.1, "opacity": 0.5, "anchor": "topLeft", "inset": 0.05, "color": [0, 0, 0], "shadow": false, "image": "", "imageWidth": 0.3});
+ let wm = ExportOptions::from_params(&json!({"watermark": w})).unwrap().watermark.unwrap();
+ assert!((wm.size - 0.1).abs() < 1e-6 && wm.vertical && wm.anchor == Anchor::TopLeft && wm.color == [0, 0, 0] && !wm.shadow);
+ assert_eq!(ExportOptions::from_params(&json!({"watermark": {"text": "x", "size": 0.5}})).unwrap().watermark.map(|w| w.size), Some(0.5));
+ // the Export dialog's sliders (1–15 % size, 5–100 % opacity, 2–100 % width) stay inside the accepted ranges
+ assert!(WATERMARK_SIZE_RANGE.0 <= 0.01 && WATERMARK_SIZE_RANGE.1 >= 0.15);
+ assert!(WATERMARK_IMAGE_WIDTH_RANGE.0 <= 0.02 && WATERMARK_IMAGE_WIDTH_RANGE.1 >= 1.0);
+}
+
+/// A batch with `lanes` photos in flight into a fake folder `out` (nothing exists there):
+/// results, writes (path, bytes) and progress calls; `progress` returns false at `cancel_at`.
+#[allow(clippy::type_complexity)]
+fn lanes_batch(
+ s: &mut crate::Session,
+ ids: &[lightcraft_catalog::PhotoId],
+ o: &ExportOptions,
+ lanes: usize,
+ stop_on_error: bool,
+ cancel_at: usize,
+) -> (Result<Vec<serde_json::Value>, String>, Vec<(String, Vec<u8>)>, Vec<(usize, String)>) {
+ let items = prepare_batch(s, ids, o).unwrap();
+ let to = Destination { dir: "out".into(), exact: None };
+ let mut written = Vec::new();
+ let mut write = |p: &str, b: &[u8]| {
+ written.push((p.to_string(), b.to_vec()));
+ Ok(())
+ };
+ let mut seen = Vec::new();
+ let mut progress = |i: usize, name: &str| {
+ seen.push((i, name.to_string()));
+ i < cancel_at
+ };
+ let files = run_batch_with(items, &mut Placer::new(o, &to, &mut write, &|_| false, stop_on_error), &mut progress, lanes);
+ (files, written, seen)
+}
+
+/// The files of a batch without their byte counts: a GPU render (when another test turns the
+/// GPU off mid-run) may differ from a CPU one by an LSB, never in name, size or order.
+fn shape(files: &[serde_json::Value]) -> Vec<serde_json::Value> {
+ files.iter().map(|f| json!({"path": f["path"], "width": f["width"], "height": f["height"], "error": f["error"]})).collect()
+}
+
+/// Issue #675: a batch reports a render that fell back from the GPU to the CPU on that file's
+/// entry (`gpuFallback`, the render's own reason) and says nothing on the others.
+#[test]
+fn a_batch_reports_a_gpu_fallback_on_the_file_it_hit() {
+ if !lightcraft_gpu::available() {
+ lightcraft_testkit::skip!(Gpu, "no GPU adapter ({})", lightcraft_gpu::unavailable_reason().unwrap_or_default());
+ return;
+ }
+ let mut s = crate::Session::with_demo();
+ let ids: Vec<_> = s.visible().iter().copied().take(2).collect();
+ let o = ExportOptions::from_json(&json!({"format": "png", "width": 64}));
+ // one lane: both photos render on this thread, and the fault hits the first render here
+ lightcraft_gpu::inject_fault(lightcraft_gpu::Fault::Limit(1 << 10));
+ let (files, _, _) = lanes_batch(&mut s, &ids, &o, 1, true, usize::MAX);
+ let files = files.unwrap();
+ assert_eq!(files.len(), 2, "{files:?}");
+ let why: Vec<_> = files.iter().filter_map(|f| f.get("gpuFallback").and_then(serde_json::Value::as_str)).collect();
+ assert_eq!(why.len(), 1, "exactly one file fell back: {files:?}");
+ assert!(why[0].contains("limit"), "{files:?}");
+ assert!(files[1].get("gpuFallback").is_none(), "the second render was fine: {files:?}");
+ assert!(lightcraft_gpu::available(), "a limit is no device failure");
+}
+
+// Issue #496: photos rendered side by side give the same files, names, order and progress as
+// Render to DNG: the rendered photo as a linear float DNG that reads back as the same picture
+#[test]
+fn rendered_dng_matches_the_rendered_tiff() {
+ let mut s = crate::Session::with_demo();
+ let id = s.visible()[0];
+ let dng = export_photo(&mut s, id, &ExportOptions::from_json(&json!({"format": "rendereddng", "width": 64})), 1).unwrap();
+ assert!(dng.file_name.ends_with(".dng"), "{}", dng.file_name);
+ let png = export_photo(&mut s, id, &ExportOptions::from_json(&json!({"format": "png", "width": 64})), 1).unwrap();
+ let raw = lightcraft_raw::decode(&dng.bytes).unwrap();
+ assert_eq!((raw.width, raw.height, raw.cpp), (dng.width, dng.height, 3));
+ assert!(raw.color.profile.tone_curve.is_some(), "identity tone curve keeps converters from adding one");
+ let back = raw.develop(lightcraft_raw::Method::Bilinear).unwrap();
+ let reference = lightcraft_codecs::decode_thumbnail(&png.bytes, 4096).unwrap().image;
+ assert_eq!((reference.width, reference.height), (back.width, back.height));
+ // mean brightness: the PNG holds 8-bit sRGB, the DNG linear sRGB
+ let mean_dng: f32 = back.data.iter().map(|p| lightcraft_color::transfer::linear_to_srgb(p[1].min(1.0))).sum::<f32>() / back.data.len() as f32;
+ let mean_tif: f32 = reference.data.iter().map(|p| p[1] as f32 / 255.0).sum::<f32>() / reference.data.len() as f32;
+ assert!((mean_dng - mean_tif).abs() < 0.02, "{mean_dng} vs {mean_tif}");
+}
+
+// one at a time, and a cancel stops at the same photo
+#[test]
+fn side_by_side_batches_match_one_at_a_time() {
+ let mut s = crate::Session::with_demo();
+ let ids: Vec<_> = s.visible().iter().copied().take(5).collect();
+ // one name for all: the Unique numbering follows the order the files are placed in
+ let o = ExportOptions::from_json(&json!({"format": "png", "width": 40, "naming": "same"}));
+ let (files, written, seen) = lanes_batch(&mut s, &ids, &o, 1, true, usize::MAX);
+ let files = files.unwrap();
+ let paths: Vec<_> = written.iter().map(|(p, _)| p.clone()).collect();
+ assert_eq!(paths, ["out/same.png", "out/same-2.png", "out/same-3.png", "out/same-4.png", "out/same-5.png"]);
+ let heights: std::collections::HashSet<_> = files.iter().map(|f| f["height"].as_u64()).collect();
+ assert!(heights.len() > 1, "photos of different shapes show the order: {files:?}");
+ for lanes in [2, 3, 8] {
+ let (f, w, sn) = lanes_batch(&mut s, &ids, &o, lanes, true, usize::MAX);
+ assert_eq!(shape(&f.unwrap()), shape(&files), "{lanes} lanes");
+ assert_eq!(w.iter().map(|(p, _)| p.clone()).collect::<Vec<_>>(), paths, "{lanes} lanes");
+ assert_eq!(sn, seen, "{lanes} lanes");
+ }
+ let (f, w, sn) = lanes_batch(&mut s, &ids, &o, 3, true, 2);
+ assert_eq!(shape(&f.unwrap()), shape(&files[..2]));
+ assert_eq!((w.len(), sn.len()), (2, 3), "photos past the cancel are never written");
+}
+
+// A panic in `progress` while lanes run must end the batch (the lanes stop waiting), not hang it
+#[test]
+fn a_panic_in_progress_does_not_hang_the_lanes() {
+ let mut s = crate::Session::with_demo();
+ let ids: Vec<_> = s.visible().iter().copied().take(5).collect();
+ let o = ExportOptions::from_json(&json!({"format": "png", "width": 40}));
+ let items = prepare_batch(&mut s, &ids, &o).unwrap();
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let to = Destination { dir: "out".into(), exact: None };
+ let mut write = |_: &str, _: &[u8]| Ok(());
+ let mut calls = 0;
+ let mut progress = |_: usize, _: &str| {
+ calls += 1;
+ assert!(calls < 2, "progress panics on its second call");
+ true
+ };
+ let r =
+ crate::guard::catch("test batch", || run_batch_with(items, &mut Placer::new(&o, &to, &mut write, &|_| false, true), &mut progress, 2));
+ tx.send(r.and_then(|r| r)).ok();
+ });
+ let r = rx.recv_timeout(std::time::Duration::from_secs(60));
+ assert!(matches!(r, Ok(Err(_))), "the batch returns an error instead of hanging: {r:?}");
+}
+
+// A photo that fails is reported in its place while the others are exported; with
+// stop_on_error the batch ends there and nothing after it is written
+#[test]
+fn side_by_side_batches_report_failures_in_order() {
+ use lightcraft_catalog::{Op, Photo, PhotoId, Source};
+ let mut s = crate::Session::with_demo();
+ let mut ids: Vec<_> = s.visible().iter().copied().take(3).collect();
+ let gone = Photo::new(PhotoId(9_496), Source::File { path: "no/such/dir/gone.jpg".into() }, "gone.jpg", "JPEG", 600, 400, "2026-10-09T00:00:00");
+ s.catalog.apply(Op::AddPhoto { photo: Box::new(gone) }).unwrap();
+ ids.insert(1, PhotoId(9_496));
+ let o = ExportOptions::from_json(&json!({"format": "jpeg", "width": 40}));
+ let (files, written, _) = lanes_batch(&mut s, &ids, &o, 3, false, usize::MAX);
+ let files = files.unwrap();
+ assert_eq!(files.len(), 4);
+ assert_eq!((files[1]["photo"].as_u64(), files[1]["file"].as_str()), (Some(9_496), Some("gone.jpg")), "{files:?}");
+ assert!(files[1]["error"].is_string());
+ assert!([0, 2, 3].iter().all(|&i| files[i]["path"].is_string()), "{files:?}");
+ assert_eq!(written.len(), 3);
+ let one = lanes_batch(&mut s, &ids, &o, 1, false, usize::MAX).0.unwrap();
+ assert_eq!(shape(&files), shape(&one));
+
+ let (r, written, _) = lanes_batch(&mut s, &ids, &o, 3, true, usize::MAX);
+ assert!(r.is_err());
+ assert_eq!(written.len(), 1, "only the photo before the failure");
+}
+
+#[test]
+fn export_weights_follow_the_source_and_output_sizes() {
+ use crate::media::SourceLevel;
+ let mb = |b: usize| b >> 20;
+ // a full-size 24 MP export (measured peak ~1.2 GB)
+ assert_eq!(mb(render_weight(6000 * 4000, 6000, SourceLevel::Full, 6000 * 4000)), 1098);
+ // 2048 px from the 2560 px preview (measured ~150 MB)
+ assert_eq!(mb(render_weight(6000 * 4000, 6000, SourceLevel::Preview, 2048 * 1365)), 145);
+ // a photo smaller than the preview level is its own source
+ assert_eq!(render_weight(1000 * 500, 1000, SourceLevel::Preview, 0), 1000 * 500 * 12);
+ assert_eq!(render_weight(0, 0, SourceLevel::Full, 0), 0);
+ assert!(render_weight(usize::MAX, 1, SourceLevel::Full, usize::MAX) > 0, "no overflow");
+}
diff --cc crates/ui-egui/src/dialogs.rs
index 646288220,000000000..c9cb13cf6
mode 100644,000000..100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -1,1846 -1,0 +1,1857 @@@
+//! Modal dialogs (new album, rename, create preset, choose settings to copy, export, about, shortcuts).
+
+use lightcraft_develop::{ControlSpec, Section, SettingsGroup, Track};
+use serde_json::json;
+
+use crate::LightcraftApp;
+use crate::state::Dialog;
+use crate::theme::Tokens;
+use lightcraft_engine::export::{ExportOptions, Resize};
+
+mod confirm;
+mod cull;
+mod export;
+mod frame;
+mod rename;
+mod sam_model;
+
+pub(crate) use confirm::album_entries;
+pub use confirm::confirm_dialog;
+pub use cull::{MAX_BURST_GAP, clamp_cull_burst, cull_params, fmt_gap, parse_gap};
+use export::{
+ LIMIT_KB, QUALITY, START_NUMBER, WM_IMAGE_WIDTH, WM_INSET_X, WM_INSET_Y, WM_OPACITY, WM_POSITIONS, WM_SIZE, export_dialog_params, export_size,
- group_checklist, watermark_preview,
++ group_checklist, preset_lzw_note, tiff_lzw_note, watermark_preview,
+};
+pub use frame::{ConfirmStyle, confirm_style, list_height, prompt};
+use frame::{
+ DIALOG_CHROME_GUESS, DIALOG_MIN_BODY, DIALOG_SCREEN_MARGIN, choices, clicked_backdrop, dialog_body, dialog_field, field, just_opened, num,
+ only_shows, return_confirms, trailing_button_row,
+};
+pub(crate) use rename::rename_preview;
+use rename::{RENAME_PREVIEW_ROWS, person_rename_plan};
+pub(crate) use sam_model::show_model_folder;
+use sam_model::{sam_by_hand, sam_model_body};
+use slideshow_export::slideshow_export_body;
+
+pub mod credits;
+pub mod faces;
+pub mod import;
+pub mod keymap;
+pub mod lightroom_destination;
+pub mod merge;
+pub mod print_view;
+pub mod rules_editor;
+pub mod settings;
+pub mod slideshow_export;
+pub mod updates_ui;
+
+/// About dialog tabs: (widget id suffix, label). The credits come from `crate::credits`.
+pub const ABOUT_TABS: &[(&str, &str)] = &[("about", "About"), ("contributors", "Contributors"), ("models", "Models")];
+
+/// Help ▸ What's New (docs/whats-new.md).
+pub const WHATS_NEW: &str = include_str!("../../../docs/whats-new.md");
+
+/// The import review and Settings keep window ids of their own, so the size each is given
+/// doesn't carry over to the other dialogs.
+fn window_id(dialog: &Dialog) -> egui::Id {
+ egui::Id::unique(match dialog {
+ Dialog::Import { .. } => "lightcraft-import-dialog",
+ Dialog::Print => "lightcraft-print-dialog",
+ Dialog::Settings { .. } => "lightcraft-settings-dialog",
+ _ => "lightcraft-dialog",
+ })
+}
+
+/// Block the underlying panels from the first frame, before the window establishes its modal
+/// layer. Close background menus on entry; popups subsequently opened inside the dialog stay usable.
+pub(crate) fn prepare(app: &LightcraftApp, ui: &mut egui::Ui) {
+ let Some(dialog) = &app.ui.dialog else { return };
+ ui.disable();
+ let layer = egui::LayerId::new(egui::Order::Middle, window_id(dialog));
+ if ui.ctx().memory(|m| m.top_modal_layer()) != Some(layer) {
+ egui::Popup::close_all(ui.ctx());
+ }
+}
+
+/// Draw the open dialog. `blocked` is true when a quit prompt or settings notice was on screen at
+/// the start of this frame: the dialog is still drawn (its state is preserved), but none of its raw
+/// keyboard/backdrop handling may act. The caller freezes `blocked` for the whole frame so the
+/// click or key that dismisses the prompt cannot also reach the dialog drawn after it. The
+/// blocking library-problem/launch-list window gets the same raw-input treatment while it is
+/// actually on screen over this dialog; ordinary dialogs without that window keep their normal
+/// Escape and outside-click behaviour.
+pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) {
+ let Some(mut dlg) = app.ui.dialog.clone() else { return };
+ let at_start = dlg.clone();
+ let library_blocks = crate::panels::library_problem::blocks_dialog_input(app);
+ let raw_blocked = blocked || library_blocks;
+ // Esc with a popup open in the dialog (a dropdown, a date picker's calendar) closes the popup
+ // only: claimed before the dialog is drawn, since the popup is gone once it has handled the key
+ if !raw_blocked && ctx.input(|i| i.key_pressed(egui::Key::Escape)) && egui::Popup::is_any_open(ctx) {
+ crate::widgets::take_escape(ctx);
+ }
+ let t = Tokens::get(ctx);
+ let screen = ctx.content_rect();
+ // The backdrop is an area below the dialog window (a bare `Middle` layer painter would be
+ // painted after every area — i.e. over the dialog too).
+ egui::Area::new(egui::Id::unique("dialog-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(false).show(ctx, |ui| {
+ ui.painter().rect_filled(screen, 0.0, egui::Color32::from_black_alpha(140));
+ });
+ let mut close = false;
+ let mut confirm = false;
+ // Return presses OK in a dialog without a text field of its own (Lightroom's default button);
+ // a widget that has the keyboard focus (a text field, a button or checkbox reached with Tab)
+ // takes Return itself. Consumed before the dialog is drawn, so nothing else sees it too.
+ if !raw_blocked
+ && return_confirms(&dlg)
+ && ctx.memory(|m| m.focused().is_none())
+ && !egui::Popup::is_any_open(ctx)
+ && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))
+ {
+ confirm = true;
+ }
+ let title = dialog_title(app, &dlg);
+ let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(16, 12));
+ // The import review can be resized (its photo grid takes the room); it keeps a window id of its
+ // own so the size it is given doesn't carry over to the other dialogs. Its content scrolls
+ // rather than growing the window when the options below the grid get taller (e.g. Copy).
+ let import = matches!(dlg, Dialog::Import { .. });
+ // The Print dialog sizes itself to the window and scrolls its settings column on its own.
+ let print = matches!(dlg, Dialog::Print);
+ let window_id = window_id(&dlg);
+ // Every other dialog fits the window (#781): its options scroll when they don't, and the title
+ // bar and the button row stay outside the scroll area. The room they take is measured on the
+ // previous frame (a guess on the first one).
+ let chrome_id = window_id.with("chrome");
+ let chrome = ctx.data(|d| d.get_temp::<f32>(chrome_id)).unwrap_or(DIALOG_CHROME_GUESS);
+ // Settings keeps its top edge, and the widest it has been, while tabs of different sizes are shown, so its tab
+ // row stays where it is (centred like the others, the row jumped with each tab's height)
+ let settings = matches!(dlg, Dialog::Settings { .. });
+ let top = (screen.height() * 0.08).clamp(DIALOG_SCREEN_MARGIN, 96.0);
+ let body_max =
+ if settings { screen.height() - top - DIALOG_SCREEN_MARGIN - chrome } else { screen.height() - 2.0 * DIALOG_SCREEN_MARGIN - chrome }
+ .max(DIALOG_MIN_BODY);
+ let widest_id = window_id.with("widest");
+ let widest = if settings { ctx.data(|d| d.get_temp::<f32>(widest_id)).unwrap_or(0.0).min(screen.width() * 0.9) } else { 0.0 };
+ let mut content_w = 0.0f32;
+ let mut body_h = None;
+ // before the window: drawing it closes a dropdown the click lands outside of
+ let popup_was_open = egui::Popup::is_any_open(ctx);
+ let shown = egui::Window::new(crate::i18n::tr(&title))
+ .id(window_id)
+ .collapsible(false)
+ .resizable(import)
+ .vscroll(import)
+ .resize(|r| if import { r.default_height(crate::import::DIALOG_SIZE[1]) } else { r })
+ .frame(frame)
+ .anchor(if settings { egui::Align2::CENTER_TOP } else { egui::Align2::CENTER_CENTER }, [0.0, if settings { top } else { 0.0 }])
+ .min_width(widest)
+ .default_width(match dlg {
+ Dialog::Import { .. } => crate::import::DIALOG_SIZE[0],
+ Dialog::SmartRules { .. } => 680.0,
+ Dialog::AllMetadata { .. } => 620.0,
+ Dialog::Print => 1100.0,
+ Dialog::FaceModel { .. } => 460.0,
+ Dialog::LightroomCatalog { .. } => 440.0,
+ Dialog::LightroomDestination { .. } => 480.0,
+ Dialog::ManageEffects { .. } => 560.0,
+ _ => 380.0,
+ })
+ .show(ctx, |ui| {
+ // Disabled, not skipped: the dialog keeps its layout and state, but a raw event in the
+ // first prompt frame cannot toggle a checkbox or press a button underneath it. The
+ // blocking library window gets the same treatment: it owns input while it is on screen,
+ // so the dialog behind it must not take focus or accept typed text either.
+ if raw_blocked {
+ ui.disable();
+ }
+ ui.spacing_mut().item_spacing.y = 8.0;
+ body_h = dialog_body(ui, (!import && !print).then_some(title.as_str()), body_max, |ui| {
+ dialog_content(app, ui, &t, body_max, &mut confirm, &mut dlg)
+ });
+ ui.add_space(4.0);
+ // the confirm on the right with Cancel to its left (macOS and GNOME's order), filled with
+ // the accent when it is the dialog's primary action. The row spans the width the window
+ // gives its content this frame (its default width, or its content's if wider), so it
+ // reaches the edge without widening the window.
+ let row_w = ui.available_width().max(ui.min_rect().width()).max(1.0);
+ let row_h = ui.spacing().interact_size.y;
+ ui.allocate_ui_with_layout(egui::vec2(row_w, row_h), egui::Layout::left_to_right(egui::Align::Center), |ui| {
+ button_row(app, ui, &dlg, &mut close, &mut confirm);
+ });
+ if import {
+ crate::import::note_dialog_bottom(ui);
+ }
+ content_w = ui.min_rect().width();
+ });
+ if settings && content_w > widest + 0.5 {
+ ctx.data_mut(|d| d.insert_temp(widest_id, content_w));
+ }
+ if let Some(w) = &shown {
+ // (the import review keeps its hand-picked photos however the click lands)
+ if !raw_blocked && app.ui.settings.close_dialogs_outside && !import && clicked_backdrop(ctx, w.response.rect, popup_was_open) {
+ close = true;
+ } else if raw_blocked {
+ // A press made under the prompt or library window must not be remembered as a
+ // backdrop press for a release that arrives after that covering window goes away.
+ ctx.data_mut(|d| d.remove_temp::<bool>(egui::Id::unique("dialog-backdrop-press")));
+ }
+ }
+ if let Some(w) = shown {
+ ctx.memory_mut(|m| m.set_modal_layer(w.response.layer_id));
+ if let Some(body_h) = body_h {
+ let measured = (w.response.rect.height() - body_h).max(0.0);
+ if (measured - chrome).abs() > 0.5 {
+ ctx.data_mut(|d| d.insert_temp(chrome_id, measured));
+ ctx.request_repaint();
+ }
+ }
+ ctx.move_to_top(w.response.layer_id);
+ crate::widgets::register_response("dialog:window", w.response.rect, &w.response);
+ }
+ // (while the shortcuts editor records a key, it takes Esc itself to cancel; an open popup in
+ // the dialog, such as a date picker's calendar, takes it to close itself)
+ if !raw_blocked && ctx.input(|i| i.key_pressed(egui::Key::Escape)) && !crate::widgets::escape_taken(ctx) {
+ close = true;
+ }
+ if !raw_blocked && confirm {
+ close |= confirmed(app, ctx, &mut dlg);
+ }
+ // a dialog opened from inside this one (a button in Settings that shows a licence) takes its place
+ if app.ui.dialog.as_ref().is_some_and(|now| *now != at_start) {
+ return;
+ }
+ if !close && !blocked {
+ let frame = ctx.cumulative_frame_nr();
+ ctx.data_mut(|d| d.insert_temp(egui::Id::unique(BACKDROP_SHOWN), frame));
+ }
+ app.ui.dialog = if close { None } else { Some(dlg) };
+}
+
+/// The title of a dialog.
+fn dialog_title(app: &LightcraftApp, dlg: &Dialog) -> String {
+ match dlg {
+ Dialog::TextPrompt { title, .. } => title.as_str(),
+ Dialog::NewAlbum { folder: true, .. } => "Create Folder",
+ Dialog::NewAlbum { .. } => "Create Album",
+ Dialog::RenameAlbum { .. } => "Rename Album",
+ Dialog::Rename { .. } => "Rename Photos",
+ Dialog::Import { .. } => "Import Photos",
+ Dialog::LightroomResult { .. } => "Lightroom Catalog Import",
+ Dialog::LabelNames { .. } => "Edit Color Label Names",
+ Dialog::CaptureTime { .. } => "Edit Capture Time",
+ Dialog::RenameKeyword { .. } => "Rename Keyword",
+ Dialog::RenamePerson { .. } => "Rename Person",
+ Dialog::KeywordTag { editing: None, .. } => "Create Keyword Tag",
+ Dialog::KeywordTag { .. } => "Edit Keyword Tag",
+ Dialog::DeleteKeyword { .. } => "Delete Keyword",
+ Dialog::MoveKeyword { .. } => "Merge Keywords",
+ Dialog::KeywordSet { .. } => "Edit Keyword Set",
+ Dialog::MergeKeywords { .. } => "Merge Keywords",
+ Dialog::NewSmartAlbum { .. } => "Create Smart Album",
+ Dialog::AllMetadata { .. } => "All Metadata",
+ Dialog::SystemInfo { .. } => "System Info",
+ Dialog::DenoiseModel { .. } => "AI Denoise Model",
+ Dialog::FaceModel { info, .. } if info["download"].is_string() => "Download Face Model",
+ Dialog::FaceModel { .. } => "Add Face Model",
+ Dialog::WhatsNew => "What's New",
+ Dialog::Cull { .. } => "Assisted Culling",
+ Dialog::SmartRules { id: None, .. } => "New Smart Album",
+ Dialog::SmartRules { .. } => "Edit Smart Album",
+ Dialog::AutoStack { .. } => "Auto-Stack by Capture Time",
+ Dialog::CreatePreset { .. } => "Create Preset",
+ Dialog::CopySettings { .. } => "Choose Edit Settings to Copy",
+ Dialog::PasteSettings { .. } => "Paste Selected Settings",
+ Dialog::Export { .. } => "Export",
+ Dialog::ContactSheet { .. } => "Contact Sheet PDF",
+ Dialog::SlideshowExport { .. } => "Export Slideshow",
+ Dialog::Print => "Print",
+ Dialog::Merge { opts } => opts.title(),
+ Dialog::Settings { .. } => "Settings",
+ Dialog::ConfirmDelete { .. } => "Delete Photos",
+ Dialog::MovePhotos { .. } => "Move Photos",
+ Dialog::LightroomCatalog { .. } => "Lightroom Classic Catalog",
+ Dialog::LightroomDestination { .. } => "Import Lightroom Catalog",
+ Dialog::SaveEffect { .. } => "New Effect Preset",
+ Dialog::ManageEffects { .. } => "Manage Effect Presets",
+ Dialog::DeleteEffects { names } if names.len() == 1 => "Delete Effect Preset",
+ Dialog::DeleteEffects { .. } => "Delete Effect Presets",
+ Dialog::RemoveFolder { disk: true, .. } => "Remove Disk from Library",
+ Dialog::RemoveFolder { .. } => "Remove Folder from Library",
+ Dialog::SynchronizeFolder { .. } => "Synchronize Folder",
+ // (nothing to download from in this build: the dialog explains the manual install)
+ Dialog::SamModel { .. } if sam_by_hand(&app.session.segmenter) => "Install the SAM 3 Model",
+ Dialog::SamModel { .. } => "Download the SAM 3 Model?",
+ Dialog::About => "About LightCraft",
+ Dialog::Shortcuts => "Keyboard Shortcuts",
+ Dialog::ViewOptions => "View Options",
+ }
+ .to_string()
+}
+
+/// Whether a dialog only shows something: a model file LightCraft cannot use has nothing to confirm, nor has a
+/// dialog that only shows something (one Close, no Cancel / OK).
+fn is_informational(dlg: &Dialog) -> bool {
+ let unusable_model = matches!(dlg, Dialog::DenoiseModel { info, .. } | Dialog::FaceModel { info, .. } if info["kind"] == "unsupported");
+ unusable_model || matches!(dlg, Dialog::LightroomResult { first: None, .. }) || only_shows(dlg)
+}
+
+/// What the SAM 3 download looks like: installed, running, failed, and whether there is nowhere to download from.
+struct SamState {
+ installed: bool,
+ running: bool,
+ failed: bool,
+ /// no download location in this build: nothing to offer but the manual install
+ by_hand: bool,
+}
+
+impl SamState {
+ fn of(app: &LightcraftApp) -> Self {
+ let sam = &app.session.segmenter;
+ SamState {
+ installed: sam.installed(),
+ running: sam.download_status().running,
+ failed: sam.download_status().error.is_some(),
+ by_hand: sam_by_hand(sam),
+ }
+ }
+}
+
+/// The label of a dialog's cancel button.
+fn cancel_label(dlg: &Dialog, sam: &SamState) -> &'static str {
+ match dlg {
+ Dialog::SamModel { .. } if sam.running || sam.installed || sam.by_hand => "Close",
+ Dialog::SamModel { .. } => "Not Now",
+ Dialog::LightroomResult { .. } => "Close",
+ _ => "Cancel",
+ }
+}
+
+/// The label of a dialog's confirm button (empty: it has none).
+fn ok_label(app: &LightcraftApp, dlg: &Dialog, informational: bool, sam: &SamState) -> String {
+ let label = match dlg {
+ Dialog::Import { opts } => {
+ let n = opts.selected_paths().len();
+ let verb = if opts.copy && opts.move_files { "Move" } else { "Import" };
+ return crate::i18n::tr_format!("{verb} {n} Photo{}", if n == 1 { "" } else { "s" }, verb = crate::i18n::tr(verb), n = n);
+ }
+ Dialog::LightroomResult { first: Some(_), .. } => "Show in Library",
+ Dialog::ContactSheet { .. } => "Choose PDF…",
+ Dialog::SlideshowExport { .. } => "Export…",
+ Dialog::Print => "Print to PDF…",
+ Dialog::Merge { .. } => "Merge",
+ Dialog::DenoiseModel { info, .. } if info["download"].is_string() => "Accept & Download",
+ Dialog::DenoiseModel { .. } => "Install",
+ Dialog::FaceModel { info, .. } if !informational && info["download"].is_string() => "Download",
+ Dialog::FaceModel { .. } if !informational => "Install",
+ Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } => "Delete",
+ Dialog::SaveEffect { .. } => "Create",
+ Dialog::MovePhotos { .. } => "Move",
+ // (not "Merge": that is photo merging, HDR / panorama, in some languages)
+ Dialog::MoveKeyword { .. } => "Merge Keywords",
+ Dialog::KeywordSet { .. } => "Save",
+ Dialog::KeywordTag { editing: None, .. } => "Create",
+ Dialog::KeywordTag { .. } => "Save",
+ Dialog::RemoveFolder { .. } => "Remove",
+ Dialog::LightroomCatalog { .. } => "Import Lightroom Catalog…",
+ d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::ok_label(d),
+ Dialog::SynchronizeFolder { .. } if informational => "Close",
+ Dialog::SynchronizeFolder { .. } => "Synchronize",
+ Dialog::SamModel { .. } => return sam_ok_label(dlg, sam).to_string(),
+ Dialog::RenamePerson { from, to, .. } if person_rename_plan(&app.session.catalog, from, to).needs_merge => "Merge",
+ _ if informational => "Close",
+ _ => "OK",
+ };
+ label.to_string()
+}
+
+/// The label of the SAM 3 dialog's confirm button.
+fn sam_ok_label(dlg: &Dialog, sam: &SamState) -> &'static str {
+ match dlg {
+ Dialog::SamModel { then: Some(_), .. } if sam.installed => "Continue",
+ Dialog::SamModel { .. } if sam.installed || sam.running || sam.by_hand => "",
+ Dialog::SamModel { error, .. } if error.is_some() || sam.failed => "Try Again",
+ _ => "Download",
+ }
+}
+
+/// Whether the confirm button works: installing waits for the licence to be accepted (and Synchronize waits for the
+/// scan), a rename waits for its conflicts to be settled, smart-album rules that can't mean anything wait to be fixed.
+fn can_confirm(app: &LightcraftApp, dlg: &Dialog, informational: bool) -> bool {
+ let rename_blocked = match dlg {
+ Dialog::RenamePerson { from, to, merge } => {
+ let plan = person_rename_plan(&app.session.catalog, from, to);
+ plan.block.is_some() || (plan.needs_merge && !*merge)
+ }
+ _ => false,
+ };
+ let waiting = matches!(
+ dlg,
+ Dialog::DenoiseModel { accepted: false, .. } | Dialog::FaceModel { accepted: false, .. } | Dialog::SynchronizeFolder { counts: None, .. }
+ );
+ let bad_rules =
+ matches!(dlg, Dialog::SmartRules { id, rules, .. } if !rules.check_for(&app.session.catalog, id.map(lightcraft_catalog::AlbumId)).is_empty());
+ !rename_blocked && (informational || (!waiting && !bad_rules))
+}
+
+/// The row of buttons under a dialog: Cancel and the confirm; `close` and `confirm` are set when one is clicked.
+fn button_row(app: &LightcraftApp, ui: &mut egui::Ui, dlg: &Dialog, close: &mut bool, confirm: &mut bool) {
+ let informational = is_informational(dlg);
+ let sam = SamState::of(app);
+ let cancel = cancel_label(dlg, &sam);
+ let ok = ok_label(app, dlg, informational, &sam);
+ let ok = ok.as_str();
+ let can_confirm = can_confirm(app, dlg, informational);
+ let primary = !informational && can_confirm && confirm_style(dlg) == ConfirmStyle::Primary;
+ use crate::button::{Button, Kind};
+ // (each kind of dialog its own buttons: the keyboard's place doesn't carry from a
+ // dialog to the one it opens)
+ let kind = std::mem::discriminant(dlg);
+ let cancel_button = Button::new(cancel).widget("button:dialogCancel").id_salt(kind).min_width(72.0);
+ let ok_button = Button::new(ok)
+ .kind(if primary { Kind::Primary } else { Kind::Secondary })
+ .enabled(can_confirm)
+ .widget("button:dialogOk")
+ .id_salt(kind)
+ .min_width(72.0);
+ // (Cancel first, then the confirm: the keyboard goes through them as the eye does)
+ let gap = ui.spacing().item_spacing.x;
+ let mut buttons_w = 0.0;
+ if !informational {
+ buttons_w += cancel_button.desired_size(ui).x + gap;
+ }
+ if !ok.is_empty() {
+ buttons_w += ok_button.desired_size(ui).x;
+ }
+ ui.add_space((ui.available_width() - buttons_w).max(0.0));
+ if !informational && cancel_button.show(ui).clicked() {
+ *close = true;
+ }
+ let r = (!ok.is_empty()).then(|| ok_button.show(ui));
+ if r.is_some_and(|r| r.clicked()) {
+ if informational {
+ *close = true;
+ } else {
+ *confirm = true;
+ }
+ }
+}
+
+/// The dialog's confirm was pressed: do it. Whether the dialog closes.
+fn confirmed(app: &mut LightcraftApp, ctx: &egui::Context, dlg: &mut Dialog) -> bool {
+ let mut closed = false;
+ match confirm_dialog(app, dlg) {
+ // the import review stays open on an error (e.g. an unusable folder template), and so
+ // does Export (e.g. no folder chosen) so the choices aren't lost, and Edit Capture Time
+ // (a time that isn't a date, or a shift it refuses)
+ Err(e)
+ if matches!(
+ dlg,
+ Dialog::Import { .. }
+ | Dialog::Export { .. }
+ | Dialog::ContactSheet { .. }
+ | Dialog::SlideshowExport { .. }
+ | Dialog::Print
+ | Dialog::NewAlbum { .. }
+ | Dialog::NewSmartAlbum { .. }
+ | Dialog::SmartRules { .. }
+ | Dialog::KeywordTag { .. }
+ | Dialog::KeywordSet { .. }
+ | Dialog::SynchronizeFolder { .. }
+ | Dialog::SaveEffect { .. }
+ | Dialog::CaptureTime { .. }
+ ) =>
+ {
+ app.toast(ctx, e)
+ }
+ // the SAM 3 dialog stays open to show the download (or why it can't start)
+ Err(e) if matches!(dlg, Dialog::SamModel { .. }) => {
+ if let Dialog::SamModel { error, .. } = dlg {
+ *error = Some(e);
+ }
+ }
+ Ok(r) if matches!(dlg, Dialog::NewAlbum { .. }) && r.get("skipped").and_then(serde_json::Value::as_u64).is_some_and(|n| n > 0) => {
+ // albums hold library photos (issue #684): say which part of the selection stayed out
+ crate::panels::grid::toast_skipped(app, ctx, &r);
+ closed = true;
+ }
+ // a move says how it went, or why nothing moved
+ Ok(r) if matches!(dlg, Dialog::MovePhotos { .. }) => {
+ if let Dialog::MovePhotos { name, .. } = dlg {
+ let text = crate::panels::left::moved_text(r["moved"].as_u64().unwrap_or(0), name);
+ app.toast(ctx, text);
+ }
+ closed = true;
+ }
+ Err(e) if matches!(dlg, Dialog::MovePhotos { .. }) => {
+ app.toast(ctx, e);
+ closed = true;
+ }
+ // photos whose capture time doesn't read are left as they were: say so
+ Ok(r) if matches!(dlg, Dialog::CaptureTime { .. }) && r["unreadable"].as_u64().is_some_and(|n| n > 0) => {
+ app.toast(ctx, crate::i18n::tr("Photos whose capture time can't be read were left as they were"));
+ closed = true;
+ }
+ // where a Lightroom catalog goes: stays open to be corrected (a folder that isn't
+ // empty), unless the library it names has gone
+ Err(e) if matches!(dlg, Dialog::LightroomDestination { .. }) => {
+ closed = !crate::lightroom_destination::keeps_open_on_error(app, dlg);
+ app.toast(ctx, e);
+ }
+ Ok(_) if keeps_open(app, dlg) => {
+ if let Dialog::SamModel { error, .. } = dlg {
+ *error = None;
+ }
+ }
+ _ => closed = true,
+ }
+
+ closed
+}
+
+/// The last frame a dialog was drawn and stayed open, for [`clicked_backdrop`].
+const BACKDROP_SHOWN: &str = "dialog-backdrop-shown";
+
+/// Whether a dialog stays open after its action succeeded (the SAM 3 dialog while the model
+/// downloads).
+pub fn keeps_open(app: &LightcraftApp, dlg: &Dialog) -> bool {
+ matches!(dlg, Dialog::SamModel { .. }) && !app.session.segmenter.installed()
+}
+
+/// The body of the AutoStack dialog.
+fn auto_stack_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::AutoStack { gap } = dlg else { return };
+ ui.label(egui::RichText::new(crate::i18n::tr("Stack photos taken within this time of each other:")).color(t.text_label));
+ let r = ui.add(
+ egui::Slider::new(gap, 0.0..=86400.0)
+ .logarithmic(true)
+ .smallest_positive(1.0)
+ .custom_formatter(|v, _| crate::panels::dialogs::fmt_gap(v))
+ .custom_parser(crate::panels::dialogs::parse_gap),
+ );
+ crate::widgets::named(r, crate::i18n::tr("Stack photos taken within this time of each other:"));
+ let preview = app.session.execute("stack.auto", &json!({"gap": *gap, "preview": true})).unwrap_or_default();
+ let scope = if app.session.selection.ids.len() > 1 { "the selected photos" } else { "the photos in view" };
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!(
+ "Creates {} stacks from {} of {scope}",
+ preview["stacks"],
+ preview["photos"],
+ scope = crate::i18n::tr(scope)
+ ))
+ .color(t.text_dim),
+ );
+}
+
+/// The body of the Cull dialog.
+fn cull_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::Cull { reject_below, pick_best, burst_gap, similarity } = dlg else { return };
+ let n = app.session.selection.ids.len();
+ let scope = if n > 1 {
+ crate::i18n::tr_format!("the {n} selected photos", n = n)
+ } else {
+ crate::i18n::tr_format!("the {} photos in view", app.session.visible_cloned().len())
+ };
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!(
+ "Scores {scope} for focus and exposure and finds similar shots taken within seconds of each other (bursts).",
+ scope = scope
+ ))
+ .color(t.text_label),
+ );
+ ui.add_space(6.0);
+ let r = ui.add(egui::Slider::new(reject_below, 0.0..=80.0).text(crate::i18n::tr("Reject below focus")).step_by(1.0));
+ crate::widgets::register(ui, "field:cullReject", r.rect);
+ ui.label(
+ egui::RichText::new(crate::i18n::tr(if *reject_below > 0.0 {
+ "Blurry photos below the score are flagged as rejects."
+ } else {
+ "0: nothing is rejected."
+ }))
+ .color(t.text_dim),
+ );
+ let r = ui.checkbox(pick_best, crate::i18n::tr("Pick the sharpest photo of each burst"));
+ crate::widgets::register(ui, "check:cullPick", r.rect);
+ ui.add_space(6.0);
+ // the sliders drag over the usual range; their value fields take whatever
+ // `photo.analyze` accepts (a gap of 0 s to a day, a similarity of 0 to 1)
+ let r = ui.add(
+ egui::Slider::new(burst_gap, 1.0..=600.0)
+ .logarithmic(true)
+ .smallest_positive(1.0)
+ .clamping(egui::SliderClamping::Never)
+ .text(crate::i18n::tr("Burst: shots at most this far apart"))
+ .custom_formatter(|v, _| crate::panels::dialogs::fmt_gap(v))
+ .custom_parser(crate::panels::dialogs::parse_gap),
+ );
+ crate::widgets::register(ui, "field:cullGap", r.rect);
+ let r = ui.add(
+ egui::Slider::new(similarity, 0.70..=0.99)
+ .clamping(egui::SliderClamping::Never)
+ .text(crate::i18n::tr("Burst: how alike (loose … strict)"))
+ // a typed 0.995 is kept (whole hundredths would round it to 1.00)
+ .step_by(0.001)
+ .min_decimals(2)
+ .max_decimals(3),
+ );
+ crate::widgets::register(ui, "field:cullSimilar", r.rect);
+ clamp_cull_burst(burst_gap, similarity);
+ ui.label(egui::RichText::new(crate::i18n::tr("Lower it when a panning or moving burst splits into several groups.")).color(t.text_dim));
+ ui.label(
+ egui::RichText::new(crate::i18n::tr("Scores stay on the photos: filter or make smart albums with Focus and Best of Similar Shots."))
+ .color(t.text_dim),
+ );
+}
+
+/// The body of the WhatsNew dialog.
+fn whats_new_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::WhatsNew = dlg else { return };
+ egui::ScrollArea::vertical().max_height(list_height(ui, 460.0)).auto_shrink([false, true]).show(ui, |ui| {
+ for line in WHATS_NEW.lines() {
+ let l = line.trim_end();
+ if let Some(h) = l.strip_prefix("### ") {
+ ui.add_space(6.0);
+ ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(12.5)).color(t.text));
+ } else if let Some(h) = l.strip_prefix("## ") {
+ ui.add_space(8.0);
+ ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(14.0)).color(t.text));
+ } else if l.starts_with("# ") || l.is_empty() {
+ } else if let Some(b) = l.strip_prefix("- ") {
+ ui.label(egui::RichText::new(format!("• {}", crate::i18n::tr(b).replace('`', ""))).color(t.text_label));
+ } else {
+ ui.label(egui::RichText::new(crate::i18n::tr(l.trim()).replace('`', "")).color(t.text_label));
+ }
+ }
+ });
+}
+
+/// The body of the LightroomResult dialog.
+fn lightroom_result_body(ui: &mut egui::Ui, dlg: &mut Dialog) {
+ let Dialog::LightroomResult { summary, library, details, .. } = dlg else { return };
+ ui.label(summary.as_str());
+ ui.add_space(8.0);
+ if let Some(library) = library {
+ ui.label(crate::i18n::tr("Destination library"));
+ ui.add(egui::Label::new(library.as_str()).wrap().selectable(true));
+ ui.label(crate::i18n::tr("Lightroom catalogs import into the open library; no separate catalog folder is created."));
+ } else {
+ ui.label(crate::i18n::tr("These photos are only in memory. Open a library on disk and import the catalog again to save them."));
+ }
+ for detail in details.iter() {
+ ui.add(egui::Label::new(detail).wrap().selectable(true));
+ }
+}
+
+/// The body of the SystemInfo dialog.
+fn system_info_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::SystemInfo { rows } = dlg else { return };
+ egui::Grid::new("sysinfo").num_columns(2).spacing([16.0, 4.0]).striped(true).show(ui, |ui| {
+ for (k, v) in rows.iter() {
+ ui.label(egui::RichText::new(crate::i18n::tr(k)).color(t.text_dim));
+ ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap());
+ ui.end_row();
+ }
+ });
+ if ui.button(crate::i18n::tr("Copy to Clipboard")).clicked() {
+ let text: String = rows.iter().map(|(k, v)| format!("{k}: {v}\n")).collect();
+ ui.ctx().copy_text(text);
+ }
+}
+
+/// The body of the AllMetadata dialog.
+fn all_metadata_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::AllMetadata { title, rows, search } = dlg else { return };
+ ui.label(egui::RichText::new(title.as_str()).color(t.text_label));
+ let r = crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(search).hint_text(crate::i18n::tr("Filter fields")).desired_width(f32::INFINITY)),
+ crate::i18n::tr("Filter fields"),
+ );
+ crate::widgets::register(ui, "field:metadataSearch", r.rect);
+ let q = search.trim().to_lowercase();
+ let keep = |n: &str, v: &str| q.is_empty() || n.to_lowercase().contains(&q) || v.to_lowercase().contains(&q);
+ let mut groups: Vec<(String, Vec<(String, String)>)> = Vec::new();
+ for row in rows["exif"].as_array().into_iter().flatten() {
+ let (g, n, v) = (row["group"].as_str().unwrap_or(""), row["name"].as_str().unwrap_or(""), row["value"].as_str().unwrap_or(""));
+ if !keep(n, v) {
+ continue;
+ }
+ match groups.iter_mut().find(|(x, _)| x == g) {
+ Some((_, list)) => list.push((n.into(), v.into())),
+ None => groups.push((g.into(), vec![(n.into(), v.into())])),
+ }
+ }
+ let xmp: Vec<(String, String)> = rows["xmp"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|r| (r["name"].as_str().unwrap_or("").to_string(), r["value"].as_str().unwrap_or("").to_string()))
+ .filter(|(n, v)| keep(n, v))
+ .collect();
+ if !xmp.is_empty() {
+ groups.push(("XMP".into(), xmp));
+ }
+ egui::ScrollArea::vertical().max_height(list_height(ui, 440.0)).auto_shrink([false, true]).show(ui, |ui| {
+ if groups.is_empty() {
+ ui.label(egui::RichText::new(crate::i18n::tr(rows["note"].as_str().unwrap_or("No metadata found"))).color(t.text_dim));
+ }
+ for (g, list) in &groups {
+ ui.add_space(6.0);
+ ui.label(egui::RichText::new(g).font(t.semibold(12.5)).color(t.text));
+ egui::Grid::new(format!("meta-{g}")).num_columns(2).spacing([16.0, 3.0]).striped(true).show(ui, |ui| {
+ for (n, v) in list {
+ ui.label(egui::RichText::new(n).color(t.text_dim));
+ ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap());
+ ui.end_row();
+ }
+ });
+ }
+ });
+}
+
+/// The body of the SmartRules dialog.
+fn smart_rules_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::SmartRules { id, name, rules, .. } = dlg else { return };
+ let r = crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Name")).desired_width(f32::INFINITY)),
+ crate::i18n::tr("Name"),
+ );
+ crate::widgets::register(ui, "field:smartName", r.rect);
+ ui.add_space(6.0);
+ // the folder an album made from a folder view carries is not in the editor, but it counts
+ let folder = id
+ .and_then(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(id)))
+ .and_then(|a| a.smart.as_deref().and_then(|f| f.library_folder.clone()));
+ // problems, count and albums: cached until the catalog or the rules change (not per frame)
+ let now = (app.session.clock)();
+ let view = app.caches.rules_view(&app.session.catalog, rules, *id, folder, &now);
+ let env = crate::panels::rules_editor::Env { problems: view.problems.clone(), today: now, albums: view.albums.clone() };
+ egui::ScrollArea::vertical().max_height(list_height(ui, 360.0)).auto_shrink([false, true]).show(ui, |ui| {
+ crate::panels::rules_editor::edit(ui, rules, "rules", 0, &[], &env);
+ });
+ let n = view.count;
+ ui.add_space(4.0);
+ if view.problems.is_empty() {
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!(
+ "{n} photo{} match · updates automatically as photos change",
+ if n == 1 { "" } else { "s" },
+ n = n
+ ))
+ .color(t.text_dim),
+ );
+ } else {
+ ui.label(egui::RichText::new(crate::i18n::tr("Fix the marked rules to save this album.")).color(t.caution));
+ }
+}
+
+/// The body of the NewSmartAlbum dialog.
+fn new_smart_album_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, confirm: &mut bool, dlg: &mut Dialog) {
+ let Dialog::NewSmartAlbum { name, .. } = dlg else { return };
+ if dialog_field(ui, "field:smartAlbumName", name, "Name") {
+ *confirm = true;
+ }
+ let rules = app.session.view_rules();
+ // counted when the library or the rules change (or, for "in the last…" rules, the minute), not every frame
+ let now = (app.session.clock)();
+ let minute = if rules.depends_on_now() { now.get(..16).unwrap_or(&now) } else { "" };
+ let n = app.caches.dialog_count(&app.session.catalog, ("smartAlbum", format!("{rules:?}"), minute), || {
+ lightcraft_catalog::rules::set_now(Some(now.clone()));
+ app.session.catalog.query(&rules, &Default::default()).len()
+ });
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!("Matches: {}", crate::i18n::filter_label(&rules, &app.session.catalog))).color(t.text_label),
+ );
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!(
+ "{n} photo{} now · updates automatically as photos change",
+ if n == 1 { "" } else { "s" },
+ n = n
+ ))
+ .color(t.text_dim),
+ );
+}
+
+/// The body of the CaptureTime dialog.
+fn capture_time_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::CaptureTime { mode, time, days, hours, minutes, zone } = dlg else { return };
+ let n = app.session.selected().len();
+ field(ui, "Change", |ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ for (i, (label, m)) in [("Set date & time", "set"), ("Shift by", "shift"), ("Time zone", "zone")].iter().enumerate() {
+ if crate::widgets::text_button(ui, &format!("captureMode-{i}"), label, mode == m).clicked() {
+ *mode = m.to_string();
+ }
+ }
+ });
+ let params = match mode.as_str() {
+ "set" => {
+ field(ui, "New time", |ui| {
+ let r = ui.add(egui::TextEdit::singleline(time).hint_text("2026-09-30 14:05:00").desired_width(f32::INFINITY));
+ crate::widgets::register(ui, "field:captureTime", r.rect);
+ });
+ json!({"time": time})
+ }
+ "shift" => {
+ field(ui, "Shift", |ui| {
+ ui.add(egui::DragValue::new(days).suffix(" d"));
+ ui.add(egui::DragValue::new(hours).suffix(" h"));
+ ui.add(egui::DragValue::new(minutes).suffix(" min"));
+ });
+ json!({"shift": *days as i64 * 86_400 + *hours as i64 * 3600 + *minutes as i64 * 60})
+ }
+ _ => {
+ field(ui, "Hours", |ui| ui.add(egui::DragValue::new(zone).range(-26.0..=26.0).speed(0.25).fixed_decimals(2)));
+ json!({"hours": zone})
+ }
+ };
+ // preview on the active photo (the others move by the same amount)
+ let active = app.session.active().and_then(|id| app.session.catalog.photo(id)).map(|p| (p.file_name.clone(), p.date().to_string()));
+ if let Some((name, cur)) = active {
+ let delta = match mode.as_str() {
+ "set" => lightcraft_catalog::dates::normalize_iso(time)
+ .and_then(|t| Some(lightcraft_catalog::dates::iso_seconds(&t)? - lightcraft_catalog::dates::iso_seconds(&cur)?)),
+ "shift" => params["shift"].as_i64(),
+ _ => Some((*zone as f64 * 3600.0).round() as i64),
+ };
+ // the photo's own time is the problem (a Lightroom catalog's capture time
+ // is copied verbatim), not what was typed
+ let unreadable = lightcraft_catalog::dates::shift_iso(&cur, 0).is_none();
+ let after = match (mode.as_str(), unreadable && n == 1) {
+ // alone, it simply gets the time typed (photo.setCaptureTime repairs it)
+ ("set", true) => lightcraft_catalog::dates::normalize_iso(time),
+ _ => delta.and_then(|d| lightcraft_catalog::dates::shift_iso(&cur, d)),
+ };
+ ui.label(
+ egui::RichText::new(match after {
+ Some(a) => format!("{name}: {} → {}", cur.replace('T', " "), a.replace('T', " ")),
+ None if unreadable && !(mode == "set" && n == 1) => crate::i18n::tr("The active photo's capture time can't be read").to_string(),
+ None => "Enter a date as YYYY-MM-DD HH:MM:SS".into(),
+ })
+ .color(t.text_label),
+ );
+ }
+ if n > 1 {
+ ui.label(egui::RichText::new(crate::i18n::tr_format!("All {n} selected photos move by the same amount.", n = n)).color(t.text_dim));
+ }
+}
+
+/// The body of the LabelNames dialog.
+fn label_names_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::LabelNames { names, save_as } = dlg else { return };
+ names.resize(5, String::new());
+ // start from a set
+ let sets = lightcraft_engine::cmd::manage::label_sets_json(&app.session);
+ field(ui, "Set", |ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ for set in sets["sets"].as_array().into_iter().flatten() {
+ let name = set["name"].as_str().unwrap_or_default();
+ if crate::widgets::text_button(ui, &format!("labelSet-{name}"), name, false).clicked() {
+ *names = set["names"].as_array().into_iter().flatten().map(|n| n.as_str().unwrap_or_default().to_string()).collect();
+ }
+ }
+ });
+ for (i, l) in lightcraft_catalog::ColorLabel::ALL.iter().enumerate() {
+ let colour = format!("{l:?}");
+ field(ui, &colour, |ui| {
+ let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover());
+ ui.painter().circle_filled(r.center(), 6.0, crate::panels::grid::label_color(*l));
+ let te = crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(&mut names[i]).hint_text(colour.as_str()).desired_width(f32::INFINITY)),
+ crate::i18n::tr(&colour),
+ );
+ crate::widgets::register(ui, format!("field:labelName-{}", colour.to_lowercase()), te.rect);
+ });
+ }
+ field(ui, "Save as set", |ui| {
+ let te = crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(save_as).hint_text(crate::i18n::tr("Optional name")).desired_width(f32::INFINITY)),
+ crate::i18n::tr("Save as set"),
+ );
+ crate::widgets::register(ui, "field:labelSetName", te.rect);
+ });
+ ui.label(
+ egui::RichText::new(crate::i18n::tr(
+ "Names appear in the label menu, the filter bar and the Info panel, and are written to XMP. Empty = the colour's name.",
+ ))
+ .color(t.text_dim),
+ );
+}
+
+/// The body of the Rename dialog.
+fn rename_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::Rename { template, start } = dlg else { return };
+ let n = app.session.selected().len();
+ ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim));
+ let template_id = egui::Id::unique("rename-template");
+ let tags_open = field(ui, "Template", |ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ let w = crate::import::tag_field_width(ui);
+ let r = crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(template).id(template_id).hint_text("{name}").desired_width(w)),
+ crate::i18n::tr("Template"),
+ );
+ crate::widgets::register(ui, "field:renameTemplate", r.rect);
+ crate::import::tag_toggle(ui, "renameTemplate")
+ });
+ if tags_open {
+ crate::import::tag_help(ui, "renameTemplate", template, template_id);
+ }
+ crate::import::unknown_tags_warning(ui, template);
+ field(ui, "Presets", |ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ for (i, (label, tpl)) in
+ [("Name", "{name}"), ("Date–Name", "{date}_{name}"), ("Title–Seq", "{title}-{seq:3}"), ("Custom–Seq", "Photo-{seq:3}")].iter().enumerate()
+ {
+ if crate::widgets::text_button(ui, &format!("renamePreset-{i}"), label, template == tpl).clicked() {
+ *template = tpl.to_string();
+ }
+ }
+ });
+ field(ui, "Start at", |ui| ui.add(egui::DragValue::new(start).range(0..=999_999)));
+ ui.label(
+ egui::RichText::new(crate::i18n::tr(
+ "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…",
+ ))
+ .color(t.text_dim),
+ );
+ let (preview, total) = rename_preview(app, ui.ctx(), template, *start as usize);
+ match &preview {
+ Some(rows) => {
+ egui::Grid::new("rename-preview").num_columns(3).spacing([8.0, 2.0]).show(ui, |ui| {
+ for pl in rows {
+ ui.label(egui::RichText::new(&pl.from).color(t.text_dim));
+ let (arrow, _) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover());
+ crate::icons::paint(ui.painter(), arrow, crate::icons::Icon::ChevronRight, t.text_dim);
+ ui.label(egui::RichText::new(&pl.to).color(t.text));
+ ui.end_row();
+ }
+ });
+ }
+ None => {
+ ui.horizontal(|ui| {
+ crate::progress::spinner(ui, 12.0);
+ ui.label(egui::RichText::new(crate::i18n::tr("Checking names…")).color(t.text_dim));
+ });
+ }
+ }
+ let more = total.saturating_sub(RENAME_PREVIEW_ROWS);
+ if more > 0 {
+ ui.label(egui::RichText::new(crate::i18n::tr_format!("… and {more} more", more = more)).color(t.text_dim));
+ }
+}
+
+/// The body of the RenamePerson dialog.
+fn rename_person_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, confirm: &mut bool, dlg: &mut Dialog) {
+ let Dialog::RenamePerson { from, to, merge } = dlg else { return };
+ let submitted = dialog_field(ui, "field:personName", to, "Name");
+ let plan = person_rename_plan(&app.session.catalog, from, to);
+ if !plan.needs_merge {
+ *merge = false;
+ }
+ if submitted && plan.block.is_none() && (!plan.needs_merge || *merge) {
+ *confirm = true;
+ }
+ if let Some(why) = plan.block {
+ ui.label(egui::RichText::new(crate::i18n::tr(why)).color(t.caution));
+ } else {
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!(
+ "Renames {n} face{} across the library. The files are not changed.",
+ if plan.faces == 1 { "" } else { "s" },
+ n = plan.faces
+ ))
+ .color(t.text_dim),
+ );
+ }
+ if plan.needs_merge {
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!(
+ "“{to}” is already a person. Combining them makes one person; Undo separates them again.",
+ to = to.trim()
+ ))
+ .color(t.caution),
+ );
+ let r = ui.checkbox(merge, crate::i18n::tr("Combine with the existing person"));
+ crate::widgets::register(ui, "check:personMerge", r.rect);
+ }
+}
+
+/// The body of the RenameKeyword dialog.
+fn rename_keyword_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, confirm: &mut bool, dlg: &mut Dialog) {
+ let Dialog::RenameKeyword { from, to } = dlg else { return };
+ let n = app.caches.dialog_count(&app.session.catalog, ("renameKeyword", from.as_str()), || {
+ app.session.catalog.photos().filter(|p| p.meta.keywords.iter().any(|k| lightcraft_catalog::keywords::is_under(k, from))).count()
+ });
+ if dialog_field(ui, "field:keywordName", to, "New name") {
+ *confirm = true;
+ }
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!(
+ "Renames “{from}” on {n} photo{} (keywords below it too). Use | for levels, e.g. Travel|Italy. An existing name merges the two.",
+ if n == 1 { "" } else { "s" },
+ from = from,
+ n = n
+ ))
+ .color(t.text_dim),
+ );
+}
+
+/// The body of the MergeKeywords dialog.
+fn merge_keywords_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, confirm: &mut bool, dlg: &mut Dialog) {
+ let Dialog::MergeKeywords { from, into } = dlg else { return };
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!("Replace {} with:", from.iter().map(|f| format!("“{f}”")).collect::<Vec<_>>().join(", ")))
+ .color(t.text_label),
+ );
+ if dialog_field(ui, "field:keywordInto", into, "Keyword") {
+ *confirm = true;
+ }
+ let options: Vec<String> = app
+ .caches
+ .suggestions(&app.session.catalog, from, into, 12)
+ .iter()
+ .filter(|k| !from.iter().any(|f| lightcraft_catalog::keywords::is_under(k, f)))
+ .cloned()
+ .collect();
+ ui.horizontal_wrapped(|ui| {
+ for k in options {
+ if ui.add(egui::Button::new(egui::RichText::new(&k).color(t.text_label)).corner_radius(10.0)).clicked() {
+ *into = k;
+ }
+ }
+ });
+}
+
+/// The body of the NewAlbum dialog.
+fn new_album_body(app: &mut LightcraftApp, ui: &mut egui::Ui, confirm: &mut bool, dlg: &mut Dialog) {
+ let Dialog::NewAlbum { name, folder, include_selected, .. } = dlg else { return };
+ if dialog_field(ui, "field:albumName", name, "Name") {
+ *confirm = true;
+ }
+ // as in Lightroom, the option is only there when something is selected
+ if !*folder && !app.session.selected().is_empty() {
+ ui.add_space(6.0);
+ let r = ui.checkbox(include_selected, crate::i18n::tr("Include selected photos"));
+ crate::widgets::register(ui, "check:albumIncludeSelected", r.rect);
+ }
+}
+
+/// The body of the PasteSettings dialog.
+fn paste_settings_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::PasteSettings { groups } = dlg else { return };
+ let n = app.session.selected().len();
+ ui.label(
+ egui::RichText::new(crate::i18n::tr_format!(
+ "Paste into {n} photo{} — only settings that were copied are pasted",
+ if n == 1 { "" } else { "s" },
+ n = n
+ ))
+ .color(t.text_dim),
+ );
+ group_checklist(ui, "pasteGroup", groups);
+}
+
+/// The body of the ContactSheet dialog.
+fn contact_sheet_body(app: &mut LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dialog) {
+ let Dialog::ContactSheet { options } = dlg else { return };
+ options.columns = options.columns.clamp(1, 8);
+ options.rows = options.rows.clamp(1, 10);
+ let n = app.session.selected().len();
+ ui.label(crate::i18n::tr_format!("{n} selected photos · {pages} pages", n = n, pages = n.div_ceil(options.columns * options.rows)));
+ field(ui, "Paper", |ui| {
+ let c = crate::widgets::combo_box("contactSheetPaper").selected_text(&options.paper).show_ui(ui, |ui| {
+ ui.selectable_value(&mut options.paper, "a4".into(), "A4");
+ ui.selectable_value(&mut options.paper, "letter".into(), crate::i18n::tr("Letter"));
+ });
+ crate::widgets::name_combo(&c.response, crate::i18n::tr("Paper"));
+ });
+ ui.checkbox(&mut options.landscape, crate::i18n::tr("Landscape"));
+ field(ui, "Columns", |ui| {
+ ui.add(egui::DragValue::new(&mut options.columns).range(1..=8));
+ });
+ field(ui, "Rows", |ui| {
+ ui.add(egui::DragValue::new(&mut options.rows).range(1..=10));
+ });
+ ui.checkbox(&mut options.captions, crate::i18n::tr("Filename captions"));
+ ui.label(crate::i18n::tr("150 dpi · sRGB · current edits · fit without cropping"));
+ ui.label(crate::i18n::tr("Choose a PDF destination after confirming. Print the PDF from your viewer."));
+}
+
+/// The body of the Export dialog.
+fn export_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::Export { opts, full_size, resize, preset_name, limit_kb, dir } = dlg else { return };
+ let n = app.session.selection.ids.len().max(1);
+ ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim));
+ export_preset_row(app, ui, opts, full_size, resize, limit_kb);
+ ui.add_space(4.0);
+ export_format_rows(ui, t, opts);
+ export_color_rows(ui, t, opts);
+ export_quality_rows(ui, opts, limit_kb);
+ if opts.format.is_rendered() {
+ export_size(ui, full_size, resize, &mut opts.ppi);
+ export_output_rows(app, ui, opts, *full_size, *resize);
+ }
+ ui.add_space(4.0);
+ export_naming_rows(ui, opts);
+ export_destination_rows(app, ui, t, opts, dir);
+ export_save_preset_row(app, ui, opts, *full_size, resize, *limit_kb, preset_name);
+}
+
+/// Export dialog: load a built-in or saved set of options.
+fn export_preset_row(
+ app: &mut LightcraftApp,
+ ui: &mut egui::Ui,
+ opts: &mut ExportOptions,
+ full_size: &mut bool,
+ resize: &mut Resize,
+ limit_kb: &mut u32,
+) {
+ // Preset: load a built-in or saved set of options into the dialog
+ field(ui, "Preset", |ui| {
+ let mut chosen = None;
+ let c = crate::widgets::combo_box("exportPreset").width(220.0).selected_text(crate::i18n::tr("Choose…")).show_ui(ui, |ui| {
+ let mut builtin = true;
+ for (p, b) in app.session.all_export_presets() {
+ if builtin && !b {
+ ui.separator();
+ }
+ builtin = b;
- if ui.selectable_label(false, crate::i18n::builtin_label(&p.name, b)).clicked() {
++ let r = ui.selectable_label(false, crate::i18n::builtin_label(&p.name, b));
++ let r = match preset_lzw_note(&p.params) {
++ Some(note) => r.on_hover_text(crate::i18n::tr(note)),
++ None => r,
++ };
++ if r.clicked() {
+ chosen = Some(p.name);
+ }
+ }
+ });
+ crate::widgets::name_combo(&c.response, crate::i18n::tr("Preset"));
+ crate::widgets::register(ui, "combo:exportPreset", c.response.rect);
+ if let Some(name) = chosen
+ && let Ok(params) = app.session.export_params(&json!({"preset": name}))
+ {
+ let o = lightcraft_engine::export::ExportOptions::from_json(&params);
+ *full_size = o.resize.is_none();
+ *resize = o.resize.unwrap_or_default();
+ *limit_kb = o.limit_kb.unwrap_or(0);
+ *opts = o;
+ }
+ });
+}
+
+/// Export dialog: the format, its variants and the bit depth.
+fn export_format_rows(ui: &mut egui::Ui, t: &Tokens, opts: &mut ExportOptions) {
+ use lightcraft_engine::export::ExportFormat as F;
+ let before = opts.format;
+ // "Rendered DNG" is a DNG option (below), not a format of its own in this list
+ let mut shown = if opts.format == F::RenderedDng { F::Dng } else { opts.format };
+ choices(
+ ui,
+ "Format",
+ "exportFormat",
+ &[
+ (F::Jpeg, "JPEG"),
+ (F::Png, "PNG"),
+ (F::Tiff, "TIFF"),
+ (F::Psd, "PSD"),
+ (F::Webp, "WebP"),
+ (F::Avif, "AVIF"),
+ (F::Jxl, "JPEG XL"),
+ (F::Dng, "DNG"),
+ (F::Original, "Original files"),
+ ],
+ &mut shown,
+ );
+ if shown != opts.format && !(shown == F::Dng && opts.format == F::RenderedDng) {
+ opts.format = shown;
+ }
+ if matches!(opts.format, F::Dng | F::RenderedDng) {
+ choices(ui, "DNG of", "exportDngKind", &[(F::Dng, "Raw data"), (F::RenderedDng, "Rendered photo")], &mut opts.format);
+ }
+ if !opts.format.is_rendered() {
+ let note = if opts.format == F::Dng {
+ "Raw photos as DNG, with the edits embedded. Size, color and output options don't apply."
+ } else {
+ "The original files, unchanged, each with an XMP sidecar holding its edits."
+ };
+ ui.label(egui::RichText::new(note).color(t.text_dim));
+ }
+ if opts.format != before {
+ // each format starts at its own default depth (TIFF 16-bit, others 8-bit)
+ opts.bit_depth = None;
+ }
+ let rendered = opts.format.is_rendered();
+ let depths = lightcraft_engine::export::ExportOptions::bit_depths(opts.format);
+ if rendered && depths.len() > 1 {
+ let mut bd = opts.bit_depth.filter(|b| depths.iter().any(|d| d.0 == *b)).unwrap_or(depths[0].0);
+ choices(ui, "Bit depth", "exportBitDepth", depths, &mut bd);
+ opts.bit_depth = Some(bd);
+ }
+}
+
+/// Export dialog: HDR output and the color space it implies (or the choice of one).
+fn export_color_rows(ui: &mut egui::Ui, t: &Tokens, opts: &mut ExportOptions) {
+ use lightcraft_engine::export::ExportFormat as F;
+ let rendered = opts.format.is_rendered();
+ if matches!(opts.format, F::Jpeg | F::Tiff | F::Avif | F::Png | F::Jxl) {
+ let tip = crate::i18n::tr(
+ "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float",
+ );
+ ui.checkbox(&mut opts.hdr, crate::i18n::tr("HDR output")).on_hover_text(tip);
+ if opts.hdr && !opts.hdr_output() {
+ ui.label(egui::RichText::new(crate::i18n::tr("HDR TIFF needs 32-bit float.")).color(t.text_dim));
+ }
+ if opts.hdr && opts.format == F::Avif {
+ use lightcraft_engine::export::HdrCurve as H;
+ choices(ui, "HDR curve", "exportHdrCurve", &[(H::Pq, "PQ"), (H::Hlg, "HLG")], &mut opts.hdr_transfer);
+ }
+ }
+ if !rendered {
+ } else if opts.format == F::Avif && opts.hdr {
+ let label = if opts.hdr_transfer == lightcraft_engine::export::HdrCurve::Hlg {
+ crate::i18n::tr("Color space: Rec. 2020 HLG (HDR AVIF)")
+ } else {
+ crate::i18n::tr("Color space: Rec. 2020 PQ (HDR AVIF)")
+ };
+ ui.label(egui::RichText::new(label).color(t.text_dim));
+ } else if opts.format == F::Png && opts.hdr {
+ ui.label(egui::RichText::new(crate::i18n::tr("Color space: Rec. 2020 PQ, 16-bit (HDR PNG)")).color(t.text_dim))
+ .on_hover_text(crate::i18n::tr("Viewers that don't read the PNG cICP chunk show PQ values as sRGB: flat and washed out. For a picture that looks right everywhere, use JPEG (gain map)."));
+ } else if opts.format == F::Jxl && opts.hdr {
+ ui.label(egui::RichText::new(crate::i18n::tr("Color space: Rec. 2020 PQ (HDR JPEG XL)")).color(t.text_dim));
+ } else if opts.format == F::Avif {
+ ui.label(egui::RichText::new(crate::i18n::tr("Color space: sRGB (AVIF)")).color(t.text_dim));
+ } else {
+ use lightcraft_engine::export::OutputSpace as C;
+ choices(
+ ui,
+ "Color space",
+ "exportColorSpace",
+ &[(C::Srgb, "sRGB"), (C::DisplayP3, "P3"), (C::AdobeRgb, "Adobe RGB"), (C::ProPhoto, "ProPhoto"), (C::Rec2020, "Rec.2020")],
+ &mut opts.color_space,
+ );
+ if opts.effective_space() != opts.color_space {
+ let note = "Lossy JPEG XL writes Adobe RGB and ProPhoto as Rec. 2020; choose Lossless to keep them.";
+ ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim));
+ }
+ }
+}
+
+/// Export dialog: quality and the other options of a lossy or JPEG XL file.
+fn export_quality_rows(ui: &mut egui::Ui, opts: &mut ExportOptions, limit_kb: &mut u32) {
+ use lightcraft_engine::export::ExportFormat as F;
+ if opts.format == F::Jxl {
+ let tip = "Mathematically lossless: every pixel is kept exactly (larger files)";
+ ui.checkbox(&mut opts.jxl_lossless, crate::i18n::tr("Lossless")).on_hover_text(crate::i18n::tr(tip));
+ }
+ if matches!(opts.format, F::Jpeg | F::Avif) || (opts.format == F::Jxl && !opts.jxl_lossless) {
+ let mut q = opts.quality as f64;
+ if num(ui, &QUALITY, &mut q) {
+ opts.quality = q as u8;
+ }
+ }
+ if opts.format == F::Jxl {
+ use lightcraft_engine::export::JxlEffort as E;
+ choices(ui, "Effort", "exportJxlEffort", &[(E::Fast, "Fast"), (E::Normal, "Normal")], &mut opts.jxl_effort);
+ let tip = "Shows a coarse version first and refines it as the file loads";
+ ui.checkbox(&mut opts.jxl_progressive, crate::i18n::tr("Progressive")).on_hover_text(crate::i18n::tr(tip));
+ }
+ if opts.format == F::Jpeg {
+ let mut k = *limit_kb as f64;
+ if num(ui, &LIMIT_KB, &mut k) {
+ *limit_kb = k as u32;
+ }
+ }
+}
+
+/// Export dialog: sharpening, metadata and the watermark of a rendered photo.
+fn export_output_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut ExportOptions, full_size: bool, resize: Resize) {
+ use lightcraft_engine::export::{MetadataPolicy as M, SharpenAmount as A, SharpenFor as S};
+ choices(
+ ui,
+ "Sharpen",
+ "exportSharpen",
+ &[(S::None, "None"), (S::Screen, "Screen"), (S::Matte, "Matte"), (S::Glossy, "Glossy")],
+ &mut opts.sharpen,
+ );
+ if opts.sharpen != S::None {
+ choices(ui, "Amount", "exportSharpenAmount", &[(A::Low, "Low"), (A::Standard, "Standard"), (A::High, "High")], &mut opts.sharpen_amount);
+ }
+ choices(
+ ui,
+ "Metadata",
+ "exportMetadata",
+ &[(M::All, "All"), (M::AllExceptCamera, "No camera"), (M::Copyright, "Copyright"), (M::None, "None")],
+ &mut opts.metadata,
+ );
+ if !matches!(opts.metadata, M::None | M::Copyright) {
+ ui.checkbox(&mut opts.remove_location, crate::i18n::tr("Remove location info"));
+ }
+ export_watermark(app, ui, opts, full_size, resize);
+}
+
+/// Export dialog: the watermark switch, its preview and its settings.
+fn export_watermark(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut ExportOptions, full_size: bool, resize: Resize) {
+ let mut wm_on = opts.watermark.is_some();
+ if ui.checkbox(&mut wm_on, crate::i18n::tr("Watermark")).changed() {
+ opts.watermark = wm_on.then(|| lightcraft_engine::export::Watermark { text: "© ".into(), ..Default::default() });
+ }
+ let wm_shown = opts.watermark.clone();
+ if let Some(wm) = &wm_shown {
+ watermark_preview(app, ui, wm, (!full_size).then_some(resize));
+ }
+ if let Some(wm) = &mut opts.watermark {
+ // text, or a graphic (a logo with transparency)
+ let mut graphic = !wm.image.is_empty() || ui.data(|d| d.get_temp::<bool>(egui::Id::unique("wm-graphic"))).unwrap_or(false);
+ let before = graphic;
+ choices(ui, "Style", "exportWmStyle", &[(false, "Text"), (true, "Graphic")], &mut graphic);
+ if graphic != before {
+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("wm-graphic"), graphic));
+ if !graphic {
+ wm.image.clear();
+ }
+ }
+ if graphic {
+ field(ui, "Graphic", |ui| {
+ trailing_button_row(ui, |ui| {
+ if app.services.pick_files.is_some()
+ && crate::widgets::text_button(ui, "exportWmChoose", crate::i18n::tr("Choose…"), false).clicked()
+ && let Some(f) = app.services.pick_files.as_mut().and_then(|pick| pick().into_iter().next())
+ {
+ wm.image = f;
+ }
+ crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(&mut wm.image).hint_text("logo.png").desired_width(ui.available_width())),
+ crate::i18n::tr("Image"),
+ );
+ });
+ });
+ let mut width = wm.image_width as f64 * 100.0;
+ if num(ui, &WM_IMAGE_WIDTH, &mut width) {
+ wm.image_width = (width / 100.0) as f32;
+ }
+ } else {
+ choices(
+ ui,
+ app.ui.language.tr("Text direction"),
+ "exportWmOrientation",
+ &[(false, app.ui.language.tr("Horizontal text")), (true, app.ui.language.tr("Vertical text"))],
+ &mut wm.vertical,
+ );
+ field(ui, "Text", |ui| {
+ crate::widgets::named(
+ ui.add(
+ egui::TextEdit::multiline(&mut wm.text)
+ .desired_rows(2)
+ .hint_text(crate::i18n::tr("© Your Name"))
+ .desired_width(f32::INFINITY),
+ ),
+ crate::i18n::tr("Text"),
+ )
+ });
+ }
+ choices(ui, "Position", "exportWmAnchor", &WM_POSITIONS, &mut wm.anchor);
+ choices(ui, "Rotate", "exportWmRotation", &[(0u16, "0°"), (90, "90°"), (180, "180°"), (270, "270°")], &mut wm.rotation);
+ let mut size = wm.size as f64 * 100.0;
+ if !graphic && num(ui, &WM_SIZE, &mut size) {
+ wm.size = (size / 100.0) as f32;
+ }
+ let mut op = wm.opacity as f64 * 100.0;
+ if num(ui, &WM_OPACITY, &mut op) {
+ wm.opacity = (op / 100.0) as f32;
+ }
+ // like Lightroom Classic: a margin from the side edges and one from the top and bottom
+ // edges, each unused (greyed) when the position is centred along that axis
+ use lightcraft_engine::export::Anchor as P;
+ let across = !matches!(wm.anchor, P::Top | P::Center | P::Bottom);
+ if let Some(v) = crate::widgets::slider(ui, &WM_INSET_X, wm.inset_x as f64 * 100.0, across, None).value {
+ wm.inset_x = (v / 100.0) as f32;
+ }
+ let down = !matches!(wm.anchor, P::Left | P::Center | P::Right);
+ if let Some(v) = crate::widgets::slider(ui, &WM_INSET_Y, wm.inset_y as f64 * 100.0, down, None).value {
+ wm.inset_y = (v / 100.0) as f32;
+ }
+ if !graphic {
+ ui.checkbox(&mut wm.shadow, crate::i18n::tr("Shadow"));
+ }
+ }
+ if opts.watermark != wm_shown {
+ // the preview above was drawn with the old settings
+ ui.ctx().request_repaint();
+ }
+}
+
+/// Export dialog: compression and the file name.
+fn export_naming_rows(ui: &mut egui::Ui, opts: &mut ExportOptions) {
+ use lightcraft_engine::export::ExportFormat as F;
+ if opts.format == F::Tiff {
+ use lightcraft_engine::export::TiffCompression as Z;
+ choices(ui, "Compression", "exportTiffCompression", &[(Z::None, "None"), (Z::Lzw, "LZW"), (Z::Deflate, "ZIP")], &mut opts.tiff_compression);
++ // issue #2882: LZW stays as picked, with a note on what it costs
++ if let Some(note) = tiff_lzw_note(opts) {
++ let t = Tokens::get(ui.ctx());
++ let r = ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim));
++ crate::widgets::register(ui, "note:exportTiffLzw", r.rect);
++ }
+ }
+ if opts.format == F::Dng {
+ use lightcraft_engine::export::DngCompression as Z;
+ choices(
+ ui,
+ "Compression",
+ "exportDngCompression",
+ &[(Z::Lossless, "Lossless"), (Z::Deflate, "ZIP"), (Z::Uncompressed, "None"), (Z::Lossy, "Lossy")],
+ &mut opts.dng_compression,
+ );
+ }
+ let naming_id = egui::Id::unique("export-naming");
+ let tags_open = field(ui, "File name", |ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ let w = crate::import::tag_field_width(ui);
+ crate::widgets::named(
+ ui.add(
+ egui::TextEdit::singleline(&mut opts.naming)
+ .id(naming_id)
+ .hint_text("{name}-{seq} · {date} · {title} · {folder}")
+ .desired_width(w),
+ ),
+ crate::i18n::tr("File name"),
+ );
+ crate::import::tag_toggle(ui, "exportNaming")
+ });
+ if tags_open {
+ crate::import::tag_help(ui, "exportNaming", &mut opts.naming, naming_id);
+ }
+ crate::import::unknown_tags_warning(ui, &opts.naming);
+ if opts.naming.contains("{seq") {
+ let mut v = opts.start_number as f64;
+ if num(ui, &START_NUMBER, &mut v) {
+ opts.start_number = v as u32;
+ }
+ }
+}
+
+/// Export dialog: where the files go and what happens when one exists.
+fn export_destination_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, opts: &mut ExportOptions, dir: &mut String) {
+ // like Lightroom Classic's Export To: one folder, or each photo's own folder (not on
+ // the web, where originals live in the browser's storage, not in folders)
+ use lightcraft_engine::export::DestinationMode as D;
+ if !cfg!(target_arch = "wasm32") || opts.destination_mode != D::SpecificFolder {
+ choices(
+ ui,
+ "Export to",
+ "exportDestinationMode",
+ &[(D::SpecificFolder, "Specific folder"), (D::SameAsOriginal, "Same folder as original photo")],
+ &mut opts.destination_mode,
+ );
+ }
+ if opts.destination_mode == D::SpecificFolder {
+ field(ui, "Folder", |ui| {
+ trailing_button_row(ui, |ui| {
+ if app.services.pick_folder.is_some()
+ && crate::widgets::text_button(ui, "exportChooseFolder", crate::i18n::tr("Choose…"), false).clicked()
+ && let Some(pick) = app.services.pick_folder.as_mut()
+ && let Some(d) = pick()
+ {
+ *dir = d;
+ }
+ crate::widgets::named(ui.add(egui::TextEdit::singleline(dir).desired_width(ui.available_width())), crate::i18n::tr("Folder"));
+ });
+ });
+ }
+ field(ui, "Subfolder", |ui| {
+ crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(&mut opts.subfolder).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY)),
+ crate::i18n::tr("Subfolder"),
+ )
+ });
+ use lightcraft_engine::export::Conflict as K;
+ choices(ui, "If file exists", "exportConflict", &[(K::Unique, "Add number"), (K::Overwrite, "Overwrite"), (K::Skip, "Skip")], &mut opts.conflict);
+ export_apple_photos_rows(ui, t, opts);
+}
+
+/// Export dialog, after export: Apple Photos imports the files written (macOS only).
+#[cfg(target_os = "macos")]
+fn export_apple_photos_rows(ui: &mut egui::Ui, t: &Tokens, opts: &mut ExportOptions) {
+ let r = ui.checkbox(&mut opts.add_to_photos, crate::i18n::tr("Add to Apple Photos"));
+ crate::widgets::register(ui, "exportAddToPhotos", r.rect);
+ if opts.add_to_photos {
+ field(ui, "Album", |ui| {
+ crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(&mut opts.photos_album).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY)),
+ crate::i18n::tr("Album"),
+ )
+ });
+ ui.label(
+ egui::RichText::new(crate::i18n::tr("The first time, macOS asks whether LightCraft may control Photos.")).size(11.0).color(t.text_dim),
+ );
+ }
+}
+
+/// Nowhere to add them: a setting carried over from a Mac is dropped, not refused.
+#[cfg(not(target_os = "macos"))]
+fn export_apple_photos_rows(_ui: &mut egui::Ui, _t: &Tokens, opts: &mut ExportOptions) {
+ opts.add_to_photos = false;
+}
+
+/// Export dialog: save the options as a preset.
+fn export_save_preset_row(
+ app: &mut LightcraftApp,
+ ui: &mut egui::Ui,
+ opts: &ExportOptions,
+ full_size: bool,
+ resize: &Resize,
+ limit_kb: u32,
+ preset_name: &mut String,
+) {
+ ui.add_space(4.0);
+ field(ui, "Save preset", |ui| {
+ trailing_button_row(ui, |ui| {
+ let named = !preset_name.trim().is_empty();
+ if crate::widgets::text_button(ui, "exportSavePreset", crate::i18n::tr("Save"), false).clicked() && named {
+ let params = export_dialog_params(opts, full_size, resize, limit_kb);
+ match app.run("export.savePreset", json!({"name": preset_name.trim(), "params": params})) {
+ Ok(_) => {
+ app.toast(ui.ctx(), crate::i18n::tr_format!("Saved export preset “{}”", preset_name.trim()));
+ preset_name.clear();
+ }
+ Err(e) => app.toast(ui.ctx(), e),
+ }
+ }
+ crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(preset_name).hint_text(crate::i18n::tr("Preset name")).desired_width(ui.available_width())),
+ crate::i18n::tr("Preset name"),
+ );
+ });
+ });
+}
+
+/// The body of the KeywordTag dialog.
+fn keyword_tag_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, confirm: &mut bool, dlg: &mut Dialog) {
+ let Dialog::KeywordTag {
+ editing,
+ name,
+ parent,
+ inside,
+ synonyms,
+ include_on_export,
+ export_containing,
+ export_synonyms,
+ person,
+ add_to_selected,
+ ..
+ } = dlg
+ else {
+ return;
+ };
+ ui.label(egui::RichText::new(crate::i18n::tr("Keyword Name")).color(t.text_dim));
+ // several fields: the name takes the focus when the dialog opens, not after
+ let r = crate::text_field::TextField::singleline("field:keywordTagName", name)
+ .hint(crate::i18n::tr("Keyword Name"))
+ .width(f32::INFINITY)
+ .select_on_focus(true)
+ .show(ui);
+ if ui.is_enabled() && just_opened(ui, "keyword-tag") {
+ r.response.request_focus();
+ }
+ if r.ending == Some(crate::text_field::Ending::Return) {
+ *confirm = true;
+ }
+ ui.add_space(4.0);
+ ui.label(egui::RichText::new(crate::i18n::tr("Synonyms")).color(t.text_dim));
+ // Return in either field creates (or saves) the keyword
+ let r = crate::text_field::TextField::singleline("field:keywordSynonyms", synonyms)
+ .hint(crate::i18n::tr("Separated by commas"))
+ .width(f32::INFINITY)
+ .show(ui);
+ if r.ending == Some(crate::text_field::Ending::Return) {
+ *confirm = true;
+ }
+ ui.add_space(6.0);
+ if editing.is_none() {
+ if let Some(p) = parent {
+ let r = ui.checkbox(inside, crate::i18n::tr_format!("Put inside “{parent}”", parent = p.replace('|', " › ")));
+ crate::widgets::register(ui, "check:keywordInside", r.rect);
+ }
+ let n = app.session.selection.ids.len();
+ let r = ui.add_enabled(n > 0, egui::Checkbox::new(add_to_selected, crate::i18n::tr("Add to Selected Photos")));
+ crate::widgets::register(ui, "check:keywordAddToSelected", r.rect);
+ ui.add_space(4.0);
+ }
+ ui.label(egui::RichText::new(crate::i18n::tr("Keyword Tag Options")).color(t.text_dim));
+ for (on, label, id) in [
+ (include_on_export, "Include on Export", "check:keywordIncludeOnExport"),
+ (export_containing, "Export Containing Keywords", "check:keywordExportContaining"),
+ (export_synonyms, "Export Synonyms", "check:keywordExportSynonyms"),
+ (person, "Person", "check:keywordPerson"),
+ ] {
+ let r = ui.checkbox(on, crate::i18n::tr(label));
+ crate::widgets::register(ui, id, r.rect);
+ }
+}
+
+/// The body of the KeywordSet dialog.
+fn keyword_set_body(ui: &mut egui::Ui, t: &Tokens, confirm: &mut bool, dlg: &mut Dialog) {
+ let Dialog::KeywordSet { replaces, name, slots, as_new } = dlg else { return };
+ ui.label(egui::RichText::new(crate::i18n::tr("Set name")).color(t.text_dim));
+ let r = crate::text_field::TextField::singleline("field:keywordSetName", name)
+ .hint(crate::i18n::tr("Set name"))
+ .width(f32::INFINITY)
+ .select_on_focus(true)
+ .show(ui);
+ if ui.is_enabled() && just_opened(ui, "keyword-set") {
+ r.response.request_focus();
+ }
+ let mut returned = r.ending == Some(crate::text_field::Ending::Return);
+ ui.add_space(6.0);
+ ui.label(egui::RichText::new(crate::i18n::tr("Keywords (⌥1–⌥9)")).color(t.text_dim));
+ slots.resize(9, String::new());
+ // equal columns of a set width (the window is still finding its own)
+ let w = 130.0;
+ egui::Grid::new("keyword-set-slots").num_columns(3).min_col_width(w).spacing([6.0, 4.0]).show(ui, |ui| {
+ for (i, slot) in slots.iter_mut().enumerate() {
+ let r = crate::text_field::TextField::singleline(&format!("field:keywordSetSlot:{}", i + 1), slot)
+ .hint(format!("⌥{}", i + 1))
+ .width(w)
+ .show(ui);
+ returned |= r.ending == Some(crate::text_field::Ending::Return);
+ if i % 3 == 2 {
+ ui.end_row();
+ }
+ }
+ });
+ if replaces.is_some() {
+ ui.add_space(6.0);
+ let r = ui.checkbox(as_new, crate::i18n::tr("Save as a new set"));
+ crate::widgets::register(ui, "check:keywordSetAsNew", r.rect);
+ }
+ // Return in any field saves the set
+ if returned {
+ *confirm = true;
+ }
+}
+
+/// The body of the MoveKeyword dialog.
+fn move_keyword_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::MoveKeyword { keyword, parent } = dlg else { return };
+ let name = keyword.rsplit('|').next().unwrap_or(keyword);
+ match parent {
+ Some(p) => {
+ ui.label(crate::i18n::tr_format!("“{parent}” has a “{name}” already. Merge the two?", parent = p.replace('|', " › "), name = name))
+ }
+ None => ui.label(crate::i18n::tr_format!("There is a “{name}” at the top level already. Merge the two?", name = name)),
+ };
+ ui.label(egui::RichText::new(crate::i18n::tr("Their photos and the keywords below them come together under one keyword.")).color(t.text_dim));
+}
+
+/// The body of the DeleteKeyword dialog.
+fn delete_keyword_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::DeleteKeyword { keyword, count } = dlg else { return };
+ let name = keyword.replace('|', " › ");
+ ui.label(crate::i18n::tr_format!("Delete the keyword “{name}”?", name = name));
+ ui.label(
+ egui::RichText::new(if *count == 0 {
+ crate::i18n::tr("No photo has it; the keywords below it go too.").to_string()
+ } else {
+ crate::i18n::tr_format!(
+ "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.",
+ if *count == 1 { "" } else { "s" },
+ count = count
+ )
+ })
+ .color(t.text_dim),
+ );
+}
+
+/// The body of the DeleteEffects dialog.
+fn delete_effects_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::DeleteEffects { names } = dlg else { return };
+ let what = match names.as_slice() {
+ [one] => crate::i18n::tr_format!("Delete the effect preset “{name}”?", name = one),
+ _ => crate::i18n::tr_format!("Delete these {n} effect presets?", n = names.len()),
+ };
+ ui.label(what);
+ ui.label(egui::RichText::new(crate::i18n::tr("Masks keep their sliders. Export presets first to keep a copy.")).color(t.text_dim));
+}
+
+/// The body of the MovePhotos dialog.
+fn move_photos_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::MovePhotos { ids, name, dont_ask, .. } = dlg else { return };
+ let n = ids.len();
+ ui.label(crate::i18n::tr_format!("Move {n} photo{} to “{}”?", if n == 1 { "" } else { "s" }, name, n = n));
+ ui.label(egui::RichText::new(crate::i18n::tr("Their files and XMP sidecars move on disk. Edit → Undo moves them back.")).color(t.text_dim));
+ ui.add_space(4.0);
+ let c = ui.checkbox(dont_ask, crate::i18n::tr("Don't ask again"));
+ crate::widgets::register(ui, "check:moveDontAsk", c.rect);
+ c.on_hover_text(crate::i18n::tr("Settings → Confirm before moving photos to another folder on disk turns it back on"));
+}
+
+/// The body of the LightroomCatalog dialog.
+fn lightroom_catalog_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::LightroomCatalog { folder, catalog } = dlg else { return };
+ ui.label(crate::i18n::tr("This is a Lightroom catalog, not a LightCraft library. Import it into a LightCraft library instead?"));
+ ui.label(egui::RichText::new(catalog.as_deref().unwrap_or(folder.as_str())).color(t.text_dim));
+ // (the import then asks where the catalog goes, unless Settings says to merge, #2672)
+ let asks = app.ui.settings.lightroom_import == crate::state::LightroomImport::Ask && app.session.library.as_ref().is_some_and(|l| l.on_disk);
+ let what = if asks {
+ "The import reads the catalog without changing it. Next, choose whether its photos, edits, keywords and collections join the library open now or go into a new library."
+ } else {
+ "The import reads the catalog without changing it and adds its photos, edits, keywords and collections to the library open now."
+ };
+ ui.label(egui::RichText::new(crate::i18n::tr(what)).color(t.text_dim));
+}
+
+/// The body of the RemoveFolder dialog.
+fn remove_folder_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::RemoveFolder { name, count, path, disk } = dlg else { return };
+ ui.label(crate::i18n::tr_format!(
+ "Remove “{name}” and its {count} photo{} from the library?",
+ if *count == 1 { "" } else { "s" },
+ name = name,
+ count = count
+ ));
+ ui.label(egui::RichText::new(path.as_str()).color(t.text_dim));
+ let scope = if *disk { "All the photos imported from this disk are included." } else { "That includes the photos in the folders inside it." };
+ ui.label(egui::RichText::new(crate::i18n::tr(scope)).color(t.text_dim));
+ ui.label(
+ egui::RichText::new(crate::i18n::tr("They move to Recently Deleted and can be restored; no file on disk is touched.")).color(t.text_dim),
+ );
+}
+
+/// The body of the About dialog.
+fn about_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
+ let Dialog::About = dlg else { return };
+ ui.set_min_width(680.0);
+ let tab_id = egui::Id::unique("about_tab");
+ let mut tab = ui.data_mut(|d| d.get_temp::<u8>(tab_id)).unwrap_or(0);
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ for (i, (id, label)) in ABOUT_TABS.iter().enumerate() {
+ if crate::widgets::text_button(ui, &format!("aboutTab-{id}"), label, usize::from(tab) == i).clicked() {
+ tab = u8::try_from(i).unwrap_or(0);
+ }
+ }
+ });
+ ui.data_mut(|d| d.insert_temp(tab_id, tab));
+ ui.separator();
+ match tab {
+ 1 => crate::credits::contributors_ui(app, ui),
+ 2 => crate::credits::models_ui(ui),
+ _ => {
+ ui.label(egui::RichText::new("LightCraft").font(t.semibold(20.0)).color(t.text));
+ ui.label(crate::i18n::tr_format!("Version {} — a clean-room, pure-Rust photo library and raw developer.", env!("CARGO_PKG_VERSION")));
+ ui.label(crate::i18n::tr_format!(
+ "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.",
+ crate::theme::font_credits(app.chinese_font.is_some())
+ ));
+ ui.add_space(10.0);
+ let r = crate::button::Button::new("Join the ArtCraft Discord")
+ .primary()
+ .large()
+ .min_width(260.0)
+ .widget("button:aboutDiscord")
+ .tooltip(crate::links::DISCORD)
+ .show(ui);
+ if r.clicked() {
+ let _ = crate::links::open(app, crate::links::DISCORD);
+ }
+ ui.add_space(6.0);
+ for (label, url) in [
+ ("LightCraft website", crate::links::APP_PAGE),
+ ("Source code on GitHub", crate::links::GITHUB),
+ ("ArtCraft — more creative apps", crate::links::WEBSITE),
+ ] {
+ let r = ui.link(crate::i18n::tr(label)).on_hover_text(url);
+ if r.clicked() {
+ let _ = crate::links::open(app, url);
+ }
+ }
+ }
+ }
+}
+
+/// The body of the open dialog: what each kind of dialog shows between its title and its buttons. `confirm` is set
+/// by a dialog that is confirmed from its body (a text field's Return).
+fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_max: f32, confirm: &mut bool, dlg: &mut Dialog) {
+ match dlg {
+ Dialog::AutoStack { .. } => auto_stack_body(app, ui, t, dlg),
+ Dialog::Cull { .. } => cull_body(app, ui, t, dlg),
+ Dialog::WhatsNew => whats_new_body(ui, t, dlg),
+ Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::model_dialog(app, ui, t, info, accepted),
+ Dialog::FaceModel { info, accepted, .. } => crate::panels::faces::model_dialog(app, ui, t, info, accepted),
+ Dialog::LightroomResult { .. } => lightroom_result_body(ui, dlg),
+ Dialog::SystemInfo { .. } => system_info_body(ui, t, dlg),
+ Dialog::AllMetadata { .. } => all_metadata_body(ui, t, dlg),
+ Dialog::SmartRules { .. } => smart_rules_body(app, ui, t, dlg),
+ Dialog::NewSmartAlbum { .. } => new_smart_album_body(app, ui, t, confirm, dlg),
+ Dialog::CaptureTime { .. } => capture_time_body(app, ui, t, dlg),
+ Dialog::LabelNames { .. } => label_names_body(app, ui, t, dlg),
+ Dialog::Rename { .. } => rename_body(app, ui, t, dlg),
+ Dialog::RenamePerson { .. } => rename_person_body(app, ui, t, confirm, dlg),
+ Dialog::RenameKeyword { .. } => rename_keyword_body(app, ui, t, confirm, dlg),
+ Dialog::MergeKeywords { .. } => merge_keywords_body(app, ui, t, confirm, dlg),
+ Dialog::TextPrompt { value, hint, .. } => {
+ if dialog_field(ui, "field:prompt", value, hint) {
+ *confirm = true;
+ }
+ }
+ Dialog::NewAlbum { .. } => new_album_body(app, ui, confirm, dlg),
+ Dialog::RenameAlbum { name, .. } => {
+ if dialog_field(ui, "field:albumName", name, "Name") {
+ *confirm = true;
+ }
+ }
+ Dialog::CreatePreset { name, group, groups } => {
+ crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Preset name")).desired_width(f32::INFINITY)),
+ crate::i18n::tr("Preset name"),
+ );
+ crate::widgets::named(
+ ui.add(egui::TextEdit::singleline(group).hint_text(crate::i18n::tr("Group")).desired_width(f32::INFINITY)),
+ crate::i18n::tr("Group"),
+ );
+ ui.label(egui::RichText::new(crate::i18n::tr("Settings to include")).color(t.text_dim));
+ group_checklist(ui, "presetInclude", groups);
+ }
+ Dialog::CopySettings { groups } => group_checklist(ui, "copyGroup", groups),
+ Dialog::PasteSettings { .. } => paste_settings_body(app, ui, t, dlg),
+ Dialog::SlideshowExport { settings } => slideshow_export_body(app, ui, settings),
+ Dialog::ContactSheet { .. } => contact_sheet_body(app, ui, dlg),
+ Dialog::Export { .. } => export_body(app, ui, t, dlg),
+ Dialog::Merge { opts } => crate::merge::body(app, ui, opts),
+ Dialog::Import { opts } => crate::import::body(app, ui, opts),
+ // (Settings is never taller than `body_max`, so the scroll area round it never
+ // scrolls: its tab bar stays put and its pages scroll by themselves)
+ Dialog::Settings { tab } => crate::panels::settings::window(app, ui, tab, body_max),
+ Dialog::SamModel { error, .. } => sam_model_body(app, ui, error.as_deref()),
+ Dialog::KeywordTag { .. } => keyword_tag_body(app, ui, t, confirm, dlg),
+ Dialog::KeywordSet { .. } => keyword_set_body(ui, t, confirm, dlg),
+ Dialog::MoveKeyword { .. } => move_keyword_body(ui, t, dlg),
+ Dialog::DeleteKeyword { .. } => delete_keyword_body(ui, t, dlg),
+ Dialog::SaveEffect { name, group, fields, amount, brush } => {
+ if crate::panels::mask_effects::save_body(app, ui, name, group, fields, amount, brush) {
+ *confirm = true;
+ }
+ }
+ Dialog::ManageEffects { search, selected, rename, confirm_delete, new_group } => {
+ crate::panels::mask_effects::manage_body(app, ui, search, selected, rename, confirm_delete, new_group)
+ }
+ Dialog::DeleteEffects { .. } => delete_effects_body(ui, t, dlg),
+ Dialog::ConfirmDelete { count } => {
+ let what =
+ if *count == 1 { crate::i18n::tr("this photo").to_string() } else { crate::i18n::tr_format!("these {count} photos", count = count) };
+ ui.label(crate::i18n::tr_format!("Move {what} to Recently Deleted?", what = what));
+ ui.label(egui::RichText::new(crate::i18n::tr("They can be restored from Recently Deleted until it is emptied.")).color(t.text_dim));
+ }
+ Dialog::MovePhotos { .. } => move_photos_body(ui, t, dlg),
+ d @ Dialog::SynchronizeFolder { .. } => crate::sync::body(app, ui, d),
+ Dialog::LightroomCatalog { .. } => lightroom_catalog_body(app, ui, t, dlg),
+ d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::body(app, ui, d),
+ Dialog::RemoveFolder { .. } => remove_folder_body(ui, t, dlg),
+ Dialog::About => about_body(app, ui, t, dlg),
+ Dialog::Shortcuts => crate::panels::keymap::body(app, ui, t),
+ Dialog::ViewOptions => crate::panels::settings::view_options(app, ui, t),
+ Dialog::Print => crate::print_view::body(app, ui, t),
+ }
+}
diff --cc crates/ui-egui/src/dialogs/export.rs
index ce9cffe77,000000000..2355c0509
mode 100644,000000..100644
--- a/crates/ui-egui/src/dialogs/export.rs
+++ b/crates/ui-egui/src/dialogs/export.rs
@@@ -1,302 -1,0 +1,431 @@@
+use super::frame::{field, num};
+use super::{ControlSpec, LightcraftApp, Section, SettingsGroup, Tokens, Track};
+
+/// The Export dialog's watermark preview: the first exported photo, as wide as the dialog whatever
+/// its shape, with the watermark drawn on it as the file will have it at size `resize` (`None` =
+/// full size). On a worker thread, once per photo, catalog change and size step, the cached
+/// thumbnail comes first (at once, a little soft) and then a render at the preview's own pixel size
+/// replaces it. The watermark is redrawn on a copy only when it, the output size or the picture
+/// changes, which is quick at this size, so the preview follows the sliders.
+pub(super) fn watermark_preview(
+ app: &mut LightcraftApp,
+ ui: &mut egui::Ui,
+ wm: &lightcraft_engine::export::Watermark,
+ resize: Option<lightcraft_engine::export::Resize>,
+) {
+ use std::hash::{Hash, Hasher};
+ // (pictures received so far: 1 the thumbnail, 2 the sharp render; the latest, or why none came)
+ type Base = std::sync::Arc<std::sync::Mutex<(u8, Option<Result<lightcraft_raster::Rgba8, String>>)>>;
+ type Shown = (u64, u8, lightcraft_engine::export::Watermark, usize, egui::TextureHandle);
+ let t = Tokens::get(ui.ctx());
+ let Some(&id) = app.session.selected().first() else { return };
+ let Some(photo) = app.session.catalog.photo(id).cloned() else { return };
+ let (out_w, out_h) = lightcraft_engine::export::output_size(&photo, &lightcraft_engine::export::ExportOptions { resize, ..Default::default() });
+ let export_short = out_w.min(out_h);
+ // pixels across the dialog, in steps so a scroll bar or a point of layout doesn't re-render
+ let step = 128.0;
+ let px = ((ui.available_width() * ui.ctx().pixels_per_point() / step).ceil() * step).clamp(step, 2048.0) as usize;
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ (id, app.session.catalog.revision, px).hash(&mut h);
+ let key = h.finish();
+ let ctx = ui.ctx().clone();
+ let (base_id, shown_id) = (egui::Id::unique("export-wm-preview-base"), egui::Id::unique("export-wm-preview-shown"));
+ let base = match ctx.data(|d| d.get_temp::<(u64, Base)>(base_id)) {
+ Some((k, base)) if k == key => base,
+ _ => {
+ let base: Base = Default::default();
+ // the thumbnail, then as wide as the dialog (a tall photo up to three times that high)
+ let jobs: Vec<_> = [app.session.thumb_job(id, 512), app.session.render_job(id, px, px * 3, false, true)].into_iter().flatten().collect();
+ // the web build has no worker thread: a full render there would hold up the page
+ #[cfg(target_arch = "wasm32")]
+ let jobs: Vec<_> = jobs.into_iter().take(1).collect();
+ if jobs.is_empty() {
+ *base.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = (1, Some(Err("no such photo".into())));
+ } else {
+ let (out, repaint) = (base.clone(), ctx.clone());
+ let work = move || {
+ for job in jobs {
+ // (a panic in the render is its failure: `RenderJob::run`)
+ let r = job.run().rendered.map(|r| r.image);
+ let mut got = out.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ // a failed sharp render keeps the thumbnail
+ if r.is_ok() || !matches!(got.1, Some(Ok(_))) {
+ *got = (got.0.saturating_add(1), Some(r));
+ repaint.request_repaint();
+ }
+ }
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Err(e) = std::thread::Builder::new().name("lc-watermark-preview".into()).spawn(work) {
+ log::warn!("watermark preview: {e}");
+ }
+ #[cfg(target_arch = "wasm32")]
+ work();
+ }
+ ctx.data_mut(|d| d.insert_temp(base_id, (key, base.clone())));
+ base
+ }
+ };
+ let shown = ctx.data(|d| d.get_temp::<Shown>(shown_id));
+ let stage = base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).0;
+ let tex = match shown {
+ Some((k, g, w, s, tex)) if k == key && g == stage && &w == wm && s == export_short => tex,
+ _ => {
+ let photo_px = match &base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).1 {
+ Some(Ok(img)) => Ok(img.clone()),
+ Some(Err(e)) => Err(Some(e.clone())),
+ None => Err(None),
+ };
+ let mut img = match photo_px {
+ Ok(img) => img,
+ Err(e) => {
+ let note = if e.is_some() { "Preview unavailable" } else { "Loading preview…" };
+ let r = ui
+ .horizontal(|ui| {
+ if e.is_none() {
+ crate::progress::spinner(ui, 12.0);
+ }
+ ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim))
+ })
+ .inner;
+ if let Some(e) = e {
+ r.on_hover_text(e);
+ }
+ return;
+ }
+ };
+ lightcraft_engine::export::draw_watermark_preview(&mut img, wm, export_short);
+ // shown through the monitor profile like every other preview
+ if let Some(d) = app.renderer.display()
+ && let Err(e) = d.profile.from_srgb(&mut img)
+ {
+ log::warn!("display profile: {e}");
+ }
+ let color = std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], &img.as_bytes()));
+ let tex = match shown {
+ Some((.., mut tex)) => {
+ tex.set(color, egui::TextureOptions::LINEAR);
+ tex
+ }
+ None => ctx.load_texture("export-wm-preview", color, egui::TextureOptions::LINEAR),
+ };
+ ctx.data_mut(|d| d.insert_temp(shown_id, (key, stage, wm.clone(), export_short, tex.clone())));
+ tex
+ }
+ };
+ let size = tex.size_vec2();
+ let scale = ui.available_width() / size.x.max(1.0);
+ let r = ui.vertical_centered(|ui| ui.add(egui::Image::new((tex.id(), size * scale)))).inner;
+ crate::widgets::register(ui, "image:exportWatermarkPreview", r.rect);
+}
+
++/// The 16-bit note: LZW's byte dictionary does worse on 16-bit samples than storing them, so
++/// 16-bit LZW TIFFs came out 10-33 % larger than uncompressed ones (issue #2882).
++pub(crate) const TIFF_LZW_NOTE_16: &str =
++ "At 16 bit, LZW is often larger than no compression, and larger and slower than ZIP. Use it only if other software needs LZW.";
++/// The note at 8 bit and 32-bit float: one 8-bit file in #2882 was larger with LZW too.
++pub(crate) const TIFF_LZW_NOTE: &str =
++ "LZW is usually larger and slower than ZIP, and can be larger than no compression. Use it only if other software needs LZW.";
++
++/// The note shown under Compression when a TIFF export uses LZW (none otherwise). The export
++/// keeps LZW: some software reads only LZW TIFFs.
++pub(crate) fn tiff_lzw_note(o: &lightcraft_engine::export::ExportOptions) -> Option<&'static str> {
++ use lightcraft_engine::export::{ExportFormat, OutputDepth, TiffCompression};
++ if o.format != ExportFormat::Tiff || o.tiff_compression != TiffCompression::Lzw {
++ return None;
++ }
++ Some(if o.effective_depth() == OutputDepth::U16 { TIFF_LZW_NOTE_16 } else { TIFF_LZW_NOTE })
++}
++
++/// [`tiff_lzw_note`] for an export preset's params: the hint on presets that write LZW TIFFs.
++pub(crate) fn preset_lzw_note(params: &serde_json::Value) -> Option<&'static str> {
++ tiff_lzw_note(&lightcraft_engine::export::ExportOptions::from_json(params))
++}
++
+/// The Export dialog's choices as `app.export` params (without the folder).
+pub(super) fn export_dialog_params(
+ opts: &lightcraft_engine::export::ExportOptions,
+ full_size: bool,
+ resize: &lightcraft_engine::export::Resize,
+ limit_kb: u32,
+) -> serde_json::Value {
+ let o = lightcraft_engine::export::ExportOptions {
+ resize: (!full_size).then_some(*resize),
+ limit_kb: (limit_kb > 0).then_some(limit_kb),
+ ..opts.clone()
+ };
+ o.to_json()
+}
+
+// ------------------------------------------------------------------------------------------ dialog widgets
+
+/// Two columns of settings-group checkboxes (Copy Settings, Create Preset) plus All / None.
+pub(super) fn group_checklist(ui: &mut egui::Ui, tag: &str, groups: &mut Vec<String>) {
+ let key_of = |g: &SettingsGroup| serde_json::to_value(g).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
+ ui.columns(2, |cols| {
+ for (i, g) in SettingsGroup::ALL.iter().enumerate() {
+ let key = key_of(g);
+ let mut on = groups.contains(&key);
+ let r = cols[i % 2].checkbox(&mut on, crate::i18n::tr(g.label()));
+ crate::widgets::register_response(format!("{tag}:{key}"), r.rect, &r);
+ if r.changed() {
+ if on {
+ groups.push(key);
+ } else {
+ groups.retain(|x| *x != key);
+ }
+ }
+ }
+ });
+ ui.horizontal(|ui| {
+ let all = ui.small_button(crate::i18n::tr("All"));
+ crate::widgets::register(ui, format!("{tag}:all"), all.rect);
+ if all.clicked() {
+ *groups = SettingsGroup::ALL.iter().map(key_of).collect();
+ }
+ let none = ui.small_button(crate::i18n::tr("None"));
+ crate::widgets::register(ui, format!("{tag}:none"), none.rect);
+ if none.clicked() {
+ groups.clear();
+ }
+ });
+}
+
+/// Width of the label column in dialogs.
+pub(super) const LABEL_W: f32 = 78.0;
+
+const fn spec(id: &'static str, label: &'static str, min: f64, max: f64, default: f64, step: f64) -> ControlSpec {
+ ControlSpec { id, label, section: Section::Light, min, max, default, step, decimals: 0, track: Track::Plain }
+}
+
+pub(super) const QUALITY: ControlSpec = spec("export.quality", "Quality", 1.0, 100.0, 90.0, 1.0);
+
+pub(super) const LIMIT_KB: ControlSpec = spec("export.limitKb", "Limit file size (KB, 0 = off)", 0.0, 20_000.0, 0.0, 10.0);
+
+const SIZE_PX: ControlSpec = spec("export.sizePx", "Pixels", 16.0, 20_000.0, 2048.0, 16.0);
+
+const SIZE_W: ControlSpec = spec("export.sizeW", "Width (px)", 16.0, 20_000.0, 2048.0, 16.0);
+
+const SIZE_H: ControlSpec = spec("export.sizeH", "Height (px)", 16.0, 20_000.0, 2048.0, 16.0);
+
+const SIZE_MP: ControlSpec = ControlSpec { decimals: 1, ..spec("export.sizeMp", "Megapixels", 0.1, 100.0, 12.0, 0.1) };
+
+const SIZE_PCT: ControlSpec = spec("export.sizePercent", "Percent", 1.0, 400.0, 50.0, 1.0);
+
+pub(super) const START_NUMBER: ControlSpec = spec("export.startNumber", "Start number", 1.0, 9999.0, 1.0, 1.0);
+
+const PPI: ControlSpec = spec("export.ppi", "Resolution (ppi)", 1.0, 1200.0, 240.0, 1.0);
+
+/// Image Sizing: full size, or a resize mode and its value(s), don't enlarge, ppi.
+pub(super) fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::export::Resize, ppi: &mut u16) {
+ use lightcraft_engine::export::ResizeMode as R;
+ const MODES: [(R, &str); 8] = [
+ (R::LongEdge, "Long Edge"),
+ (R::ShortEdge, "Short Edge"),
+ (R::Width, "Width"),
+ (R::Height, "Height"),
+ (R::WidthHeight, "Width & Height"),
+ (R::Dimensions, "Dimensions"),
+ (R::Megapixels, "Megapixels"),
+ (R::Percent, "Percentage"),
+ ];
+ let r_full = ui.checkbox(full, crate::i18n::tr("Full size"));
+ crate::widgets::register(ui, "check:exportFullSize", r_full.rect);
+ if !*full {
+ field(ui, "Resize to", |ui| {
+ let cur = MODES.iter().find(|m| m.0 == r.mode).map_or("Long Edge", |m| m.1);
+ let before = r.mode;
+ let c = crate::widgets::combo_box("exportResizeMode").width(150.0).selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| {
+ for (m, l) in MODES {
+ ui.selectable_value(&mut r.mode, m, crate::i18n::tr(l));
+ }
+ });
+ crate::widgets::name_combo(&c.response, crate::i18n::tr("Resize"));
+ crate::widgets::register(ui, "combo:exportResizeMode", c.response.rect);
+ if r.mode != before {
+ // a sensible value for the new unit
+ r.value = match r.mode {
+ R::Megapixels => 12.0,
+ R::Percent => 50.0,
+ _ if matches!(before, R::Megapixels | R::Percent) => 2048.0,
+ _ => r.value,
+ };
+ if matches!(r.mode, R::Dimensions | R::WidthHeight) && r.height == 0 {
+ r.height = r.value as u32;
+ }
+ }
+ });
+ let mut v = r.value as f64;
+ let spec = match r.mode {
+ R::Megapixels => &SIZE_MP,
+ R::Percent => &SIZE_PCT,
+ R::Dimensions | R::WidthHeight => &SIZE_W,
+ _ => &SIZE_PX,
+ };
+ if num(ui, spec, &mut v) {
+ r.value = v as f32;
+ }
+ if matches!(r.mode, R::Dimensions | R::WidthHeight) {
+ let mut h = r.height as f64;
+ if num(ui, &SIZE_H, &mut h) {
+ r.height = h as u32;
+ }
+ }
+ let c = ui.checkbox(&mut r.dont_enlarge, crate::i18n::tr("Don't enlarge"));
+ crate::widgets::register(ui, "check:exportDontEnlarge", c.rect);
+ }
+ let mut p = *ppi as f64;
+ if num(ui, &PPI, &mut p) {
+ *ppi = p as u16;
+ }
+}
+
+/// All nine positions supported by both the text and graphic watermark renderer.
+/// Keep them in grid order so bottom-centre and edge-centre anchors are available in Export.
+pub(super) const WM_POSITIONS: [(lightcraft_engine::export::Anchor, &str); 9] = {
+ use lightcraft_engine::export::Anchor::*;
+ [(TopLeft, "↖"), (Top, "↑"), (TopRight, "↗"), (Left, "←"), (Center, "•"), (Right, "→"), (BottomLeft, "↙"), (Bottom, "↓"), (BottomRight, "↘")]
+};
+
+pub(super) const WM_IMAGE_WIDTH: ControlSpec = spec("export.watermarkImageWidth", "Width (% of photo)", 2.0, 100.0, 20.0, 1.0);
+
+pub(super) const WM_SIZE: ControlSpec = spec("export.watermarkSize", "Size (% of short edge)", 1.0, 15.0, 3.5, 0.5);
+
+pub(super) const WM_OPACITY: ControlSpec = spec("export.watermarkOpacity", "Opacity (%)", 5.0, 100.0, 70.0, 1.0);
+
+pub(super) const WM_INSET_X: ControlSpec =
+ ControlSpec { decimals: 1, ..spec("export.watermarkInsetX", "Horizontal inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) };
+
+pub(super) const WM_INSET_Y: ControlSpec =
+ ControlSpec { decimals: 1, ..spec("export.watermarkInsetY", "Vertical inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) };
+
+#[cfg(test)]
+mod watermark_position_tests {
+ use super::WM_POSITIONS;
+ use lightcraft_engine::export::Anchor;
+
+ #[test]
+ fn export_dialog_offers_every_rendered_anchor_exactly_once() {
+ let anchors = [
+ Anchor::TopLeft,
+ Anchor::Top,
+ Anchor::TopRight,
+ Anchor::Left,
+ Anchor::Center,
+ Anchor::Right,
+ Anchor::BottomLeft,
+ Anchor::Bottom,
+ Anchor::BottomRight,
+ ];
+ assert_eq!(WM_POSITIONS.len(), anchors.len());
+ for anchor in anchors {
+ assert_eq!(WM_POSITIONS.iter().filter(|(position, _)| *position == anchor).count(), 1);
+ }
+ }
+}
++
++#[cfg(test)]
++mod tiff_lzw_note_tests {
++ use std::time::Duration;
++
++ use lightcraft_engine::export::{ExportFormat, ExportOptions, TiffCompression};
++ use serde_json::json;
++
++ use super::{TIFF_LZW_NOTE, TIFF_LZW_NOTE_16, export_dialog_params, preset_lzw_note, tiff_lzw_note};
++ use crate::headless::Headless;
++ use crate::state::Dialog;
++ use crate::{LightcraftApp, Services};
++
++ const T: Duration = Duration::from_secs(20);
++
++ fn tiff(compression: TiffCompression, bit_depth: Option<u8>) -> ExportOptions {
++ ExportOptions { format: ExportFormat::Tiff, tiff_compression: compression, bit_depth, ..Default::default() }
++ }
++
++ // Issue #2882: the note shows for LZW only, worded more strongly at 16 bit (TIFF's default depth)
++ #[test]
++ fn lzw_gets_a_note_stronger_at_16_bit() {
++ assert_eq!(tiff_lzw_note(&tiff(TiffCompression::Lzw, None)), Some(TIFF_LZW_NOTE_16), "TIFF defaults to 16-bit");
++ assert_eq!(tiff_lzw_note(&tiff(TiffCompression::Lzw, Some(16))), Some(TIFF_LZW_NOTE_16));
++ assert_eq!(tiff_lzw_note(&tiff(TiffCompression::Lzw, Some(8))), Some(TIFF_LZW_NOTE));
++ assert_eq!(tiff_lzw_note(&tiff(TiffCompression::Lzw, Some(32))), Some(TIFF_LZW_NOTE));
++ for compression in [TiffCompression::None, TiffCompression::Deflate, TiffCompression::PackBits] {
++ for depth in [None, Some(8), Some(16), Some(32)] {
++ assert_eq!(tiff_lzw_note(&tiff(compression, depth)), None, "{compression:?} {depth:?}");
++ }
++ }
++ // the setting only matters for TIFF: a JPEG preset that carries it gets no note
++ let jpeg = ExportOptions { format: ExportFormat::Jpeg, tiff_compression: TiffCompression::Lzw, ..Default::default() };
++ assert_eq!(tiff_lzw_note(&jpeg), None);
++ assert!(TIFF_LZW_NOTE_16.contains("16 bit") && TIFF_LZW_NOTE.contains("other software needs LZW"));
++ }
++
++ // Presets that write LZW TIFFs carry the same hint; the built-in ones don't write LZW
++ #[test]
++ fn presets_with_lzw_get_the_same_hint() {
++ assert_eq!(preset_lzw_note(&json!({"format": "tiff", "tiffCompression": "lzw"})), Some(TIFF_LZW_NOTE_16));
++ assert_eq!(preset_lzw_note(&json!({"format": "tiff", "tiffCompression": "LZW", "bitDepth": 8})), Some(TIFF_LZW_NOTE));
++ assert_eq!(preset_lzw_note(&json!({"format": "tiff", "tiffCompression": "zip"})), None);
++ assert_eq!(preset_lzw_note(&json!({"format": "tiff"})), None, "ZIP is the default");
++ for p in lightcraft_engine::export::builtin_presets() {
++ assert_eq!(preset_lzw_note(&p.params), None, "{}", p.name);
++ }
++ }
++
++ // The note never changes the choice: the dialog exports exactly the compression picked
++ #[test]
++ fn the_dialog_keeps_lzw_as_picked() {
++ for depth in [None, Some(8), Some(16), Some(32)] {
++ let o = tiff(TiffCompression::Lzw, depth);
++ let params = export_dialog_params(&o, true, &Default::default(), 0);
++ assert_eq!(ExportOptions::from_json(&params).tiff_compression, TiffCompression::Lzw, "{depth:?}: {params}");
++ }
++ }
++
++ fn set(h: &mut Headless, compression: TiffCompression, bit_depth: Option<u8>) {
++ if let Some(Dialog::Export { opts, .. }) = &mut h.app.ui.dialog {
++ opts.format = ExportFormat::Tiff;
++ opts.tiff_compression = compression;
++ opts.bit_depth = bit_depth;
++ } else {
++ panic!("no Export dialog");
++ }
++ h.settle(T);
++ }
++
++ fn note_rect(h: &Headless) -> Option<egui::Rect> {
++ h.app.widgets.iter().find(|(w, _)| w == "note:exportTiffLzw").map(|(_, r)| *r)
++ }
++
++ fn widget(h: &Headless, id: &str) -> egui::Rect {
++ h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}"))
++ }
++
++ // Scenario: in the Export dialog, picking LZW for a TIFF shows the note under Compression; ZIP
++ // and None show none, and the choice stays LZW
++ #[test]
++ fn export_dialog_shows_the_lzw_note_under_compression() {
++ let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() };
++ let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services);
++ let mut h = Headless::new(app, [1600.0, 1000.0], 1.0);
++ h.settle(T);
++ let r = h.request("engine.execute", json!({"command": "dialog.export", "params": {}}), T);
++ assert_eq!(r["ok"], true, "{r}");
++ h.settle(T);
++ for compression in [TiffCompression::Deflate, TiffCompression::None] {
++ set(&mut h, compression, None);
++ assert!(note_rect(&h).is_none(), "{compression:?} has no note");
++ }
++ for depth in [None, Some(8), Some(32)] {
++ set(&mut h, TiffCompression::Lzw, depth);
++ let note = note_rect(&h).unwrap_or_else(|| panic!("LZW at {depth:?} shows the note"));
++ // under the Compression choice, inside the dialog
++ assert!(note.top() >= widget(&h, "button:exportTiffCompression-1").bottom() - 1.0, "{note:?}");
++ assert!(widget(&h, "dialog:window").contains_rect(note), "{note:?}");
++ let Some(Dialog::Export { opts, .. }) = &h.app.ui.dialog else { panic!("dialog closed") };
++ assert_eq!(opts.tiff_compression, TiffCompression::Lzw, "the note leaves the choice alone");
++ }
++ set(&mut h, TiffCompression::Deflate, None);
++ assert!(note_rect(&h).is_none(), "back to ZIP: the note goes");
++ }
++}
diff --cc crates/ui-egui/src/panels/grid.rs
index 5064b8d40,a904f328c..2fd1aa919
--- a/crates/ui-egui/src/panels/grid.rs
+++ b/crates/ui-egui/src/panels/grid.rs
@@@ -1491,7 -1413,12 +1491,12 @@@ fn context_menu_locate_and_export(app:
}
crate::widgets::menu_button(ui, crate::i18n::tr("Export with Preset"), |ui| {
for (p, _) in app.session.all_export_presets() {
- if ui.button(&p.name).clicked() {
+ let r = ui.button(&p.name);
- let r = match crate::panels::dialogs::preset_lzw_note(&p.params) {
++ let r = match crate::dialogs::preset_lzw_note(&p.params) {
+ Some(note) => r.on_hover_text(crate::i18n::tr(note)),
+ None => r,
+ };
+ if r.clicked() {
match app.run("app.export", json!({"preset": p.name, "background": true})) {
Ok(r) if r.get("background").is_some() => {}
Ok(r) => {
diff --cc docs/parity-checklist.md
index 74bd9b4e5,c02e9c686..2f0ce61cb
--- a/docs/parity-checklist.md
+++ b/docs/parity-checklist.md
@@@ -389,24 -389,24 +389,24 @@@ differences and missing bindings are i
| Id | Feature | Tier | Status | Evidence | Missing / notes |
|---|---|---|---|---|---|
-| LR-EXP-DIALOG | Export dialog | P0 | ✅ | `cmd:dialog.export`, `cmd:app.export` (`preset`), `cmd:export.presets`, `cmd:export.savePreset`, `cmd:export.deletePreset`, `crates/ui-egui/src/panels/dialogs.rs`, `crates/engine/src/export.rs` | batch export; built-in presets (JPEG Small 2048 px / Large full size, Original + Settings, DNG) and saved user presets (library prefs) load into the dialog; deleting a user preset is command-only; on a short window the options scroll and Cancel / OK stay visible (LR-BEHAV-DIALOGS, issue #781) |
-| LR-EXP-TYPE | File types | P0 | ✅ | `cmd:app.export` (`format`), `crates/engine/src/export.rs` (`ExportFormat`), `crates/engine/src/tests_export.rs` | JPEG, PNG, TIFF, PSD (flat, 8/16-bit, no layers: `crates/codecs/src/psd.rs`), WebP, AVIF, JPEG XL (issue #247: `jixel`, native only; lossy with quality or lossless, 8/16-bit, effort fast/normal (jixel's slowest search left out: jxl-oxide misdecodes its files), progressive, EXIF/XMP boxes; lossy files in Adobe RGB / ProPhoto are written as Rec. 2020, lossless keep any space via ICC; `crates/codecs/src/jxl_encode.rs`), DNG (raw photos: lossless re-encode with the edits in the embedded XMP; a raw without colour matrices of its own, as a NEF, gets the colour it opens with as `ColorMatrix1` / `ForwardMatrix1` / `AsShotNeutral`, also in Convert / Copy as DNG, so other raw converters open it, issue #1745), Original (+ XMP sidecar). Non-raw → DNG not supported; no JPEG XL export in the web build. Opaque 8-bit PNG/TIFF/WebP exports omit the redundant alpha channel; real transparency is retained (#1670). |
-| LR-EXP-DIM | Output size | P0 | ✅ | `cmd:app.export` (`longEdge`, `shortEdge`, `width`, `height`, `fit`, `megapixels`, `percent`, `dontEnlarge`, `ppi`), `crates/engine/src/export.rs` (`Resize`), `crates/ui-egui/src/panels/dialogs.rs` | full size = the cropped native size (no longer upscaled); both of Lightroom's boxes: Dimensions (W × H fits either orientation) and Width & Height (`fit: widthHeight`, each edge bound to its own number, #1620); ppi written to JFIF / pHYs / TIFF tags; at most 65,535 px an edge, and an export enlarged past the photo's size stops at 512 megapixels (Lightroom's ceiling too) and is refused, with the size it would need, when it needs more memory than the computer has (it aborted the process before) |
+| LR-EXP-DIALOG | Export dialog | P0 | ✅ | `cmd:dialog.export`, `cmd:app.export` (`preset`), `cmd:export.presets`, `cmd:export.savePreset`, `cmd:export.deletePreset`, `crates/ui-egui/src/dialogs.rs`, `crates/engine/src/export.rs` | batch export; built-in presets (JPEG Small 2048 px / Large full size, Original + Settings, DNG) and saved user presets (library prefs) load into the dialog; deleting a user preset is command-only; on a short window the options scroll and Cancel / OK stay visible (LR-BEHAV-DIALOGS, issue #781) |
+| LR-EXP-TYPE | File types | P0 | ✅ | `cmd:app.export` (`format`), `crates/engine/src/export.rs` (`ExportFormat`), `crates/engine/src/tests/export.rs` | JPEG, PNG, TIFF, PSD (flat, 8/16-bit, no layers: `crates/codecs/src/psd.rs`), WebP, AVIF, JPEG XL (issue #247: `jixel`, native only; lossy with quality or lossless, 8/16-bit, effort fast/normal (jixel's slowest search left out: jxl-oxide misdecodes its files), progressive, EXIF/XMP boxes; lossy files in Adobe RGB / ProPhoto are written as Rec. 2020, lossless keep any space via ICC; `crates/codecs/src/jxl_encode.rs`), DNG (raw photos: lossless re-encode with the edits in the embedded XMP; a raw without colour matrices of its own, as a NEF, gets the colour it opens with as `ColorMatrix1` / `ForwardMatrix1` / `AsShotNeutral`, also in Convert / Copy as DNG, so other raw converters open it, issue #1745), Original (+ XMP sidecar). Non-raw → DNG not supported; no JPEG XL export in the web build. Opaque 8-bit PNG/TIFF/WebP exports omit the redundant alpha channel; real transparency is retained (#1670). |
+| LR-EXP-DIM | Output size | P0 | ✅ | `cmd:app.export` (`longEdge`, `shortEdge`, `width`, `height`, `fit`, `megapixels`, `percent`, `dontEnlarge`, `ppi`), `crates/engine/src/export.rs` (`Resize`), `crates/ui-egui/src/dialogs.rs` | full size = the cropped native size (no longer upscaled); both of Lightroom's boxes: Dimensions (W × H fits either orientation) and Width & Height (`fit: widthHeight`, each edge bound to its own number, #1620); ppi written to JFIF / pHYs / TIFF tags; at most 65,535 px an edge, and an export enlarged past the photo's size stops at 512 megapixels (Lightroom's ceiling too) and is refused, with the size it would need, when it needs more memory than the computer has (it aborted the process before) |
| LR-EXP-QUALITY | JPEG quality | P0 | ✅ | `cmd:app.export` (`quality`, `limitKb`), `crates/codecs/src/jpeg_par.rs` | 4:4:4 chroma (4:2:0 when a file-size limit is set); Huffman tables made for each image from its own symbol counts (T.81 Annex K.2) instead of the example tables: the same pixels, 12–14 % smaller files at quality 80–100 on a 24 MP photo-like image, still interleaved baseline (issue #1373); ordinary and HDR gain map JPEGs search quality up to the requested maximum to fit `limitKb`, including gain map and metadata, or return an error. Tested by `size_limit_respected` and `hdr_jpeg_size_limit_respected`. |
| LR-EXP-BITDEPTH | Bit depth | P1 | ✅ | `cmd:app.export` (`bitDepth`), `crates/pipeline/src/output.rs` (`OutputDepth`), `crates/engine/src/export.rs` | 16-bit PNG/TIFF/JPEG XL rendered at 16 bits (TIFF defaults to 16), 32-bit float linear TIFF with a linear profile, 10-bit AVIF; high-bit-depth renders run on the CPU |
- | LR-EXP-COMPRESSION | TIFF compression | P1 | ✅ | `cmd:app.export` (`tiffCompression`: none / lzw / zip) | |
+ | LR-EXP-COMPRESSION | TIFF compression | P1 | ✅ | `cmd:app.export` (`tiffCompression`: none / lzw / zip) | ZIP is the default. LZW is usually larger and slower than ZIP, and at 16 bit often larger than none (#2882); the export dialog notes this when LZW is picked |
| LR-EXP-COLORSPACE | Output colour space | P0 | ✅ | `cmd:app.export` (`colorSpace`), `crates/pipeline/src/output.rs`, `crates/engine/src/export.rs` | sRGB, Display P3, Adobe RGB (1998) compatible, ProPhoto RGB, Rec. 2020: rendered from the working space with gamut mapping into the target gamut (CPU + GPU), own ICC profile embedded; AVIF stays sRGB (muxer has no ICC); lossy JPEG XL declares sRGB / P3 / Rec. 2020 (Adobe RGB and ProPhoto written as Rec. 2020), lossless JPEG XL embeds the profile |
-| LR-EXP-HDR | HDR output | P2 | 🟡 | `cmd:app.export`, `crates/ui-egui/src/panels/dialogs.rs` | HDR output checkbox in the export dialog: gain map JPEG, PQ or HLG AVIF, PQ PNG, PQ JPEG XL, float TIFF; no HDR presets yet |
+| LR-EXP-HDR | HDR output | P2 | 🟡 | `cmd:app.export`, `crates/ui-egui/src/dialogs.rs` | HDR output checkbox in the export dialog: gain map JPEG, PQ or HLG AVIF, PQ PNG, PQ JPEG XL, float TIFF; no HDR presets yet |
| LR-EXP-SHARPEN | Output sharpening | P1 | ✅ | `cmd:app.export` (`sharpen`, `sharpenAmount`) | |
-| LR-EXP-METADATA | Metadata policy | P1 | ✅ | `cmd:app.export` (`metadata`, `removeLocation`) | |
+| LR-EXP-METADATA | Metadata policy | P1 | ✅ | `cmd:app.export` (`metadata`, `removeLocation`) | Original export is refused when Remove Location Info is on and the source embeds GPS or a nonblank sublocation, city, state or country; rendered exports and XMP sidecars remove those modeled fields |
| LR-EXP-WATERMARK | Watermark | P1 | 🟡 | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text uses Inter SemiBold, the existing Mincho-first CJK chain, then Thai faces from `CRAFT_FONTS_DIR`, shared with contact-sheet captions and slideshow overlays (#2052, partial). Horizontal Thai mark positioning remains incomplete. Arabic export fallback is deferred until joining and bidi reordering exist; UI font fallback is unchanged. Text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (EXIF orientation applied before sizing; oversized graphics fit the rotated image bounds without stretching, tested by `graphic_watermark_honours_exif_orientation` and `graphic_watermark_keeps_aspect_when_fitted_and_rotated`; `image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` |
| LR-EXP-NAMING | File naming | P1 | ✅ | `cmd:app.export` (`naming`, `startNumber`), `crates/engine/src/rename.rs` (`expand_tokens`) | one template language for export, Rename Photos and import renaming: `{name}`, `{num}` (number at the end of the name), `{seq}` / `{seq:N}`, `{date}` / `{date:%Y-%m-%d}`, `{folder}`, `{camera}`, `{lens}`, `{iso}`, `{rating}`, `{title}`, `{creator}`, `{ext}`; free-form template rather than a list of named schemes |
-| LR-EXP-LOCATION | Destination folder | P0 | ✅ | `cmd:app.export` (`dir`, `destinationMode`: specificFolder / sameAsOriginal, `subfolder`, `conflict`: unique / overwrite / skip), `cmd:export.checkTarget`, `crates/ui-egui/src/panels/dialogs.rs` (Choose… folder picker), `crates/engine/src/originals.rs`, `crates/catalog/src/safe_file.rs` | folder picker on the desktop; Export to: Specific folder or Same folder as original photo (each photo into its original's folder + the subfolder; a demo/browser photo or a missing folder is that photo's error, issue #956); existing files get `-2`, `-3`… by default; the policy covers a file and its sidecars together; a catalogued original (or its sidecar) is never written over, whatever the policy or an exact `path` (export, `ui.render`, MCP `render_photo`, merge `previewPath`, `lightcraft-cli render`); files are written to a temp file and renamed into place (issue #93; not synced file by file — exports can be made again, issue #134) |
+| LR-EXP-LOCATION | Destination folder | P0 | ✅ | `cmd:app.export` (`dir`, `destinationMode`: specificFolder / sameAsOriginal, `subfolder`, `conflict`: unique / overwrite / skip), `cmd:export.checkTarget`, `crates/ui-egui/src/dialogs.rs` (Choose… folder picker), `crates/engine/src/originals.rs`, `crates/catalog/src/safe_file.rs` | folder picker on the desktop; Export to: Specific folder or Same folder as original photo (each photo into its original's folder + the subfolder; a demo/browser photo or a missing folder is that photo's error, issue #956); existing files get `-2`, `-3`… by default; the policy covers a file and its sidecars together; a catalogued original (or its sidecar) is never written over, whatever the policy or an exact `path` (export, `ui.render`, MCP `render_photo`, merge `previewPath`, `lightcraft-cli render`); files are written to a temp file and renamed into place (issue #93; not synced file by file — exports can be made again, issue #134) |
| LR-EXP-PREVIOUS | Export with previous settings | P0 | ✅ | `cmd:app.exportPrevious`, `cmd:dialog.export` | last options persist in prefs.json; dialog prefilled; no named export presets yet |
| LR-EXP-DNGOPT | DNG options | P2 | 🟡 | `cmd:app.export` (`dngCompression`), `crates/engine/src/export.rs` | compression: lossless JPEG (default), ZIP, none, or lossy (demosaiced linear camera RGB as 8-bit JPEG tiles at the export quality, a `LinearizationTable` restoring linear values, scaled to the resize long edge when set; `crates/raw/tests/it/lossy_dng.rs`); no embedded JPEG preview size |
-| LR-EXP-ORIGINAL | Original + XMP | P1 | ✅ | `cmd:app.export` (`format: original`), `crates/engine/src/tests_export.rs` | file copied byte for byte, sidecar named after the output and subject to the conflict policy |
+| LR-EXP-ORIGINAL | Original + XMP | P1 | ✅ | `cmd:app.export` (`format: original`), `crates/engine/src/tests/export.rs` | file copied byte for byte, sidecar named after the output and subject to the conflict policy |
| LR-EXP-RENDERDNG | Render to DNG (Classic 15.5) | P2 | 🟡 | `cmd:app.export` (`format: rendereddng`), `crates/raw/src/dngwrite.rs` (`write_rendered_dng`), `crates/raw/tests/it/rendered_dng.rs` | export format `rendereddng` (dialog: Format DNG, "DNG of: Rendered photo"): the rendered photo (edit, crop, size, sharpening, watermark baked in) as a LinearRaw DNG of 16-bit float Deflate tiles in the export colour space, with `ColorMatrix1` / `ForwardMatrix1` for that space, a neutral `AsShotNeutral` and an identity `ProfileToneCurve` so raw converters show it as rendered; HDR edits keep highlights above white. Not a menu command on selected photos (Lightroom adds the DNG to the catalog next to the original); export only |
-| LR-EXP-PHOTOS | Export to the system photo library | P2 | 🟡 | `cmd:app.export` (`addToPhotos`, `photosAlbum`), `cmd:export.addToPhotos`, `cmd:export.photosImports`, `crates/engine/src/apple_photos.rs`, `crates/ui-egui/src/panels/dialogs.rs`, `packaging/macos/entitlements.plist`, `docs/apple-photos.md` | macOS: the exported files go to Apple Photos through Apple Events to its import command (a constant AppleScript run by `/usr/bin/osascript`; album names and paths are separate arguments), into a top-level album of exactly that name, made when missing (several of that name: refused); the Export dialog's Add to Apple Photos, Export with Previous, presets, MCP and `lightcraft-cli` all reach it; imports are jobs, off the UI thread in the desktop app and awaited in one-shot headless runs, one at a time, reserved by an export before it writes; permission, missing Photos, timeouts and partial imports are reported; the packaged app carries the Apple Events entitlement and usage text. Tested end to end with the packaged app on macOS 26.6.2 / Photos 11.0 (manual steps in `docs/apple-photos.md`). Other platforms' photo libraries are not covered |
+| LR-EXP-PHOTOS | Export to the system photo library | P2 | 🟡 | `cmd:app.export` (`addToPhotos`, `photosAlbum`), `cmd:export.addToPhotos`, `cmd:export.photosImports`, `crates/engine/src/apple_photos.rs`, `crates/ui-egui/src/dialogs.rs`, `packaging/macos/entitlements.plist`, `docs/apple-photos.md` | macOS: the exported files go to Apple Photos through Apple Events to its import command (a constant AppleScript run by `/usr/bin/osascript`; album names and paths are separate arguments), into a top-level album of exactly that name, made when missing (several of that name: refused); the Export dialog's Add to Apple Photos, Export with Previous, presets, MCP and `lightcraft-cli` all reach it; imports are jobs, off the UI thread in the desktop app and awaited in one-shot headless runs, one at a time, reserved by an export before it writes; permission, missing Photos, timeouts and partial imports are reported; the packaged app carries the Apple Events entitlement and usage text. Tested end to end with the packaged app on macOS 26.6.2 / Photos 11.0 (manual steps in `docs/apple-photos.md`). Other platforms' photo libraries are not covered |
| LR-EXP-PSD | Round trip to an external editor | P2 | ✅ | `cmd:photo.editExternal`, `cmd:photo.editInPhotoCraft`, `cmd:photo.editInExternal`, `cmd:photo.openOriginalInExternal`, `crates/engine/src/cmd/convert.rs`, `apps/lightcraft/src/editors.rs` | an `-Edit` copy of each selected photo (up to 50 at once, issue #920) with the edits (PSD or TIFF, 16- or 8-bit, Adobe RGB / ProPhoto / P3 / sRGB, chosen per editor in Settings ▸ General ▸ External Editing) next to the original, added stacked on top of it and opened in PhotoCraft (found where its installers put it; a PSD by default, which PhotoCraft saves back to in place) or the other editor set there (or the system default); also on the photo's right-click menu (Edit In). Re-read when LightCraft is focused again. Open Original in Other Editor (RAW, no copy) hands that editor each selected photo's original file itself instead (a raw stays a raw, e.g. for DxO PhotoLab: no render, no copy, nothing added; several photos go to one start of the editor, which DxO PhotoLab 8 needs to get them all; demo photos, missing files and originals that are not a file type LightCraft reads are skipped with the reason, so a path an imported catalog named cannot hand a program to the system opener, issue #2135). Imported PSD/PSB photos retain embedded capture dates; PSD edit copies retain EXIF/XMP fields in the catalog and All Metadata. Original with Remove Location Info is refused when embedded PSD/PSB GPS is detected. No "Edit a copy / Edit original" choice for non-raw files yet |
## T. Share (SHARE)