diff --git a/Cargo.lock b/Cargo.lock index 9ca643332a..7573716db5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -146,6 +146,12 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "adler32" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" + [[package]] name = "aead" version = "0.5.2" @@ -1718,6 +1724,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "dary_heap" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe" + [[package]] name = "dashmap" version = "6.2.1" @@ -2154,7 +2166,7 @@ dependencies = [ "pollster 1.0.1", "serde", "tempfile", - "toml", + "toml 1.1.6+spec-1.1.0", "wgpu", ] @@ -2292,6 +2304,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "enumn" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "env_filter" version = "0.1.4" @@ -2385,7 +2408,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4421,6 +4444,8 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3" dependencies = [ + "rayon", + "rayon-core", "tracing", ] @@ -4673,7 +4698,7 @@ dependencies = [ "lcc-raw", "serde", "serde_json", - "toml", + "toml 1.1.6+spec-1.1.0", ] [[package]] @@ -4805,6 +4830,7 @@ dependencies = [ "lcc-meta", "lcc-raster", "lcc-testkit", + "lcc-tiff", "moxcms 0.9.1", "png 0.18.1", "proptest", @@ -4925,6 +4951,13 @@ dependencies = [ "serde_json", ] +[[package]] +name = "lcc-dnglab" +version = "26.49.1" +dependencies = [ + "rawler", +] + [[package]] name = "lcc-engine" version = "26.49.1" @@ -4954,6 +4987,7 @@ dependencies = [ "lcc-denoise-core", "lcc-develop", "lcc-diag", + "lcc-dnglab", "lcc-faces", "lcc-fetch", "lcc-fidelity", @@ -5011,7 +5045,7 @@ dependencies = [ "sha2 0.10.9", "thiserror 2.0.21", "tiff", - "toml", + "toml 1.1.6+spec-1.1.0", "trash", "unicode-normalization", "unicode-segmentation", @@ -5865,6 +5899,30 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "libflate" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "561a8da1a50e1428d3c51321dafeca849df992a5bb67720c386131234caba82e" +dependencies = [ + "adler32", + "crc32fast", + "dary_heap", + "libflate_lz77", + "no_std_io2", +] + +[[package]] +name = "libflate_lz77" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7a10e427698aef6eef269482776debfef63384d30f13aad39a1a95e0e098fd" +dependencies = [ + "hashbrown 0.16.1", + "no_std_io2", + "rle-decode-fast", +] + [[package]] name = "libfuzzer-sys" version = "0.4.13" @@ -7722,7 +7780,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit", + "toml_edit 0.25.15+spec-1.1.0", ] [[package]] @@ -8087,6 +8145,40 @@ dependencies = [ "objc2-quartz-core 0.3.2", ] +[[package]] +name = "rawler" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51cb9d46a5b34946878eb236d1180adec0806eee260738ce299517b083a232e8" +dependencies = [ + "backtrace", + "bitstream-io 4.10.0", + "byteorder", + "chrono", + "enumn", + "glob", + "hex", + "image", + "itertools 0.14.0", + "jxl-oxide", + "lazy_static", + "libflate", + "log", + "md5", + "memmap2", + "multiversion", + "num", + "num_enum", + "rayon", + "rustc_version", + "serde", + "thiserror 2.0.21", + "toml 0.8.23", + "uuid", + "weezl 0.1.12", + "zerocopy", +] + [[package]] name = "rawpointer" version = "0.2.1" @@ -8296,6 +8388,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rle-decode-fast" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422" + [[package]] name = "roxmltree" version = "0.20.0" @@ -8521,7 +8619,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -8807,6 +8905,15 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "serde_spanned" version = "1.1.1" @@ -9360,10 +9467,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -9518,6 +9625,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + [[package]] name = "toml" version = "1.1.6+spec-1.1.0" @@ -9526,11 +9645,20 @@ checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" dependencies = [ "indexmap", "serde_core", - "serde_spanned", - "toml_datetime", + "serde_spanned 1.1.1", + "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", "toml_writer", - "winnow", + "winnow 1.0.4", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", ] [[package]] @@ -9542,6 +9670,20 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + [[package]] name = "toml_edit" version = "0.25.15+spec-1.1.0" @@ -9549,9 +9691,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" dependencies = [ "indexmap", - "toml_datetime", + "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", - "winnow", + "winnow 1.0.4", ] [[package]] @@ -9560,9 +9702,15 @@ version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" dependencies = [ - "winnow", + "winnow 1.0.4", ] +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "toml_writer" version = "1.1.2+spec-1.1.0" @@ -9818,6 +9966,7 @@ version = "1.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" dependencies = [ + "getrandom 0.4.3", "js-sys", "serde_core", "wasm-bindgen", @@ -10453,7 +10602,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -10848,6 +10997,15 @@ dependencies = [ "xkbcommon-dl", ] +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "1.0.4" @@ -10873,7 +11031,7 @@ version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0986a8b1d586b7d3e4fe3d9ea39fb451ae22869dcea4aa109d287a374d866087" dependencies = [ - "toml", + "toml 1.1.6+spec-1.1.0", "version_check", ] @@ -10995,7 +11153,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", - "toml", + "toml 1.1.6+spec-1.1.0", "zip", ] @@ -11081,7 +11239,7 @@ dependencies = [ "uds_windows", "uuid", "windows-sys 0.61.2", - "winnow", + "winnow 1.0.4", "zbus_macros", "zbus_names", "zvariant", @@ -11133,7 +11291,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" dependencies = [ "serde", - "winnow", + "winnow 1.0.4", "zvariant", ] @@ -11144,7 +11302,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" dependencies = [ "serde", - "winnow", + "winnow 1.0.4", "zbus_names", "zvariant", ] @@ -11327,7 +11485,7 @@ dependencies = [ "endi", "enumflags2", "serde", - "winnow", + "winnow 1.0.4", "zcheapstr", "zvariant_derive", "zvariant_utils", @@ -11356,5 +11514,5 @@ dependencies = [ "quote", "serde", "syn 3.0.6", - "winnow", + "winnow 1.0.4", ] diff --git a/Cargo.toml b/Cargo.toml index 86bb0c51c3..6d4e2c4ebb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ lcc-faces = { path = "crates/faces" } lcc-sysmem = { path = "crates/sysmem" } lcc-diag = { path = "crates/diag" } lcc-libraw = { path = "crates/libraw" } +lcc-dnglab = { path = "crates/dnglab" } lcc-hdrmeta = { path = "crates/hdrmeta" } lcc-gpumem = { path = "crates/gpumem" } lcc-onnxrt = { path = "crates/onnxrt" } @@ -103,6 +104,8 @@ base64 = "0.22" serde = { version = "1", features = ["derive", "rc"] } serde_json = { version = "1", features = ["float_roundtrip"] } log = "0.4" +# dnglab's raw decoder library (LGPL-2.1), used only by crates/dnglab +rawler = { version = "0.8", default-features = false } # the control port token (`apps/app`) getrandom = "0.3" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; CLAUDE.md). diff --git a/NOTICE b/NOTICE index 491c296f97..390e00e56f 100644 --- a/NOTICE +++ b/NOTICE @@ -67,6 +67,12 @@ used under the GNU LGPL 2.1 (crates/libraw/LICENSE-LibRaw-LGPL-2.1.txt; LibRaw a binary is offered under GPL-3.0-or-later. The source of the LibRaw version built is at that address; the crate's C shim (crates/libraw/shim/shim.cpp) is our own work and calls LibRaw's public API only. +Builds with the `dnglab` feature (the desktop app and the CLI, see crates/dnglab) contain rawler +(https://github.com/dnglab/dnglab, the crates.io `rawler` crate), the decoder library of the dnglab project, +Copyright Daniel Vogelbacher, Pedro Côrte-Real and the dnglab contributors, unmodified, used under the GNU LGPL 2.1 +(crates/dnglab/LICENSE-rawler-LGPL-2.1.txt); such a binary is offered under GPL-3.0-or-later. The wrapper in +crates/dnglab is our own work and calls rawler's public API only. + crates/pipeline/src/tone_eq.rs (the Tone Equalizer) is translated from darktable's src/iop/toneequal.c (https://github.com/darktable-org/darktable), Copyright 2018-2026 Aurélien Pierre and the darktable developers, used under the GNU GPL 3.0 or later (LICENSE-GPL-3.0.txt): the nine-band Gaussian radial-basis correction curve diff --git a/apps/app/Cargo.toml b/apps/app/Cargo.toml index 3c36b5f3be..4e91a2f1df 100644 --- a/apps/app/Cargo.toml +++ b/apps/app/Cargo.toml @@ -15,7 +15,7 @@ workspace = true [features] # The upstream project's own AI Denoise model (MIT OR Apache-2.0) is offered as a download -default = ["denoise", "own-model", "heif", "onnxruntime", "libraw"] +default = ["denoise", "own-model", "heif", "onnxruntime", "libraw", "dnglab"] denoise = ["lcc-engine/denoise", "lcc-cli/denoise"] rawnind-model = ["denoise", "lcc-engine/rawnind-model", "lcc-cli/rawnind-model"] realesrgan-model = ["denoise", "lcc-engine/realesrgan-model", "lcc-cli/realesrgan-model"] @@ -33,6 +33,8 @@ audio-out = ["lcc-engine/audio-out"] # LibRaw as a per-camera raw decoder (C++; linked only when LIBRAW_DIR or LIBRAW_SYSTEM=1 is set, see # crates/libraw/build.rs; otherwise Settings shows it unavailable). libraw = ["lcc-engine/libraw", "lcc-cli/libraw"] +# dnglab's decoder (rawler, pure Rust) as a per-camera raw decoder. +dnglab = ["lcc-engine/dnglab", "lcc-cli/dnglab"] [dependencies] # the command-line tool, run when the program is started as `` (`main`); its features follow diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.toml index 698862083c..d27993cd35 100644 --- a/apps/cli/Cargo.toml +++ b/apps/cli/Cargo.toml @@ -45,7 +45,7 @@ serde_json = { workspace = true } dhat = { workspace = true, optional = true } [features] -default = ["denoise", "heif", "libraw"] +default = ["denoise", "heif", "libraw", "dnglab"] denoise = ["lcc-engine/denoise"] rawnind-model = ["denoise", "lcc-engine/rawnind-model"] realesrgan-model = ["denoise", "lcc-engine/realesrgan-model"] @@ -59,6 +59,8 @@ dhat-heap = ["dep:dhat"] # LibRaw as a per-camera raw decoder (C++; linked only when LIBRAW_DIR or LIBRAW_SYSTEM=1 is set, see # crates/libraw/build.rs, otherwise the choice is shown as unavailable). libraw = ["lcc-engine/libraw"] +# dnglab's decoder (rawler, pure Rust) as a per-camera raw decoder. +dnglab = ["lcc-engine/dnglab"] # Open HEIC/HEIF photos (the lcc-heif crate, pure Rust). On by default, as in the app; # `--no-default-features --features denoise` leaves HEVC out. diff --git a/apps/cli/src/lib.rs b/apps/cli/src/lib.rs index 6ac35db23c..3e01d61cbe 100644 --- a/apps/cli/src/lib.rs +++ b/apps/cli/src/lib.rs @@ -1134,16 +1134,9 @@ fn render(args: &[String]) -> Result<(), String> { // Add to Apple Photos: refused before anything is written when it can't be done let after = s.after_export(&o)?; let e = export_photo(&mut s, lcc_engine::catalog::PhotoId(id), &o, 1)?; - // never over the input (or its sidecar), however it is spelled: `render IMG.jpg -o IMG.jpg` - let sidecars: Vec<(String, &Vec)> = - e.sidecars.iter().map(|(ext, bytes)| (Path::new(&output).with_extension(ext).to_string_lossy().to_string(), bytes)).collect(); - let guard = s.original_guard(); - for p in std::iter::once(&output).chain(sidecars.iter().map(|(p, _)| p)) { - guard.check(Path::new(p)).map_err(|err| format!("render: {err}"))?; - } - e.save(&output)?; - for (sc, bytes) in &sidecars { - lcc_engine::export::write_file(sc, bytes)?; + // never over the input (or its sidecar), however it is spelled (`render IMG.jpg -o IMG.jpg`), and the sidecars named as + // every export names them: the engine's one writer of an export to a path + for sc in e.save(&output, &s.original_guard()).map_err(|err| format!("render: {err}"))? { eprintln!("{CLI}: wrote {sc}"); } let limit = diff --git a/apps/cli/tests/cli.rs b/apps/cli/tests/cli.rs index 3f4a3051cb..abe1d466f4 100644 --- a/apps/cli/tests/cli.rs +++ b/apps/cli/tests/cli.rs @@ -836,6 +836,35 @@ fn render_export_options() { assert!(!o.status.success() && String::from_utf8_lossy(&o.stderr).contains("unknown extension")); } +/// FX-216: `render` names an Original's sidecar as every export does (everything before the last dot is the stem), and +/// writes a file and its sidecar or neither: a sidecar that can't be written (its name is a folder) leaves no copy of the +/// file, and the error names it (FX-214). +#[test] +fn render_names_its_sidecar_like_every_export_and_writes_both_or_neither() { + let input = tmp("sc-in.png"); + gradient_png(&input); + let dir = input.parent().unwrap().to_path_buf(); + let render = |out: &std::path::Path| { + Command::new(BIN) + .args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", "light.exposure=1", "--opt", "format=original"]) + .output() + .unwrap() + }; + // several dots: the stem is everything before the last one + let out = dir.join("album.v1.final.png"); + let o = render(&out); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + assert!(dir.join("album.v1.final.xmp").is_file(), "the sidecar takes the stem"); + assert!(!dir.join("album.xmp").exists() && !dir.join("album.v1.xmp").exists()); + // a sidecar that can't be written: no copy without it + let out = dir.join("copy.png"); + std::fs::create_dir(dir.join("copy.xmp")).unwrap(); + let o = render(&out); + let err = String::from_utf8_lossy(&o.stderr); + assert!(!o.status.success() && err.contains("copy.xmp"), "{err}"); + assert!(!out.exists(), "a copy without its edits was left behind"); +} + #[test] fn commands_subcommand_lists_registry() { let o = Command::new(BIN).args(["commands", "--json"]).output().unwrap(); diff --git a/crates/camprof/src/jpeg_look.rs b/crates/camprof/src/jpeg_look.rs index cfac684404..923c5581c9 100644 --- a/crates/camprof/src/jpeg_look.rs +++ b/crates/camprof/src/jpeg_look.rs @@ -44,8 +44,11 @@ pub struct CameraLook { impl CameraLook { /// The look as `.cube` text titled `title`. pub fn to_cube(&self, title: &str) -> String { - let clean: String = title.chars().filter(|c| *c != '"' && !c.is_control()).collect(); - let mut s = format!("TITLE \"{clean}\"\nLUT_3D_SIZE {GRID}\n"); + let mut s = String::new(); + if let Some(t) = lcc_color::cube::title_text(title) { + s.push_str(&format!("TITLE \"{t}\"\n")); + } + s.push_str(&format!("LUT_3D_SIZE {GRID}\n")); for c in &self.table { s.push_str(&format!("{:.6} {:.6} {:.6}\n", c[0], c[1], c[2])); } @@ -374,4 +377,17 @@ mod tests { assert!(t.starts_with("TITLE \"My Cam\"\n")); assert_eq!(t.lines().filter(|l| l.starts_with(|c: char| c.is_ascii_digit())).count(), GRID * GRID * GRID); } + + /// FX-196: a title with line breaks can't write lines of its own, and a title with nothing left writes no line. + #[test] + fn a_title_cannot_inject_lines_into_the_cube_text() { + let look = fit(&synthetic(5000)).unwrap(); + let t = look.to_cube("a\r\nDOMAIN_MAX 8 8 8\nLUT_3D_SIZE 3"); + assert!(t.starts_with("TITLE \"a DOMAIN_MAX 8 8 8 LUT_3D_SIZE 3\"\nLUT_3D_SIZE "), "{}", t.lines().take(3).collect::>().join("|")); + assert_eq!(t.lines().filter(|l| l.starts_with("LUT_3D_SIZE")).count(), 1); + assert_eq!(t.lines().filter(|l| l.starts_with("DOMAIN")).count(), 0); + for empty in ["", "\n", "\r\n", "\"", " \t "] { + assert!(look.to_cube(empty).starts_with("LUT_3D_SIZE "), "{empty:?}"); + } + } } diff --git a/crates/catalog/src/facets.rs b/crates/catalog/src/facets.rs index cffccc9c0c..afd3752960 100644 --- a/crates/catalog/src/facets.rs +++ b/crates/catalog/src/facets.rs @@ -217,7 +217,7 @@ pub fn aspect(p: &Photo) -> Option { fn presets(p: &Photo) -> Vec { let mut out: Vec = Vec::new(); for step in &p.history { - if let Some(name) = step.label.strip_prefix("Preset: ").map(str::trim).filter(|n| !n.is_empty()) + if let Some(name) = step.label.strip_prefix(crate::model::PRESET_STEP_PREFIX).map(str::trim).filter(|n| !n.is_empty()) && !out.iter().any(|o| o.eq_ignore_ascii_case(name)) { out.push(name.to_string()); diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index ce072c7090..b770267fc9 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -24,6 +24,9 @@ pub(crate) struct Indexes { stacks: OnceLock>>, /// Album → its photos (regular albums; a smart album's list is empty). albums: OnceLock>>, + /// Collection set → the collections inside it, at any depth ([`Catalog::folder_collections`]); + /// dropped by any op that adds, removes or moves an album, or changes rules. + pub(crate) folder_collections: OnceLock>>, /// Folder ([`photo_folder_index_key`], lower-cased) → the photos whose file is directly in it, /// whatever their state (library, Recently Deleted, browsed in Local). Demo photos have none. folders: OnceLock>>, @@ -213,6 +216,7 @@ impl Indexes { /// An album came, went or got other rules: whether a smart album asks about contents is asked again. pub(crate) fn albums_changed(&mut self) { self.contents_asked = OnceLock::new(); + self.folder_collections = OnceLock::new(); } } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 59c07b2315..8d5f1c1800 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -450,6 +450,35 @@ pub struct Catalog { /// Lookups derived from the above (never saved), see [`index`]. #[serde(skip)] index: index::Indexes, + /// The photos that have a smart preview on disk, as the engine last listed them (never saved; empty until it + /// does), for the Has Smart Preview rule. + #[serde(skip)] + smart_previews: SmartPreviewSet, + /// The names of the publish services, by service id, as the engine last listed them (never saved; empty until it + /// does), for the Published Via rule: the names live in `publish.json`, which the catalog never reads. + #[serde(skip)] + publish_services: PublishServiceNames, +} + +/// [`Catalog::set_publish_services`]'s names. Compares equal whatever it holds, like [`SmartPreviewSet`]. +#[derive(Clone, Debug, Default)] +struct PublishServiceNames(Arc>); + +impl PartialEq for PublishServiceNames { + fn eq(&self, _: &Self) -> bool { + true + } +} + +/// [`Catalog::set_smart_previews`]'s photos. Compares equal whatever it holds, like [`index::Indexes`]: it is +/// what the disk holds, not part of the library. +#[derive(Clone, Debug, Default)] +struct SmartPreviewSet(Arc>); + +impl PartialEq for SmartPreviewSet { + fn eq(&self, _: &Self) -> bool { + true + } } /// What of a photo an op changed: enough to tell which tallies of the library an edit leaves as they were (a @@ -647,14 +676,58 @@ impl Catalog { /// Albums (regular and smart) that contain the photo. pub fn albums_of(&self, id: PhotoId) -> Vec { let Some(p) = self.photos.get(&id) else { return Vec::new() }; - self.albums.values().filter(|a| self.album_contains(a.id, p)).map(|a| a.id).collect() + self.albums.values().filter(|a| !a.folder && self.album_contains(a.id, p)).map(|a| a.id).collect() + } + + /// The collections inside folder `id`, at any depth (not the folders themselves), worked out + /// for every folder on first use and kept until an album comes, goes, moves or gets other rules. A saved loop of + /// parents ends the walk: each folder is visited once, and the depth is bounded. + fn folder_collections(&self, id: AlbumId) -> &[AlbumId] { + const MAX_DEPTH: usize = 64; + let all = self.index.folder_collections.get_or_init(|| { + let mut kids: std::collections::HashMap> = std::collections::HashMap::new(); + for a in self.albums.values() { + if let Some(p) = a.parent { + kids.entry(p).or_default().push(a); + } + } + let mut all = std::collections::HashMap::new(); + for f in self.albums.values().filter(|a| a.folder) { + let mut seen: std::collections::HashSet = std::collections::HashSet::from([f.id]); + let mut out = Vec::new(); + let mut level = vec![f.id]; + for _ in 0..MAX_DEPTH { + let mut next = Vec::new(); + for a in level.iter().filter_map(|l| kids.get(l)).flatten() { + if !seen.insert(a.id) { + continue; + } + if a.folder { + next.push(a.id); + } else { + out.push(a.id); + } + } + if next.is_empty() { + break; + } + level = next; + } + out.sort_unstable(); + all.insert(f.id, out); + } + all + }); + all.get(&id).map_or(&[], Vec::as_slice) } /// Whether album `id` contains `p` (a smart album evaluates its rules; deleted photos are in - /// no smart album). + /// no smart album; a collection set holds what the collections inside it hold, at any depth). pub fn album_contains(&self, id: AlbumId, p: &Photo) -> bool { match self.albums.get(&id) { Some(Album { smart: Some(rules), .. }) => self.smart_album_has(id, rules, &rules.prepare_one(), p), + // a folder (a collection set) holds what its collections hold, at any depth + Some(a) if a.folder => self.folder_collections(a.id).iter().any(|c| self.album_contains(*c, p)), Some(a) => self.album_lists(a.id, p.id), None => false, } @@ -720,6 +793,11 @@ impl Catalog { let prepared = rules.prepare(); self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).map(|p| p.id).collect() } + Some(a) if a.folder => { + // each photo once, in id order + let held: std::collections::BTreeSet = self.folder_collections(a.id).iter().flat_map(|c| self.album_photos(*c)).collect(); + held.into_iter().collect() + } Some(a) => a.photos.clone(), None => Vec::new(), } @@ -751,6 +829,36 @@ impl Catalog { Ok(()) } + /// Tell the catalog which photos have a smart preview on disk (the engine lists them: the catalog never + /// reads files). Changes what the Has Smart Preview rule matches, so it counts as a change for what is + /// keyed by [`Catalog::revision`]. + pub fn set_smart_previews(&mut self, ids: std::collections::HashSet) { + if *self.smart_previews.0 != ids { + self.smart_previews = SmartPreviewSet(Arc::new(ids)); + self.revision = self.revision.wrapping_add(1); + } + } + + /// Whether `id` is among the photos last given to [`Catalog::set_smart_previews`]. + pub fn has_smart_preview(&self, id: PhotoId) -> bool { + self.smart_previews.0.contains(&id) + } + + /// Tell the catalog the name of each publish service, by service id (the engine reads them from `publish.json`: + /// the catalog never reads files). Changes what the Published Via rule matches, so it counts as a change for what + /// is keyed by [`Catalog::revision`]. + pub fn set_publish_services(&mut self, names: BTreeMap) { + if *self.publish_services.0 != names { + self.publish_services = PublishServiceNames(Arc::new(names)); + self.revision = self.revision.wrapping_add(1); + } + } + + /// The name of publish service `id`, as last given to [`Catalog::set_publish_services`]. + pub fn publish_service_name(&self, id: &str) -> Option<&str> { + self.publish_services.0.get(id).map(String::as_str) + } + /// The name of a colour label: its custom name, else the colour (`Red`). pub fn label_name(&self, l: ColorLabel) -> String { self.label_names.get(&l).cloned().unwrap_or_else(|| format!("{l:?}")) @@ -944,7 +1052,7 @@ impl Catalog { _ => None, } .filter(|_| self.follows_contents()); - let albums = matches!(op, Op::AddAlbum { .. } | Op::RemoveAlbum { .. } | Op::SetAlbumRules { .. }); + let albums = matches!(op, Op::AddAlbum { .. } | Op::RemoveAlbum { .. } | Op::MoveAlbum { .. } | Op::SetAlbumRules { .. }); let before = photo.and_then(|id| self.content_of(id)); let inv = self.apply_op(op)?; if let Some(id) = photo { @@ -1950,6 +2058,8 @@ mod tests_folder_index; #[cfg(test)] mod tests_folder_records; #[cfg(test)] +mod tests_folder_union; +#[cfg(test)] mod tests_folders; #[cfg(test)] mod tests_follow; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 8853c90ca6..9a37d6d418 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -305,6 +305,25 @@ pub struct Version { pub auto: bool, } +/// The History label prefix of a step that applied a preset. +pub const PRESET_STEP_PREFIX: &str = "Preset: "; + +/// Whether a history step labelled `label` applied a named preset. +pub fn is_preset_step(label: &str) -> bool { + label.strip_prefix(PRESET_STEP_PREFIX).is_some_and(|n| !n.trim().is_empty()) +} + +/// Where a photo's settings stand against the presets applied to it ([`Photo::develop_preset`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DevelopPreset { + /// No preset applied. + Default, + /// A named preset is the latest change. + Specified, + /// Adjusted after a preset. + Custom, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HistoryStep { pub label: String, @@ -941,7 +960,14 @@ impl Photo { /// Edited by the user: settings differ from what import gave the photo, As Shot's stored numbers and Remove Hot /// Pixels aside. pub fn is_edited(&self) -> bool { - let mut defaults = self.import_defaults(); + self.differs_from(self.import_defaults()) + } + /// Has adjustments: settings differ from the camera defaults, so a default preset import applied counts, which + /// [`Photo::is_edited`] does not. + pub fn has_adjustments(&self) -> bool { + self.differs_from(self.camera_defaults()) + } + fn differs_from(&self, mut defaults: DevelopSettings) -> bool { self.as_shot_normalised(&mut defaults); // Remove Hot Pixels is on for raws imported since the box exists and off for older ones // (upstream #4390); a photo doesn't record which it had, so neither is an edit. @@ -954,6 +980,15 @@ impl Photo { } *self.develop != defaults && !self.develop.is_unedited() } + /// Which preset the photo's develop settings come from, read from its history (`Preset: ` steps, as the + /// preset commands and import write them). + pub fn develop_preset(&self) -> DevelopPreset { + match self.history.iter().rposition(|s| is_preset_step(&s.label)) { + None => DevelopPreset::Default, + Some(i) if i + 1 == self.history.len() => DevelopPreset::Specified, + Some(_) => DevelopPreset::Custom, + } + } /// The name a virtual copy is shown with (its Copy Name), and `None` for a photo that isn't one, whatever Copy /// Name it carries. pub fn virtual_copy_name(&self) -> Option<&str> { diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index a1fe63a60a..f845157360 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -1,6 +1,5 @@ //! Filtering, search and sorting. -use chrono::Datelike; use serde::{Deserialize, Serialize}; use crate::{AlbumId, Catalog, ColorLabel, Flag, MediaKind, Photo, PhotoId}; @@ -651,6 +650,21 @@ pub(crate) struct Prepared { only: Option>, /// A pass over many photos: the catalog's kept search text is made when missing. whole: bool, + /// [`Filter::capture_month_day`] as numbers (month, day); `None` without it. + month_day: Option<(u32, u32)>, +} + +impl Prepared { + /// What every filter has, whatever the pass: the library folder and the calendar day asked for. + fn base(filter: &Filter) -> Self { + Prepared { root: filter.library_root(), only: None, whole: false, month_day: filter.capture_month_day.as_deref().and_then(month_day_of) } + } +} + +/// `MM-DD` as (month, day) when it is well-formed (the callers that take it from a command check it first). +fn month_day_of(day: &str) -> Option<(u32, u32)> { + let (m, d) = day.split_once('-')?; + Some((m.parse().ok()?, d.parse().ok()?)) } /// A photo's place in the shuffle for `seed`. @@ -1042,6 +1056,12 @@ impl Filter { (None, Some(b)) => v.push(format!("captured until {b}")), _ => {} } + if let Some(day) = &self.capture_month_day { + v.push(match self.capture_before_year { + Some(year) => format!("captured on {day} before {year}"), + None => format!("captured on {day}"), + }); + } for f in self.facets.iter().filter(|f| !f.is_empty()) { let mut any: Vec<&str> = f.values.iter().map(String::as_str).collect(); if f.none { @@ -1101,13 +1121,13 @@ impl Filter { /// [`Filter::prepare`] for testing one photo (the `only` ids are looked through, not hashed). pub(crate) fn prepare_one(&self) -> Prepared { - Prepared { root: self.library_root(), only: None, whole: false } + Prepared::base(self) } /// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than /// once per photo: the library folder's identity and the `only` ids as a set. pub(crate) fn prepare(&self) -> Prepared { - Prepared { root: self.library_root(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()), whole: true } + Prepared { only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()), whole: true, ..Prepared::base(self) } } /// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice. @@ -1233,15 +1253,26 @@ impl Filter { { return false; } - if let Some(day) = self.capture_month_day.as_deref() { - let Some(captured) = p.captured.as_deref().filter(|c| c.get(..10).is_some()) else { return false }; - // Parse the stored prefix directly: capture_start deliberately turns a year/month-only - // timestamp into the first day of its period, but that is not a known capture day. - // Malformed and non-ASCII metadata simply won't match. - let Some(date) = captured.get(..10).and_then(|s| chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").ok()) else { + // Read from the stored prefix directly: capture_start deliberately turns a year/month-only + // timestamp into the first day of its period, but that is not a known capture day. A + // strict `YYYY-MM-DD` of ASCII digits (so nothing is allocated per photo, and chrono's + // lenient `%Y-%m-%d`, which also reads `+2025-1-3`, lets no oddity through); malformed and + // non-ASCII metadata simply won't match. + if let Some((want_month, want_day)) = prepared.month_day { + let Some(c) = p.captured.as_deref().and_then(|c| c.get(..10)) else { return false }; + let b = c.as_bytes(); + let digits = |r: std::ops::Range| b.get(r).is_some_and(|d| d.iter().all(u8::is_ascii_digit)); + if b.get(4) != Some(&b'-') || b.get(7) != Some(&b'-') || !(digits(0..4) && digits(5..7) && digits(8..10)) { return false; - }; - if date.format("%m-%d").to_string() != day || self.capture_before_year.is_some_and(|year| date.year() >= year) { + } + let num = |r: std::ops::Range| c.get(r).and_then(|d| d.parse::().ok()).unwrap_or(i32::MAX); + let (year, month, day) = (num(0..4), num(5..7), num(8..10)); + let Ok(month) = u32::try_from(month) else { return false }; + let Ok(day) = u32::try_from(day) else { return false }; + if (month, day) != (want_month, want_day) + || chrono::NaiveDate::from_ymd_opt(year, month, day).is_none() + || self.capture_before_year.is_some_and(|before| year >= before) + { return false; } } diff --git a/crates/catalog/src/remote.rs b/crates/catalog/src/remote.rs index b7d606c004..b4781fe864 100644 --- a/crates/catalog/src/remote.rs +++ b/crates/catalog/src/remote.rs @@ -54,6 +54,10 @@ pub struct RemoteIdentity { pub sync_state: SyncState, } +/// The `service` of a publish link (`lcc_publish::SERVICE`, which a test there keeps equal): its `account_id` is +/// `/`. +pub const PUBLISH_SERVICE: &str = "publish"; + /// The forward key: a photo's link on one account. pub type RemoteKey = (PhotoId, String, String); diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index bbb181abf3..8e19b1218e 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -55,6 +55,100 @@ pub enum Kind { Bool, } +/// The AI edits a photo's own settings can carry ([`ai_edits`]). +pub const AI_EDITS: &[(&str, &str)] = &[("denoise", "Denoise"), ("generativeFill", "Generative Fill"), ("none", "None")]; + +/// The mask types a photo can have ([`mask_types`]). +pub const MASK_TYPES: &[(&str, &str)] = &[ + ("subject", "Subject"), + ("sky", "Sky"), + ("background", "Background"), + ("people", "People"), + ("landscape", "Landscape"), + ("object", "Object"), + ("prompt", "Prompt"), + ("concept", "Remembered Object"), + ("brush", "Brush"), + ("linear", "Linear Gradient"), + ("radial", "Radial Gradient"), + ("colorRange", "Color Range"), + ("luminanceRange", "Luminance Range"), + ("depthRange", "Depth Range"), + ("none", "None"), +]; + +/// The modes of a photo's retouch spots ([`remove_modes`]). +pub const REMOVE_MODES: &[(&str, &str)] = &[ + ("remove", "Remove"), + ("heal", "Heal"), + ("clone", "Clone"), + ("fill", "Content-Aware Fill"), + ("flat", "Even Out"), + ("generate", "Generative"), + ("none", "None"), +]; + +/// The AI edits in a photo's settings: a denoise that is on, and a generative fill whose patches were made. Raw Details +/// and Super Resolution make a separate file and mark nothing here. +pub fn ai_edits(p: &Photo) -> Vec<&'static str> { + let mut out = Vec::new(); + if p.develop.enhance.denoise_enabled() { + out.push("denoise"); + } + if p.develop.spots.iter().any(|s| s.mode == lcc_develop::SpotMode::Generate && s.generated.is_some()) { + out.push("generativeFill"); + } + out +} + +/// The kinds of mask a photo has, each once. +pub fn mask_types(p: &Photo) -> Vec<&'static str> { + use lcc_develop::MaskShape as S; + let mut out: Vec<&'static str> = Vec::new(); + for c in p.develop.masks.iter().flat_map(|m| m.components.iter()) { + let t = match c.shape { + S::Subject => "subject", + S::Sky => "sky", + S::Background => "background", + S::People { .. } => "people", + S::Landscape { .. } => "landscape", + S::Object { .. } => "object", + S::Prompt { .. } => "prompt", + S::Concept { .. } => "concept", + S::Brush { .. } => "brush", + S::Linear { .. } => "linear", + S::Radial { .. } => "radial", + S::ColorRange { .. } => "colorRange", + S::LuminanceRange { .. } => "luminanceRange", + S::DepthRange { .. } => "depthRange", + }; + if !out.contains(&t) { + out.push(t); + } + } + out +} + +/// The modes of a photo's retouch spots, each once. +pub fn remove_modes(p: &Photo) -> Vec<&'static str> { + use lcc_develop::SpotMode as M; + let mut out: Vec<&'static str> = Vec::new(); + for s in &p.develop.spots { + let m = match s.mode { + M::Remove => "remove", + M::Heal => "heal", + M::Clone => "clone", + M::Fill => "fill", + M::Flat => "flat", + M::Generate => "generate", + }; + if !out.contains(&m) { + out.push(m); + } + } + out +} + /// The fields rules can test: (id, label, kind), in field-menu order ([`TOP_LEVEL_FIELDS`], then /// each of [`FIELD_GROUPS`]). pub const FIELDS: &[(&str, &str, Kind)] = &[ @@ -72,6 +166,8 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[ ("copyName", "Copy Name", Kind::Text), ("stacked", "In a Stack", Kind::Bool), ("immich", "Immich", Kind::Choice(&[("linked", "Linked"), ("probable", "Probably Linked"), ("notLinked", "Not Linked")])), + ("publishedVia", "Published Via", Kind::Text), + ("publishCollection", "Publish Collection", Kind::Text), // File ("fileName", "Filename", Kind::Text), ("extension", "File Extension", Kind::Text), @@ -86,6 +182,7 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[ ("captureDate", "Capture Date", Kind::Date), ("importDate", "Import Date", Kind::Date), ("editDate", "Edit Date", Kind::Date), + ("lastExported", "Last Exported", Kind::Date), ("captureMonth", "Capture Month", Kind::Number), ("captureDay", "Capture Day", Kind::Number), // Keywords & People @@ -98,6 +195,10 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[ ("title", "Title", Kind::Text), ("caption", "Caption", Kind::Text), ("altText", "Alt Text", Kind::Text), + ("extendedDescription", "Extended Description", Kind::Text), + ("labelText", "Label Text", Kind::Text), + ("iptcText", "Any Searchable IPTC", Kind::Text), + ("exifText", "Any Searchable EXIF", Kind::Text), ("creator", "Creator", Kind::Text), ("copyright", "Copyright", Kind::Text), ("usageTerms", "Rights Usage Terms", Kind::Text), @@ -133,7 +234,20 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[ ("megapixels", "Megapixels", Kind::Number), // Develop ("edited", "Has Edits", Kind::Bool), + ("hasAdjustments", "Has Adjustments", Kind::Bool), + ("developPreset", "Develop Preset", Kind::Choice(&[("default", "Default"), ("specified", "Specified"), ("custom", "Custom")])), + ("lensCorrections", "Lens Profile Corrections", Kind::Bool), + ("removeCa", "Remove Chromatic Aberration", Kind::Bool), + ("hasPointColor", "Has Point Color", Kind::Bool), + ("hdrEdit", "HDR Edit Mode", Kind::Bool), + ("hasAi", "Has AI", Kind::Bool), + ("hasGenAi", "Has Generative AI", Kind::Bool), + ("aiEdit", "AI Edit", Kind::Choice(AI_EDITS)), + ("maskType", "Masking", Kind::Choice(MASK_TYPES)), + ("manualRemove", "Manual Remove", Kind::Choice(REMOVE_MODES)), ("cropped", "Cropped", Kind::Bool), + ("hasSnapshots", "Has Snapshots", Kind::Bool), + ("smartPreview", "Has Smart Preview", Kind::Bool), ("treatment", "Treatment", Kind::Choice(&[("color", "In Color"), ("monochrome", "Black & White")])), ("processVersion", "Process Version", Kind::Number), ("vignettingReference", "Vignetting Reference", Kind::Choice(&[("reference", "Reference"), ("none", "Not a Reference")])), @@ -160,15 +274,52 @@ pub const TOP_LEVEL_FIELDS: &[&str] = &["rating", "flag", "label", "text"]; /// The field menu's submenus: (label, fields), in order. Every field of [`FIELDS`] is either here /// once or in [`TOP_LEVEL_FIELDS`]. pub const FIELD_GROUPS: &[(&str, &[&str])] = &[ - ("Source", &["album", "virtualCopy", "copyName", "stacked", "immich"]), + ("Source", &["album", "virtualCopy", "copyName", "stacked", "immich", "publishedVia", "publishCollection"]), ("File", &["fileName", "extension", "filePath", "folder", "kind", "format", "duration", "fileSize", "sameContent"]), - ("Date", &["captureDate", "importDate", "editDate", "captureMonth", "captureDay"]), + ("Date", &["captureDate", "importDate", "editDate", "lastExported", "captureMonth", "captureDay"]), ("Keywords & People", &["keywords", "keywordCount", "person", "personCount", "faceCount"]), - ("Description", &["title", "caption", "altText", "creator", "copyright", "usageTerms", "copyrightStatus"]), + ( + "Description", + &[ + "title", + "caption", + "altText", + "extendedDescription", + "labelText", + "iptcText", + "exifText", + "creator", + "copyright", + "usageTerms", + "copyrightStatus", + ], + ), ("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso", "flash", "exposureBias", "cameraSerial"]), ("Location", &["location", "sublocation", "city", "state", "country", "countryCode", "hasGps"]), ("Size", &["longEdge", "shortEdge", "width", "height", "aspect", "megapixels"]), - ("Develop", &["edited", "cropped", "treatment", "processVersion", "vignettingReference"]), + ( + "Develop", + &[ + "edited", + "hasAdjustments", + "developPreset", + "lensCorrections", + "removeCa", + "hasPointColor", + "hdrEdit", + "hasAi", + "hasGenAi", + "aiEdit", + "maskType", + "manualRemove", + "cropped", + "hasSnapshots", + "smartPreview", + "treatment", + "processVersion", + "vignettingReference", + ], + ), ("Assisted Culling", &["sharpness", "bestOfGroup", "clipped", "eyesOpen", "aesthetic", "cullScore", "suggestedStars"]), ("Image Quality", &["qualityScore", "qualitySharpness", "qualityNoise", "qualityExposure", "qualityCompression", "qualityVerdict"]), ]; @@ -839,6 +990,37 @@ pub(crate) fn rule_text_of(p: &Photo) -> String { .to_lowercase() } +/// The IPTC fields of `p` joined, for Any Searchable IPTC. +fn iptc_text_of(p: &Photo) -> String { + let m = &p.meta; + [ + m.title.as_str(), + &m.caption, + &m.headline, + &m.extended_description, + &m.alt_text, + &m.creator, + &m.copyright, + &m.usage_terms, + &m.location, + &m.city, + &m.state, + &m.country, + &m.country_code, + &m.category, + &m.supplemental_categories.join(" "), + &m.subject_code.join(" "), + &m.keywords.join(" "), + ] + .join(" ") +} + +/// The EXIF fields of `p` joined, for Any Searchable EXIF. +fn exif_text_of(p: &Photo) -> String { + let m = &p.meta; + [m.camera.as_str(), &m.lens, &m.camera_serial].join(" ") +} + fn text_op(op: &str, have: &str, want: &str) -> bool { text_op_lowered(op, &have.trim().to_lowercase(), want) } @@ -870,6 +1052,31 @@ fn names_op>(op: &str, names: &[S], want: &str) -> bool { } } +/// The names of the publish services and of the published collections `id` has a publish link in (the link, not +/// the collection's membership now, decides). A service the engine never named, or a collection that is gone, +/// has no name to match. +fn publish_link_names(cat: &Catalog, id: crate::PhotoId) -> (Vec, Vec) { + let (mut services, mut collections) = (Vec::new(), Vec::new()); + for l in cat.remote_of(id).filter(|l| l.service == crate::remote::PUBLISH_SERVICE) { + let Some((service, album)) = l.account_id.split_once('/') else { continue }; + if let Some(n) = cat.publish_service_name(service) { + services.push(n.to_string()); + } + if let Some(a) = album.parse::().ok().and_then(|a| cat.album(crate::AlbumId(a))) { + collections.push(a.name.clone()); + } + } + (services, collections) +} + +/// A text operator over the names of all of a photo's links: `isNot` is the opposite of `is`, not "some link isn't". +fn text_of_links(op: &str, names: &[String], want: &str) -> bool { + match op { + "isNot" => !names_op("is", names, want), + _ => names_op(op, names, want), + } +} + fn number(v: &Value) -> Option { match v { Value::Number(n) => n.as_f64(), @@ -989,6 +1196,12 @@ fn capture_part(p: &Photo, at: std::ops::Range) -> Option { captured.get(at).and_then(|n| n.parse::().ok()).filter(|n| *n > 0).map(f64::from) } +/// Whether `have` holds the choice `want` (any case) for `is`, or lacks it for `isNot`; `none` is an empty list. +fn member(have: &[&str], want: &str, op: &str) -> bool { + let has = if want.eq_ignore_ascii_case("none") { have.is_empty() } else { have.iter().any(|h| h.eq_ignore_ascii_case(want)) }; + has == (op == "is") +} + fn date_op(op: &str, have: Option<&str>, value: &Value) -> bool { if op == "isEmpty" { return have.is_none_or(str::is_empty); @@ -1052,6 +1265,25 @@ impl Rule { } "kind" => (kind_name(p.kind) == want) == (op == "is"), "edited" => yes(p.is_edited()), + "hasAdjustments" => yes(p.has_adjustments()), + "lensCorrections" => yes(p.develop.optics.lens_profile), + "removeCa" => yes(p.develop.optics.remove_ca), + "hasPointColor" => yes(!p.develop.point_colors.is_empty()), + "hdrEdit" => yes(p.develop.hdr.enabled), + "developPreset" => { + use crate::model::DevelopPreset as D; + let state = match p.develop_preset() { + D::Default => "default", + D::Specified => "specified", + D::Custom => "custom", + }; + (state == want) == (op == "is") + } + "hasAi" => yes(!ai_edits(p).is_empty()), + "hasGenAi" => yes(ai_edits(p).contains(&"generativeFill")), + "aiEdit" => member(&ai_edits(p), &want, op), + "maskType" => member(&mask_types(p), &want, op), + "manualRemove" => member(&remove_modes(p), &want, op), "hasGps" => yes(m.gps.is_some()), "virtualCopy" => yes(p.copy_of.is_some()), "copyName" => text(p.copy_name.as_deref().unwrap_or("")), @@ -1061,6 +1293,8 @@ impl Rule { let want = if want == "notlinked" { "notLinked" } else { want.as_str() }; crate::query::immich_state_is(cat, p.id, want) == (op == "is") } + "publishedVia" => text_of_links(op, &publish_link_names(cat, p.id).0, &want), + "publishCollection" => text_of_links(op, &publish_link_names(cat, p.id).1, &want), "cropped" => yes(p.is_cropped()), "treatment" => { let t = if p.develop.treatment == lcc_develop::Treatment::Bw { "monochrome" } else { "color" }; @@ -1098,6 +1332,13 @@ impl Rule { "title" => text(&m.title), "caption" => text(&m.caption), "altText" => text(&m.alt_text), + "extendedDescription" => text(&m.extended_description), + // the standard name (`red`), not a name the person gave the label + "labelText" => text(p.label.map_or("", label_colour)), + "iptcText" => text(&iptc_text_of(p)), + "exifText" => text(&exif_text_of(p)), + "hasSnapshots" => yes(p.versions.iter().any(|v| !v.auto)), + "smartPreview" => yes(cat.has_smart_preview(p.id)), "city" => text(&m.city), "state" => text(&m.state), "country" => text(&m.country), @@ -1134,6 +1375,11 @@ impl Rule { "captureDate" => date_op(op, p.captured.as_deref().map(crate::dates::capture_start).as_deref(), value), "importDate" => date_op(op, Some(&p.imported), value), "editDate" => date_op(op, p.edited.as_deref(), value), + // a photo never exported (or reset) has no date, so no date rule matches it, "isn't in the last" included + "lastExported" => match p.exported.as_deref() { + Some(at) => date_op(op, Some(at), value), + None => op == "isEmpty", + }, // the month and the day of the month a photo was taken, whatever the year (issue #1135: "on this day") "captureMonth" => num_op(op, capture_part(p, 5..7), value), "captureDay" => num_op(op, capture_part(p, 8..10), value), @@ -1666,6 +1912,283 @@ mod tests { assert_eq!(field_group("shutterSpeed"), Some("Camera Info")); } + /// The Develop state fields: each matches a photo with the setting and not one without. + #[test] + fn develop_state_fields() { + use crate::HistoryStep; + use std::sync::Arc; + let cat = Catalog::new(); + let one = + |p: &Photo, field: &str, value: serde_json::Value| rs(json!({"rules": [{"field": field, "op": "is", "value": value}]})).matches(p, &cat); + let yes_no = |field: &str, set: &dyn Fn(&mut lcc_develop::DevelopSettings)| { + let plain = photo(1); + let mut with = photo(2); + set(Arc::make_mut(&mut with.develop)); + assert!(!one(&plain, field, json!(true)) && one(&plain, field, json!(false)), "{field}: a photo without the setting"); + assert!(one(&with, field, json!(true)) && !one(&with, field, json!(false)), "{field}: a photo with the setting"); + }; + yes_no("lensCorrections", &|d| d.optics.lens_profile = true); + yes_no("removeCa", &|d| d.optics.remove_ca = true); + yes_no("hasPointColor", &|d| d.point_colors.push(lcc_develop::PointColor::default())); + yes_no("hdrEdit", &|d| d.hdr.enabled = true); + + // Has Adjustments counts what a default preset gave the photo at import; Has Edits does not + let mut p = photo(3); + assert!(!one(&p, "hasAdjustments", json!(true)) && one(&p, "hasAdjustments", json!(false))); + let mut look = p.camera_defaults(); + look.light.exposure = 1.0; + p.import_look = Some(Arc::new(look.clone())); + p.develop = Arc::new(look); + assert!(one(&p, "hasAdjustments", json!(true)), "the import look differs from the camera defaults"); + assert!(one(&p, "edited", json!(false)), "but it is still as imported"); + Arc::make_mut(&mut p.develop).light.exposure = 2.0; + assert!(one(&p, "edited", json!(true)) && one(&p, "hasAdjustments", json!(true))); + + // Develop Preset reads the history's `Preset: ` steps + let step = |label: &str| HistoryStep { label: label.into(), settings: Arc::new(Default::default()), batch: None }; + let mut p = photo(4); + let state = |p: &Photo, want: &str| one(p, "developPreset", json!(want)); + assert!(state(&p, "default") && !state(&p, "specified") && !state(&p, "custom")); + p.history.push(step("Exposure")); + assert!(state(&p, "default"), "an edit is not a preset"); + p.history.push(step("Preset: Warm Glow")); + assert!(state(&p, "specified") && !state(&p, "default") && !state(&p, "custom")); + p.history.push(step("Exposure")); + assert!(state(&p, "custom") && !state(&p, "specified")); + p.history.push(step("Preset: Cool")); + assert!(state(&p, "specified"), "a later preset is the latest change"); + p.history.clear(); + p.history.push(step("Preset: ")); + assert!(state(&p, "default"), "an unnamed step is no preset"); + assert_eq!(field_group("developPreset"), Some("Develop")); + } + + /// Has AI, Has Generative AI, AI Edit, Masking and Manual Remove: each matches a photo with the edit and not one + /// without, and AI Edit and the other choices match by membership. + #[test] + fn ai_edit_mask_and_retouch_fields() { + use lcc_develop::{GenFill, Mask, MaskComponent, MaskShape, Spot, SpotMode}; + use std::sync::Arc; + let cat = Catalog::new(); + let one = |p: &Photo, field: &str, op: &str, value: serde_json::Value| { + rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat) + }; + let with = |set: &dyn Fn(&mut lcc_develop::DevelopSettings)| { + let mut p = photo(1); + set(Arc::make_mut(&mut p.develop)); + p + }; + let denoised = with(&|d| d.enhance.denoise_on = Some(true)); + let generative = with(&|d| { + d.spots.push(Spot { mode: SpotMode::Generate, generated: Some(GenFill::default()), ..Spot::default() }); + }); + let marked_only = with(&|d| d.spots.push(Spot { mode: SpotMode::Generate, ..Spot::default() })); + let plain = photo(2); + + // Has AI: any edit Cf records on the photo + for (p, want) in [(&plain, false), (&denoised, true), (&generative, true), (&marked_only, false)] { + assert_eq!(one(p, "hasAi", "is", json!(true)), want); + assert_eq!(one(p, "hasAi", "is", json!(false)), !want); + } + // Has Generative AI: only the fill + assert!(one(&generative, "hasGenAi", "is", json!(true)) && !one(&denoised, "hasGenAi", "is", json!(true))); + assert!(one(&denoised, "hasGenAi", "is", json!(false)) && !one(&plain, "hasGenAi", "is", json!(true))); + + // AI Edit: the chosen edit among the applied ones; `none` is no edit + let both = with(&|d| { + d.enhance.denoise_on = Some(true); + d.spots.push(Spot { mode: SpotMode::Generate, generated: Some(GenFill::default()), ..Spot::default() }); + }); + assert!(one(&both, "aiEdit", "is", json!("denoise")) && one(&both, "aiEdit", "is", json!("generativeFill"))); + assert!(!one(&both, "aiEdit", "is", json!("none")) && one(&both, "aiEdit", "isNot", json!("none"))); + assert!(one(&denoised, "aiEdit", "is", json!("denoise")) && !one(&denoised, "aiEdit", "is", json!("generativeFill"))); + assert!(one(&plain, "aiEdit", "is", json!("none")) && !one(&plain, "aiEdit", "is", json!("denoise"))); + assert!(one(&plain, "aiEdit", "isNot", json!("denoise")) && !one(&denoised, "aiEdit", "isNot", json!("denoise"))); + + // Masking: the mask types it has + let mask = |shape: MaskShape| Mask { + components: vec![MaskComponent { name: None, anchor: None, op: Default::default(), invert: false, shape }], + ..Mask::default() + }; + let masked = with(&|d| { + d.masks.push(mask(MaskShape::Sky)); + d.masks.push(mask(MaskShape::Linear { start: Default::default(), end: Default::default() })); + }); + assert!(one(&masked, "maskType", "is", json!("sky")) && one(&masked, "maskType", "is", json!("linear"))); + assert!(!one(&masked, "maskType", "is", json!("subject")) && one(&masked, "maskType", "isNot", json!("subject"))); + assert!(!one(&masked, "maskType", "is", json!("none")) && one(&plain, "maskType", "is", json!("none"))); + + // Manual Remove: the modes of its spots + let healed = with(&|d| { + d.spots.push(Spot { mode: SpotMode::Heal, ..Spot::default() }); + d.spots.push(Spot { mode: SpotMode::Clone, ..Spot::default() }); + }); + assert!(one(&healed, "manualRemove", "is", json!("heal")) && one(&healed, "manualRemove", "is", json!("clone"))); + assert!(!one(&healed, "manualRemove", "is", json!("remove")) && one(&healed, "manualRemove", "isNot", json!("remove"))); + assert!(one(&plain, "manualRemove", "is", json!("none")) && !one(&healed, "manualRemove", "is", json!("none"))); + assert!(one(&marked_only, "manualRemove", "is", json!("generate"))); + + for f in ["hasAi", "hasGenAi", "aiEdit", "maskType", "manualRemove"] { + assert_eq!(field_group(f), Some("Develop"), "{f}"); + } + } + + /// Published Via and Publish Collection read the photo's publish links: the service's name as the engine last + /// gave it, the collection's own name. A photo with no link is empty, an unknown name matches nothing, and a + /// number or a date is a problem, not a panic. + #[test] + fn publish_fields_follow_the_links() { + use crate::remote::{PUBLISH_SERVICE, RemoteIdentity, SyncState}; + use crate::{Album, AlbumId, Op}; + let mut cat = Catalog::new(); + let (a, b) = (photo(1), photo(2)); + cat.apply(Op::AddPhoto { photo: Box::new(a.clone()) }).unwrap(); + cat.apply(Op::AddPhoto { photo: Box::new(b.clone()) }).unwrap(); + cat.apply(Op::AddAlbum { album: Album::new(AlbumId(7), "Web") }).unwrap(); + let link = RemoteIdentity { + photo_id: a.id, + service: PUBLISH_SERVICE.into(), + account_id: "svc-1/7".into(), + remote_id: "a.jpg".into(), + remote_checksum: None, + remote_updated_at: None, + last_synced_at: None, + sync_state: SyncState::Synced, + }; + cat.apply(Op::SetRemote { photo: a.id, service: link.service.clone(), account_id: link.account_id.clone(), record: Some(Box::new(link)) }) + .unwrap(); + let one = |cat: &Catalog, p: &Photo, field: &str, op: &str, value: serde_json::Value| { + rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, cat) + }; + // the service has no name until the engine gives one + assert!(!one(&cat, &a, "publishedVia", "contains", json!("disk"))); + cat.set_publish_services([("svc-1".to_string(), "Hard Disk".to_string())].into_iter().collect()); + assert!(one(&cat, &a, "publishedVia", "is", json!("hard disk")) && one(&cat, &a, "publishedVia", "contains", json!("disk"))); + assert!(!one(&cat, &b, "publishedVia", "contains", json!("disk")), "no link, no match"); + assert!(one(&cat, &b, "publishedVia", "isEmpty", json!(null)) && one(&cat, &a, "publishedVia", "isNotEmpty", json!(null))); + assert!(one(&cat, &b, "publishedVia", "isNot", json!("Hard Disk")) && !one(&cat, &a, "publishedVia", "isNot", json!("Hard Disk"))); + assert!(!one(&cat, &a, "publishedVia", "is", json!("Nowhere"))); + assert!(one(&cat, &a, "publishCollection", "is", json!("Web")) && !one(&cat, &b, "publishCollection", "is", json!("Web"))); + assert!(one(&cat, &a, "publishCollection", "notContains", json!("print"))); + // a collection that is gone, or a link whose account isn't ours to read, has no name + cat.apply(Op::RemoveAlbum { id: AlbumId(7) }).unwrap(); + assert!(!one(&cat, &a, "publishCollection", "is", json!("Web"))); + assert!(one(&cat, &a, "publishCollection", "isEmpty", json!(null))); + // bad rules are problems + for (field, op, value) in [("publishedVia", "gte", json!(3)), ("publishedVia", "contains", json!(""))] { + let r = rs(json!({"rules": [{"field": field, "op": op, "value": value}]})); + assert!(!r.check(&cat).is_empty(), "{field} {op} {value}"); + assert!(!r.matches(&a, &cat) || op == "contains", "{field} {op} {value}"); + } + } + + /// A smart album's cached count follows the publish rules: a link set or removed is followed from the photo, a + /// service named, renamed or dropped makes the counts be taken again, and an orphan link (its service gone from + /// publish.json) matches nothing. + #[test] + fn publish_rules_keep_the_counts_current() { + use crate::remote::{PUBLISH_SERVICE, RemoteIdentity, SyncState}; + use crate::tally::AlbumTally; + use crate::{Album, AlbumId, Op}; + let mut cat = Catalog::new(); + let a = photo(1); + cat.apply(Op::AddPhoto { photo: Box::new(a.clone()) }).unwrap(); + cat.apply(Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(AlbumId(5), "Via disk") } }).unwrap(); + let rules = rs(json!({"rules": [{"field": "publishedVia", "op": "is", "value": "Disk"}]})); + let filter = crate::Filter { rule_set: Some(rules), ..Default::default() }; + cat.apply(Op::SetAlbumRules { id: AlbumId(5), rules: Box::new(filter) }).unwrap(); + let count = |t: &AlbumTally| t.counts().get(&AlbumId(5)).copied(); + let mut tally = AlbumTally::of(&cat); + assert_eq!(count(&tally), Some(0)); + let link = RemoteIdentity { + photo_id: a.id, + service: PUBLISH_SERVICE.into(), + account_id: "svc-1/9".into(), + remote_id: "a.jpg".into(), + remote_checksum: None, + remote_updated_at: None, + last_synced_at: None, + sync_state: SyncState::Synced, + }; + // a link alone, with no name for its service: nothing matches + cat.apply(Op::SetRemote { + photo: a.id, + service: link.service.clone(), + account_id: link.account_id.clone(), + record: Some(Box::new(link.clone())), + }) + .unwrap(); + if !tally.update(&cat) { + tally = AlbumTally::of(&cat); + } + assert_eq!(count(&tally), Some(0), "an orphan link matches nothing"); + // naming the service changes the counts without a photo being touched + cat.set_publish_services([("svc-1".to_string(), "Disk".to_string())].into_iter().collect()); + assert!(!tally.update(&cat), "the counts are taken again"); + tally = AlbumTally::of(&cat); + assert_eq!(count(&tally), Some(1)); + // the service goes: so does the match + cat.set_publish_services(Default::default()); + assert!(!tally.update(&cat)); + assert_eq!(count(&AlbumTally::of(&cat)), Some(0)); + // a link removed is followed from the photo + cat.set_publish_services([("svc-1".to_string(), "Disk".to_string())].into_iter().collect()); + tally = AlbumTally::of(&cat); + cat.apply(Op::SetRemote { photo: a.id, service: link.service, account_id: link.account_id, record: None }).unwrap(); + assert!(tally.update(&cat), "a link change is followed"); + assert_eq!(count(&tally), Some(0)); + } + + /// The status and metadata fields (Has Snapshots, Has Smart Preview, Label Text, Extended Description, Any + /// Searchable IPTC / EXIF, Last Exported). + #[test] + fn status_and_metadata_fields() { + let mut cat = Catalog::new(); + let mut p = photo(1); + p.label = None; + let one = |cat: &Catalog, p: &Photo, field: &str, op: &str, value: serde_json::Value| { + rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, cat) + }; + // Has Snapshots counts the versions a person saved, not the ones Cf made by itself + let version = |auto| crate::Version { name: "v".into(), created: "2026-11-01T10:00:00".into(), settings: Default::default(), auto }; + assert!(one(&cat, &p, "hasSnapshots", "is", json!(false)) && !one(&cat, &p, "hasSnapshots", "is", json!(true))); + p.versions.push(version(true)); + assert!(!one(&cat, &p, "hasSnapshots", "is", json!(true)), "an automatic version is no snapshot"); + p.versions.push(version(false)); + assert!(one(&cat, &p, "hasSnapshots", "is", json!(true)) && !one(&cat, &p, "hasSnapshots", "is", json!(false))); + // Has Smart Preview follows what the engine last listed + assert!(one(&cat, &p, "smartPreview", "is", json!(false)), "nothing listed yet"); + cat.set_smart_previews([p.id].into_iter().collect()); + assert!(one(&cat, &p, "smartPreview", "is", json!(true)) && !one(&cat, &p, "smartPreview", "is", json!(false))); + assert!(!one(&cat, &photo(2), "smartPreview", "is", json!(true)), "only the listed photos"); + // Label Text is the standard name, whatever the label was renamed to; empty with no label + assert!(one(&cat, &p, "labelText", "isEmpty", json!(null))); + p.label = Some(crate::ColorLabel::Red); + cat.apply(crate::Op::SetLabelName { label: crate::ColorLabel::Red, name: Some("Hero".into()) }).unwrap(); + assert!(one(&cat, &p, "labelText", "is", json!("Red")) && !one(&cat, &p, "labelText", "is", json!("Hero"))); + assert!(one(&cat, &p, "labelText", "isNotEmpty", json!(null)) && one(&cat, &p, "labelText", "isNot", json!("Blue"))); + // Extended Description, and the searches over the IPTC and the EXIF fields + p.meta.extended_description = "A long walk at dusk".into(); + p.meta.camera = "Canon EOS R8".into(); + p.meta.caption = "Sunset over the bay".into(); + assert!(one(&cat, &p, "extendedDescription", "contains", json!("dusk"))); + assert!(one(&cat, &p, "iptcText", "contains", json!("sunset")) && !one(&cat, &p, "iptcText", "contains", json!("canon"))); + assert!(one(&cat, &p, "exifText", "contains", json!("canon eos")) && !one(&cat, &p, "exifText", "contains", json!("sunset"))); + // Last Exported matches by date, and a photo never exported (or reset) matches no date rule + let at = |p: &Photo, op: &str, value: serde_json::Value| one(&cat, p, "lastExported", op, value); + for (op, value) in + [("is", json!("2026-11-10")), ("inLast", json!(1)), ("notInLast", json!(1)), ("before", json!("2030-01-01")), ("today", json!(null))] + { + assert!(!at(&p, op, value.clone()), "never exported: {op}"); + } + assert!(at(&p, "isEmpty", json!(null))); + p.exported = Some("2026-11-10T08:00:00".into()); + assert!(at(&p, "is", json!("2026-11-10")) && at(&p, "after", json!("2026-11-01")) && at(&p, "before", json!("2026-12-01"))); + assert!(at(&p, "between", json!(["2026-11-01", "2026-11-30"])) && !at(&p, "after", json!("2026-11-10")) && !at(&p, "isEmpty", json!(null))); + assert_eq!(field_group("lastExported"), Some("Date")); + assert_eq!(field_group("hasSnapshots"), Some("Develop")); + } + #[test] fn shutter_seconds_parses_camera_notation() { for (s, want) in [("1/250", Some(0.004)), (" 1/250 s", Some(0.004)), ("0.5", Some(0.5)), ("2\"", Some(2.0)), ("30s", Some(30.0))] { diff --git a/crates/catalog/src/safe_file.rs b/crates/catalog/src/safe_file.rs index 5967a35bff..65ea05b6e5 100644 --- a/crates/catalog/src/safe_file.rs +++ b/crates/catalog/src/safe_file.rs @@ -426,6 +426,40 @@ pub fn write_new_unique(candidates: &mut dyn Iterator, data: &[u write_new_unique_progress(candidates, data, &NoProgress) } +/// How many numbered names ([`first_free_numbered`]) a search tries before it gives up: `a-2` … `a-999999`. One +/// limit for every place that numbers a clashing file name (export, Edit In, publishing, a catalog's copied +/// originals), so none runs out sooner than the others (FX-235). +pub const NUMBERED_NAME_TRIES: u32 = 1_000_000; + +/// `name` as stem and extension, split at the last dot. A leading dot (a hidden file's) starts no extension: +/// `.hidden` has the stem `.hidden`. (The one rule of where a clash number goes.) +pub fn split_extension(name: &str) -> (&str, Option<&str>) { + match name.rfind('.').filter(|&i| i > 0) { + Some(i) => (name.get(..i).unwrap_or(name), name.get(i + 1..)), + None => (name, None), + } +} + +/// The name `stem-n.ext` (`stem-n` with no extension): `a`, `jpg`, 2 is `a-2.jpg`. `stem` may carry a folder in +/// front (`dir/a`): it is kept as given. +pub fn numbered_name(stem: &str, ext: Option<&str>, n: u32) -> String { + match ext { + Some(x) => format!("{stem}-{n}.{x}"), + None => format!("{stem}-{n}"), + } +} + +/// The first of `stem-from.ext`, `stem-{from+1}.ext`, … (below [`NUMBERED_NAME_TRIES`]) that `free` accepts, or +/// `None` when every one is taken: the caller reports that, it never reuses a taken name. +pub fn first_free_numbered(stem: &str, ext: Option<&str>, from: u32, free: impl FnMut(&str) -> bool) -> Option { + first_free_numbered_below(stem, ext, from, NUMBERED_NAME_TRIES, free) +} + +/// [`first_free_numbered`] with its own bound (the numbers `from..below`). +pub fn first_free_numbered_below(stem: &str, ext: Option<&str>, from: u32, below: u32, mut free: impl FnMut(&str) -> bool) -> Option { + (from..below).map(|n| numbered_name(stem, ext, n)).find(|name| free(name)) +} + /// Bytes per write (and at most per read back) of [`write_new_unique_progress`], so `progress` /// hears from a slow volume often. const PROGRESS_CHUNK: usize = 4 << 20; @@ -746,6 +780,35 @@ mod tests { let _ = fs::remove_dir_all(&d); } + /// One rule for where a clash number goes, and for which numbers are tried (FX-235). + #[test] + fn numbered_names_split_at_the_last_dot_and_start_where_asked() { + // a leading dot starts no extension; neither does a name with no dot + assert_eq!(split_extension("a.jpg"), ("a", Some("jpg"))); + assert_eq!(split_extension("a.b.jpg"), ("a.b", Some("jpg"))); + assert_eq!(split_extension(".hidden"), (".hidden", None)); + assert_eq!(split_extension("noext"), ("noext", None)); + assert_eq!(split_extension("a."), ("a", Some(""))); + assert_eq!(split_extension(""), ("", None)); + assert_eq!(numbered_name("a", Some("jpg"), 2), "a-2.jpg"); + assert_eq!(numbered_name("dir/a", None, 7), "dir/a-7"); + // the first free one from `from` on; a taken number is stepped over + let taken = ["a-2.jpg", "a-3.jpg"]; + assert_eq!(first_free_numbered("a", Some("jpg"), 2, |n| !taken.contains(&n)).as_deref(), Some("a-4.jpg")); + assert_eq!(first_free_numbered("a", Some("jpg"), 1, |_| true).as_deref(), Some("a-1.jpg"), "`from` itself is tried"); + // the bound: below / at / above the last number tried + let all_but = |last: u32| move |n: &str| n == numbered_name("a", None, last); + assert_eq!(first_free_numbered_below("a", None, 2, 6, all_but(5)).as_deref(), Some("a-5"), "the last number below the bound"); + assert_eq!(first_free_numbered_below("a", None, 2, 6, all_but(6)), None, "the bound itself is not tried"); + assert_eq!(first_free_numbered_below("a", None, 2, 6, all_but(7)), None); + assert_eq!(first_free_numbered_below("a", None, 6, 6, |_| true), None, "an empty range"); + assert_eq!(first_free_numbered_below("a", None, 2, 6, |_| false), None, "all taken"); + assert_eq!(NUMBERED_NAME_TRIES, 1_000_000); + let last = NUMBERED_NAME_TRIES - 1; + assert_eq!(first_free_numbered("a", None, 2, |n| n == numbered_name("a", None, last)).as_deref(), Some("a-999999")); + assert_eq!(first_free_numbered("a", None, 2, |n| n == numbered_name("a", None, last + 1)), None); + } + fn temp(tag: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("lc-safe-file-{tag}-{}", std::process::id())); let _ = fs::remove_dir_all(&d); diff --git a/crates/catalog/src/tests_folder_union.rs b/crates/catalog/src/tests_folder_union.rs new file mode 100644 index 0000000000..57fdcdcf45 --- /dev/null +++ b/crates/catalog/src/tests_folder_union.rs @@ -0,0 +1,112 @@ +//! A collection set (a folder album) holds the photos of its collections, at any depth. +//! +//! Scenarios: +//! - Given collections in nested sets, then the outer set lists their photos, each once, and +//! contains each of them. +//! - Given a set with no photos in it, then it lists nothing. +//! - A photo's own collections never name a set. + +use crate::*; + +fn photo(c: &mut Catalog, i: u64) -> PhotoId { + let id = c.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: format!("/p/{i}.jpg") }, &format!("{i}.jpg"), "JPEG", 4, 3, "2026-01-01"); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id +} + +fn add(c: &mut Catalog, name: &str, parent: Option, folder: bool, photos: Vec) -> AlbumId { + let id = c.alloc_album_id(); + c.apply(Op::AddAlbum { album: Album { parent, folder, photos, ..Album::new(id, name) } }).unwrap(); + id +} + +#[test] +fn a_set_holds_the_photos_of_its_collections_at_any_depth_once() { + let mut c = Catalog::new(); + let p: Vec = (0..4).map(|i| photo(&mut c, i)).collect(); + let outer = add(&mut c, "Trips", None, true, vec![]); + let inner = add(&mut c, "Europe", Some(outer), true, vec![]); + let paris = add(&mut c, "Paris", Some(inner), false, vec![p[0], p[1]]); + add(&mut c, "Best", Some(outer), false, vec![p[1], p[2]]); + assert_eq!(c.album_photos(outer), vec![p[0], p[1], p[2]], "each photo once"); + assert_eq!(c.album_photos(inner), vec![p[0], p[1]]); + let held = |c: &Catalog, set, i: usize| c.album_contains(set, c.photo(p[i]).unwrap()); + assert!(held(&c, outer, 0) && held(&c, outer, 2) && !held(&c, outer, 3)); + assert!(held(&c, inner, 1) && !held(&c, inner, 2)); + assert_eq!(c.albums_of(p[1]).len(), 2, "its two collections, not the sets"); + assert!(c.albums_of(p[1]).contains(&paris)); +} + +#[test] +fn a_set_with_no_photos_in_it_lists_nothing() { + let mut c = Catalog::new(); + let set = add(&mut c, "Empty", None, true, vec![]); + add(&mut c, "Nothing", Some(set), false, vec![]); + assert!(c.album_photos(set).is_empty()); +} + +/// Moving a collection into or out of a set changes what the set holds at once (the answer is kept +/// between edits, so an edit must drop it), and undo brings it back. +#[test] +fn moving_a_collection_changes_what_its_set_holds() { + let mut c = Catalog::new(); + let p = photo(&mut c, 0); + let set = add(&mut c, "Trips", None, true, vec![]); + let album = add(&mut c, "Paris", None, false, vec![p]); + assert!(c.album_photos(set).is_empty()); + let undo = c.apply(Op::MoveAlbum { id: album, parent: Some(set) }).unwrap(); + assert_eq!(c.album_photos(set), vec![p]); + c.apply(undo).unwrap(); + assert!(c.album_photos(set).is_empty(), "undone: the set is empty again"); + let inner = add(&mut c, "Inner", Some(set), true, vec![]); + add(&mut c, "Deep", Some(inner), false, vec![p]); + assert_eq!(c.album_photos(set), vec![p]); +} + +/// Given a set that holds a smart collection whose rules name that set (a loop the rules refuse +/// to be made, but saved data may hold), then the set's photos and membership end, with no panic. +#[test] +fn a_smart_collection_testing_its_own_set_ends() { + let mut c = Catalog::new(); + let p = photo(&mut c, 0); + let set = add(&mut c, "Trips", None, true, vec![]); + let smart = c.alloc_album_id(); + let rules = Filter { album: Some(set), ..Filter::default() }; + let made = c.apply(Op::AddAlbum { album: Album { parent: Some(set), smart: Some(Box::new(rules)), ..Album::new(smart, "Loop") } }); + assert!(made.is_ok(), "{made:?}"); + let _ = c.album_photos(set); + let _ = c.album_contains(set, c.photo(p).unwrap()); +} + +/// Removing a collection, or a batch that fails halfway and rolls back, leaves the set holding what +/// the catalog holds now. (A kept list that still named a removed collection would resolve to no +/// photos, so this checks the results, not the invalidation; the move test checks that.) +#[test] +fn removing_or_rolling_back_leaves_the_set_in_step() { + let mut c = Catalog::new(); + let p = photo(&mut c, 0); + let set = add(&mut c, "Trips", None, true, vec![]); + let kept = add(&mut c, "Kept", Some(set), false, vec![p]); + let spare = add(&mut c, "Spare", None, false, vec![]); + assert_eq!(c.album_photos(set), vec![p]); + // a batch that moves a collection in, then fails: rolled back, and the set as it was + let outcome = c.apply(Op::Batch { ops: vec![Op::MoveAlbum { id: spare, parent: Some(set) }, Op::RemoveAlbum { id: AlbumId(u64::MAX) }] }); + assert!(outcome.is_err()); + assert_eq!(c.album_photos(set), vec![p]); + assert_eq!(c.album_children(Some(set)).len(), 1, "the move was rolled back"); + c.apply(Op::RemoveAlbum { id: kept }).unwrap(); + assert!(c.album_photos(set).is_empty(), "the collection is gone, and so are its photos from the set"); +} + +/// The collections of a set are worked out once and kept between queries, not per photo. +#[test] +fn a_sets_collections_are_kept_between_calls() { + let mut c = Catalog::new(); + let set = add(&mut c, "Trips", None, true, vec![]); + add(&mut c, "Paris", Some(set), false, vec![]); + let first = c.folder_collections(set).as_ptr(); + assert_eq!(first, c.folder_collections(set).as_ptr(), "the same list, not a new one"); + add(&mut c, "Rome", Some(set), false, vec![]); + assert_eq!(c.folder_collections(set).len(), 2, "an added collection drops it"); +} diff --git a/crates/catalog/src/transfer.rs b/crates/catalog/src/transfer.rs index 0c480a07df..942e42e3c3 100644 --- a/crates/catalog/src/transfer.rs +++ b/crates/catalog/src/transfer.rs @@ -144,17 +144,20 @@ pub fn subset(cat: &Catalog, opts: &ExportOptions) -> Catalog { out } -/// A file name that is unique in `dir` (`a.jpg`, `a-2.jpg`, …). -fn unique_in(dir: &Path, name: &str) -> PathBuf { +/// A file name that is unique in `dir` (`a.jpg`, `a-2.jpg`, …). `None` when every numbered name is taken +/// ([`crate::safe_file::NUMBERED_NAME_TRIES`]): the caller reports it, never writing over a taken name (FX-235). +fn unique_in(dir: &Path, name: &str) -> Option { + unique_in_below(dir, name, crate::safe_file::NUMBERED_NAME_TRIES) +} + +/// [`unique_in`] trying the numbers below `below` only. +fn unique_in_below(dir: &Path, name: &str, below: u32) -> Option { let first = dir.join(name); if !first.exists() { - return first; + return Some(first); } - let (stem, ext) = match name.rsplit_once('.') { - Some((s, e)) => (s, format!(".{e}")), - None => (name, String::new()), - }; - (2..10_000).map(|n| dir.join(format!("{stem}-{n}{ext}"))).find(|p| !p.exists()).unwrap_or(first) + let (stem, ext) = crate::safe_file::split_extension(name); + crate::safe_file::first_free_numbered_below(stem, ext, 2, below, |n| !dir.join(n).exists()).map(|n| dir.join(n)) } /// Export `opts` of `cat` as a new catalog `parent/name`. @@ -177,7 +180,10 @@ pub fn export_catalog(cat: &Catalog, opts: &ExportOptions, parent: &Path, name: Some(n) => n.clone(), None => { let file = Path::new(&path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "original".into()); - let dest = unique_in(&originals, &file); + let Some(dest) = unique_in(&originals, &file) else { + report.originals_failed.push((path.clone(), format!("{file}: no free file name in the Originals folder"))); + continue; + }; match std::fs::copy(&path, &dest) { Ok(_) => { report.originals_copied += 1; @@ -476,3 +482,39 @@ impl ImportPlan { Op::Batch { ops } } } + +#[cfg(test)] +mod name_tests { + use super::*; + + fn dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lcc-transfer-names-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + /// A copied original takes the first free numbered name, and is never given a taken one: when every numbered name + /// is taken the copy fails (a line in the report) instead of replacing the file there (FX-235). + #[test] + fn a_copied_original_takes_a_free_name_and_never_a_taken_one() { + let d = dir("unique"); + assert_eq!(unique_in(&d, "a.jpg"), Some(d.join("a.jpg")), "free: its own name"); + std::fs::write(d.join("a.jpg"), b"1").unwrap(); + assert_eq!(unique_in(&d, "a.jpg"), Some(d.join("a-2.jpg"))); + std::fs::write(d.join("a-2.jpg"), b"2").unwrap(); + std::fs::write(d.join("a-4.jpg"), b"4").unwrap(); + assert_eq!(unique_in(&d, "a.jpg"), Some(d.join("a-3.jpg")), "the first free number"); + // a name with no extension, and a hidden file's (no extension: the number goes after the whole name) + std::fs::write(d.join("raw"), b"1").unwrap(); + assert_eq!(unique_in(&d, "raw"), Some(d.join("raw-2"))); + std::fs::write(d.join(".hid"), b"1").unwrap(); + assert_eq!(unique_in(&d, ".hid"), Some(d.join(".hid-2"))); + // every number below the bound taken (a-2 … a-4 here, with the bound at 5): none, not `a.jpg` again + std::fs::write(d.join("a-3.jpg"), b"3").unwrap(); + assert_eq!(unique_in_below(&d, "a.jpg", 6).as_deref(), Some(d.join("a-5.jpg").as_path()), "below the bound: a number is left"); + assert_eq!(unique_in_below(&d, "a.jpg", 5), None, "at the bound: every number tried is taken"); + assert_eq!(unique_in_below(&d, "a.jpg", 2), None, "no number to try"); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 46983098ef..05b9e00b6e 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -13,6 +13,8 @@ lcc-brand = { workspace = true } lcc-geom = { workspace = true } lcc-color = { workspace = true } lcc-raster = { workspace = true } +# the Exif block of a TIFF export is read back into the file's own IFDs (FX-188) +lcc-tiff = { workspace = true } lcc-heif = { workspace = true, optional = true } serde = { workspace = true } bytemuck = { workspace = true } @@ -22,7 +24,6 @@ image = { workspace = true, features = ["gif", "bmp"] } zune-jpeg = { workspace = true } zune-core = { workspace = true } jpeg-decoder = { workspace = true } -jpeg-encoder = { workspace = true } png = { workspace = true } tiff = { workspace = true } image-webp = { workspace = true } @@ -66,6 +67,8 @@ avif = ["dep:ravif", "dep:rav1e", "dep:avif-serialize"] lcc-fuzzkit = { workspace = true } # tests record why they skip (`cargo xtask ci` lists the skips) lcc-testkit = { workspace = true } +# tests and the benchmark example compare the parallel JPEG encoder with it, and make files it alone writes (CMYK) +jpeg-encoder = { workspace = true } # JPEG XL tests read encoded samples without our colour conversion jxl-oxide = { workspace = true } proptest = { workspace = true } diff --git a/crates/codecs/README.md b/crates/codecs/README.md index daa14b9b0e..5a4e6c160f 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -51,7 +51,7 @@ CRW, MRW, X3F) are detected so the engine can route them to `lcc-raw`; `decode` | Format | Decode | Encode | Notes | |---|---|---|---| -| JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (jpeg-encoder, baseline, 4:4:4/4:2:2/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2; only complete, consistently counted, uniquely numbered chunk sequences are assembled; malformed profiles use the existing unsupported-profile fallback), Adobe APP14, MPF previews | +| JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (our own parallel restart-interval encoder, baseline, 4:4:4/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2; only complete, consistently counted, uniquely numbered chunk sequences are assembled; malformed profiles use the existing unsupported-profile fallback), Adobe APP14, MPF previews | | PNG | yes, 1–16-bit, palette, tRNS, interlaced | 8/16-bit, gray/GA/RGB/RGBA | iCCP, eXIf, iTXt XMP; sRGB/cICP/cHRM/gAMA honoured when no ICC | | TIFF | 8/16-bit int (32/64-bit int kept to 16 bits), 16/32/64-bit float, gray/RGB/CMYK/palette, alpha (assoc./unassoc.), planar, LZW/Deflate/PackBits/JPEG | 8/16-bit, 32-bit float; none/LZW/Deflate/PackBits | ICC (34675), XMP (700), Orientation; first IFD only; EXIF not written (use `lcc-tiff`) | | WebP | lossy + lossless, alpha, first frame of animations | lossless only | ICCP/EXIF/XMP chunks | diff --git a/crates/codecs/src/encode.rs b/crates/codecs/src/encode.rs index 8adc1b58c1..d7b0eb2c34 100644 --- a/crates/codecs/src/encode.rs +++ b/crates/codecs/src/encode.rs @@ -71,17 +71,32 @@ pub struct EncodeMeta<'a> { pub ppi: Option, } -/// JPEG chroma subsampling. +/// JPEG chroma subsampling: the two the parallel encoder writes ([`crate::jpeg_par`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum ChromaSubsampling { /// No subsampling (best quality). #[default] S444, - S422, S420, } const XMP_NS: &[u8] = b"http://ns.adobe.com/xap/1.0/\0"; +const EXIF_HEADER: &[u8] = b"Exif\0\0"; + +/// The most EXIF a JPEG holds: one APP1 segment ([`crate::jpeg_par::MAX_SEGMENT_PAYLOAD`], after `Exif\0\0`). +pub const JPEG_MAX_EXIF: usize = crate::jpeg_par::MAX_SEGMENT_PAYLOAD - EXIF_HEADER.len(); +/// The most XMP a JPEG holds: one APP1 segment, after the XMP namespace. A longer packet would need Extended XMP, +/// which is not written. +pub const JPEG_MAX_XMP: usize = crate::jpeg_par::MAX_SEGMENT_PAYLOAD - XMP_NS.len(); + +/// Refuse `len` bytes of `what` past the `max` one JPEG APP1 segment holds, saying by how much: the one message for +/// both the EXIF and the XMP cap (callers that know which field is long, such as an export, trim before this). +fn check_app1(what: &str, len: usize, max: usize) -> Result<()> { + match len.checked_sub(max).filter(|over| *over > 0) { + Some(over) => Err(Error::Encode(format!("{what} is {len} bytes, {over} more than the {max} that fit in one JPEG segment"))), + None => Ok(()), + } +} /// The APP segments [`encode_jpeg`] writes for `meta` (marker byte, payload): JFIF density, EXIF, /// XMP and the ICC profile in chunks, in that order. @@ -93,10 +108,8 @@ pub(crate) fn jpeg_app_segments(meta: &EncodeMeta) -> Result)>> }); segs.push((0xE0, [&b"JFIF\0\x01\x02"[..], &ppi, &[0, 0]].concat())); if let Some(exif) = meta.exif { - if exif.len() > 65_527 { - return Err(Error::Encode("EXIF larger than one APP1 segment (64 KiB)".into())); - } - segs.push((0xE1, [&b"Exif\0\0"[..], exif].concat())); + check_app1("the EXIF block", exif.len(), JPEG_MAX_EXIF)?; + segs.push((0xE1, [EXIF_HEADER, exif].concat())); } if let Some(xmp) = meta.xmp { segs.push((0xE1, xmp_segment(xmp)?)); @@ -114,13 +127,10 @@ pub(crate) fn jpeg_app_segments(meta: &EncodeMeta) -> Result)>> Ok(segs) } -/// An APP1 XMP payload (namespace + packet), refusing packets larger than one segment. +/// An APP1 XMP payload (namespace + packet), refusing packets larger than one segment (Extended XMP is not written). pub(crate) fn xmp_segment(xmp: &str) -> Result> { - let seg = [XMP_NS, xmp.as_bytes()].concat(); - if seg.len() > 65_533 { - return Err(Error::Encode("XMP larger than one APP1 segment (extended XMP not supported)".into())); - } - Ok(seg) + check_app1("the XMP packet", xmp.len(), JPEG_MAX_XMP)?; + Ok([XMP_NS, xmp.as_bytes()].concat()) } /// Encode baseline JPEG (8-bit; alpha is dropped). `quality` 1..=100. @@ -133,51 +143,16 @@ pub fn encode_jpeg(img: &EncodeImage, quality: u8, subsampling: ChromaSubsamplin return Err(Error::Encode("JPEG dimensions are limited to 65535".into())); } let n = img.width as usize * img.height as usize; - let (data, ct): (std::borrow::Cow<[u8]>, jpeg_encoder::ColorType) = match img.channels { - 1 => (data[..n].into(), jpeg_encoder::ColorType::Luma), - 2 => (data.as_chunks::<2>().0.iter().take(n).map(|c| c[0]).collect::>().into(), jpeg_encoder::ColorType::Luma), - 3 => (data[..n * 3].into(), jpeg_encoder::ColorType::Rgb), - _ => (data[..n * 4].into(), jpeg_encoder::ColorType::Rgba), + // (a gray + alpha image is encoded as gray: alpha is dropped) + let (data, ch): (std::borrow::Cow<[u8]>, usize) = match img.channels { + 1 => (data[..n].into(), 1), + 2 => (data.as_chunks::<2>().0.iter().take(n).map(|c| c[0]).collect::>().into(), 1), + 3 => (data[..n * 3].into(), 3), + _ => (data[..n * 4].into(), 4), }; - if subsampling != ChromaSubsampling::S422 { - // Parallel encoder (restart-interval bands on all cores). - let segs = jpeg_app_segments(meta)?; - let ch = if img.channels == 2 { 1 } else { img.channels as usize }; - // `data` is already gray for 2-channel input (see above) - return crate::jpeg_par::encode(&data, img.width as usize, img.height as usize, ch, quality, subsampling, &segs); - } - let mut out = Vec::new(); - let mut enc = jpeg_encoder::Encoder::new(&mut out, quality.clamp(1, 100)); - enc.set_sampling_factor(match subsampling { - ChromaSubsampling::S444 => jpeg_encoder::SamplingFactor::R_4_4_4, - ChromaSubsampling::S422 => jpeg_encoder::SamplingFactor::R_4_2_2, - ChromaSubsampling::S420 => jpeg_encoder::SamplingFactor::R_4_2_0, - }); - // Standard tables: jpeg-encoder's optimized-table mode writes non-interleaved scans, which some - // decoders (incl. zune-jpeg 0.5) mishandle. Interleaved baseline is universally supported. - let e = |e: jpeg_encoder::EncodingError| Error::Encode(e.to_string()); - if let Some(ppi) = meta.ppi.filter(|p| *p > 0) { - enc.set_density(jpeg_encoder::PixelDensity::dpi(ppi)); - } - if let Some(exif) = meta.exif { - if exif.len() > 65_527 { - return Err(Error::Encode("EXIF larger than one APP1 segment (64 KiB)".into())); - } - enc.add_exif_metadata(exif).map_err(e)?; - } - if let Some(xmp) = meta.xmp { - let mut seg = XMP_NS.to_vec(); - seg.extend_from_slice(xmp.as_bytes()); - if seg.len() > 65_533 { - return Err(Error::Encode("XMP larger than one APP1 segment (extended XMP not supported)".into())); - } - enc.add_app_segment(1, seg).map_err(e)?; - } - if let Some(icc) = meta.icc { - enc.add_icc_profile(icc).map_err(e)?; - } - enc.encode(&data, img.width as u16, img.height as u16, ct).map_err(e)?; - Ok(out) + // The one JPEG writer: restart-interval bands on all cores, APP segments from `jpeg_app_segments`. + let segs = jpeg_app_segments(meta)?; + crate::jpeg_par::encode(&data, img.width as usize, img.height as usize, ch, quality, subsampling, &segs) } /// Encode PNG (8- or 16-bit; float input is rejected — quantize first). @@ -229,7 +204,8 @@ pub enum TiffCompression { } /// Encode TIFF: 8/16-bit integer or 32-bit float, gray/RGB with optional (unassociated) alpha. -/// ICC and XMP are embedded; EXIF is not (write it through the TIFF writer in `lcc-tiff`). +/// ICC, XMP and EXIF are embedded: the Exif block's IFD0 tags go in the image's IFD0, which points at an Exif IFD +/// and a GPS IFD of the file's own (`tiff_exif`). pub fn encode_tiff(img: &EncodeImage, compression: TiffCompression, meta: &EncodeMeta) -> Result> { img.validate()?; write_tiff(img, compression, meta, 2) @@ -311,6 +287,9 @@ fn write_tiff_with(img: &EncodeImage, compression: TiffCompression, meta: &Encod let predictor = if !float && matches!(compression, TiffCompression::Lzw | TiffCompression::Deflate) { Predictor::Horizontal } else { Predictor::None }; let mut enc = TiffEncoder::new(&mut cur).map_err(e)?.with_compression(comp).with_predictor(predictor); + // the Exif and GPS IFDs are written ahead of the image's IFD, which points at them + let exif = meta.exif.map(crate::tiff_exif::TiffExif::parse).transpose()?; + let exif_at = exif.as_ref().map(|x| x.write_directories(&mut enc)).transpose()?; let (w, h) = (img.width, img.height); let n = w as usize * h as usize; // Gray + alpha is stored as RGBA (the encoder has no GrayA colour type). @@ -328,6 +307,9 @@ fn write_tiff_with(img: &EncodeImage, compression: TiffCompression, meta: &Encod if let Some(xmp) = meta.xmp { im.encoder().write_tag(tiff::tags::Tag::from_u16_exhaustive(700), xmp.as_bytes()).map_err(e)?; } + if let (Some(exif), Some(at)) = (&exif, &exif_at) { + exif.write_ifd0(im.encoder(), at)?; + } if $alpha { im.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[extra_samples][..]).map_err(e)?; } @@ -397,9 +379,18 @@ pub fn encode_webp_lossless(img: &EncodeImage, meta: &EncodeMeta) -> Result u32 { + if lossy { WEBP_MAX_SIDE } else { WEBP_LOSSLESS_MAX_SIDE } +} + /// Encode lossy WebP (VP8, and VP8L-compressed alpha when the image has some) at `quality` 1..=100 through libwebp, /// with `meta`'s ICC profile, EXIF and XMP in an extended (`VP8X`) file. Grey images are written as RGB. An error /// for samples other than 8-bit, sides past [`WEBP_MAX_SIDE`], or a build without [`WEBP_LOSSY`]. diff --git a/crates/codecs/src/exif.rs b/crates/codecs/src/exif.rs index 40803d69b4..48ef544ee3 100644 --- a/crates/codecs/src/exif.rs +++ b/crates/codecs/src/exif.rs @@ -1,5 +1,6 @@ //! Minimal, bounds-checked TIFF/EXIF walking: just what decoding needs (orientation, embedded -//! thumbnail, colour-space hint). Full EXIF parsing lives in `lcc-meta`. +//! thumbnail, colour-space hint). Full EXIF parsing lives in `lcc-meta`. A directory is read as `lcc-tiff` reads it +//! (one entry limit, [`lcc_tiff::DEFAULT_MAX_ENTRIES`]), so a file reads the same here and there (FX-240). /// Byte-order aware reader over a TIFF-structured blob. #[derive(Clone, Copy)] @@ -42,19 +43,30 @@ impl<'a> Tiff<'a> { } Some(self.u32_at(4)? as usize) } - /// Entries of the IFD at `pos` and the offset of the next IFD (0 = none). + /// Entries of the IFD at `pos` and the offset of the next IFD (0 = none), read as `lcc-tiff` reads a directory + /// ([`lcc_tiff::directory_entries`], with its [`lcc_tiff::DEFAULT_MAX_ENTRIES`] limit): the declared count cut to + /// the entries the data holds and to that limit, and the next IFD followed only when the whole table was read. + /// `None` for an empty directory or one with no room for an entry. pub fn ifd(&self, pos: usize) -> Option<(Vec, usize)> { - let n = self.u16_at(pos)? as usize; - if n > 4096 { - return None; - } - let mut v = Vec::with_capacity(n); - for i in 0..n { - let e = pos + 2 + i * 12; - v.push(Entry { tag: self.u16_at(e)?, typ: self.u16_at(e + 2)?, count: self.u32_at(e + 4)?, value_pos: e + 8 }); - } - let next = self.u32_at(pos + 2 + n * 12).unwrap_or(0) as usize; - Some((v, next)) + let order = if self.le { lcc_tiff::ByteOrder::Little } else { lcc_tiff::ByteOrder::Big }; + let dir = lcc_tiff::directory_entries(self.data, u64::try_from(pos).ok()?, order, false, lcc_tiff::DEFAULT_MAX_ENTRIES).ok()?; + let entries = dir + .positions() + .map(|e| { + Some(Entry { + tag: self.u16_at(e)?, + typ: self.u16_at(e.checked_add(2)?)?, + count: self.u32_at(e.checked_add(4)?)?, + value_pos: e.checked_add(8)?, + }) + }) + .collect::>>()?; + let whole = u64::try_from(entries.len()).is_ok_and(|n| n == dir.declared()); + let next = match whole.then(|| pos.checked_add(2)?.checked_add(entries.len().checked_mul(12)?)).flatten() { + Some(at) => self.u32_at(at).unwrap_or(0) as usize, + None => 0, + }; + Some((entries, next)) } /// First value of a SHORT/LONG entry. pub fn uint(&self, e: &Entry) -> Option { @@ -162,4 +174,98 @@ mod tests { assert_eq!(summarize(&[]), ExifSummary::default()); } } + + /// A little-endian TIFF whose IFD0 declares `declared` entries and holds `present` of them: entry `at` (if any) is + /// Orientation = 6, the others ImageWidth. `next` is the next-IFD pointer after the table (when the table is whole). + fn tiff_with_ifd0(declared: u16, present: usize, at: Option, next: u32) -> Vec { + let mut v = b"II*\0\x08\0\0\0".to_vec(); + v.extend_from_slice(&declared.to_le_bytes()); + for i in 0..present { + let (tag, value) = if Some(i) == at { (0x0112u16, 6u16) } else { (0x0100, 0) }; + v.extend_from_slice(&tag.to_le_bytes()); + v.extend_from_slice(&3u16.to_le_bytes()); + v.extend_from_slice(&1u32.to_le_bytes()); + v.extend_from_slice(&value.to_le_bytes()); + v.extend_from_slice(&[0, 0]); + } + v.extend_from_slice(&next.to_le_bytes()); + v + } + + /// `tiff_with_ifd0` followed by an IFD1 holding a JPEG thumbnail (SOI + padding), which IFD0's next pointer names. + fn tiff_with_thumbnail(entries: u16, at: Option) -> Vec { + let ifd1 = 8 + 2 + entries as usize * 12 + 4; + let mut v = tiff_with_ifd0(entries, entries as usize, at, ifd1 as u32); + let thumb = ifd1 + 2 + 2 * 12 + 4; + v.extend_from_slice(&2u16.to_le_bytes()); + for (tag, value) in [(0x0201u16, thumb as u32), (0x0202, 6)] { + v.extend_from_slice(&tag.to_le_bytes()); + v.extend_from_slice(&4u16.to_le_bytes()); + v.extend_from_slice(&1u32.to_le_bytes()); + v.extend_from_slice(&value.to_le_bytes()); + } + v.extend_from_slice(&0u32.to_le_bytes()); + v.extend_from_slice(&[0xFF, 0xD8, 0xFF, 0xD9, 0, 0]); + v + } + + /// The entry limit is the one `lcc-tiff` applies, at, just below and just above it, and at the old 4096: an IFD0 of + /// 4097..8192 entries no longer reads as nothing (its orientation was lost, a rotated photo shown upright). + #[test] + fn the_entry_limit_is_lcc_tiffs_at_below_and_above() { + let limit = lcc_tiff::DEFAULT_MAX_ENTRIES; + assert_eq!(limit, 8192, "the boundaries below are written for this limit"); + for n in [1usize, 4095, 4096, 4097, 8191, 8192, 8193, 9000, 65_535] { + // Orientation last in the table: read when the table is read to its end, else cut off + let blob = tiff_with_ifd0(n as u16, n, Some(n - 1), 0); + let want = (n <= limit).then_some(6); + assert_eq!(summarize(&blob).orientation, want, "{n} entries, orientation last"); + // Orientation first: read whatever the count + let blob = tiff_with_ifd0(n as u16, n, Some(0), 0); + assert_eq!(summarize(&blob).orientation, Some(6), "{n} entries, orientation first"); + // the entries read are as many as `lcc-tiff` reads from the same bytes + let t = Tiff::new(&blob).unwrap(); + let (entries, _) = t.ifd(8).unwrap(); + let shared = lcc_tiff::directory_entries(&blob, 8, lcc_tiff::ByteOrder::Little, false, limit).unwrap(); + assert_eq!((entries.len(), shared.read()), (n.min(limit), n.min(limit)), "{n} entries"); + } + } + + /// The next IFD (the thumbnail's) follows a whole table only: at the limit it is read, one entry past it is not, + /// as `lcc-tiff` leaves the chain after a cut table. + #[test] + fn the_next_ifd_follows_a_table_read_whole_and_not_one_that_was_cut() { + for (n, thumb) in [(4097u16, true), (8192, true), (8193, false)] { + let blob = tiff_with_thumbnail(n, Some(0)); + let s = summarize(&blob); + assert_eq!((s.orientation, s.thumbnail.is_some()), (Some(6), thumb), "{n} entries"); + } + } + + /// Hostile layouts end with nothing or a partial read, never a panic or a loop. + #[test] + fn hostile_directories_are_bounded_and_do_not_panic() { + // 65535 declared, three present: what the data holds is read, no next IFD + let blob = tiff_with_ifd0(65_535, 3, Some(2), 8); + assert_eq!(summarize(&blob).orientation, Some(6)); + // declared but no room for any entry, an empty table, a table starting past the data + assert_eq!(summarize(&tiff_with_ifd0(5, 0, None, 0)), ExifSummary::default()); + assert_eq!(summarize(&tiff_with_ifd0(0, 0, None, 0)), ExifSummary::default()); + assert_eq!(summarize(b"II*\0\xff\xff\xff\xff"), ExifSummary::default()); + assert_eq!(summarize(b"II*\0\xfe\xff\xff\xff\x01\0"), ExifSummary::default()); + // the next pointer names IFD0 itself, and IFD0's own Exif IFD pointer does: no loop + let mut blob = tiff_with_ifd0(2, 2, Some(0), 8); + blob[8 + 2 + 12 - 12..8 + 2 + 12].copy_from_slice(&[0x69, 0x87, 4, 0, 1, 0, 0, 0, 8, 0, 0, 0]); + let s = summarize(&blob); + assert_eq!(s.thumbnail, None); + // a table truncated mid-entry reads the whole entries before it + let mut blob = tiff_with_ifd0(4, 3, Some(1), 0); + blob.truncate(blob.len() - 4 - 5); + assert_eq!(summarize(&blob).orientation, Some(6)); + // every prefix of a valid blob is nothing or a partial read + let whole = tiff_with_thumbnail(40, Some(7)); + for cut in 0..whole.len() { + let _ = summarize(&whole[..cut]); + } + } } diff --git a/crates/codecs/src/gainmap.rs b/crates/codecs/src/gainmap.rs index e7d24477fc..e7c78f5778 100644 --- a/crates/codecs/src/gainmap.rs +++ b/crates/codecs/src/gainmap.rs @@ -539,6 +539,10 @@ fn primary_description(gain_len: usize) -> String { ) } +/// Bytes [`encode_with_gain`] adds to the primary image's XMP packet (the gain map container description), so a caller +/// fitting its own packet to [`crate::encode::JPEG_MAX_XMP`] leaves this much room. +pub const XMP_RESERVE: usize = 1024; + /// `xmp` with `description` added as another `rdf:Description` (a fresh packet when there is /// none, or when it has no `rdf:RDF` to add to). fn merge_xmp(xmp: Option<&str>, description: &str) -> String { @@ -614,8 +618,6 @@ pub fn encode_with_gain(base: &EncodeImage, gain_jpeg: &[u8], quality: u8, sub: if w == 0 || h == 0 || w > u16::MAX as usize || h > u16::MAX as usize { return Err(Error::Encode("JPEG dimensions are limited to 65535".into())); } - // jpeg_par writes 4:4:4 or 4:2:0 - let sub = if sub == ChromaSubsampling::S422 { ChromaSubsampling::S420 } else { sub }; let xmp = merge_xmp(meta.xmp, &primary_description(gain_jpeg.len())); let mut segs = jpeg_app_segments(&EncodeMeta { xmp: Some(&xmp), ..*meta })?; @@ -790,6 +792,23 @@ pub(crate) mod test_support { mod tests { use super::*; + /// What the primary image's packet gains in `encode_with_gain` stays within the room callers leave for it. + #[test] + fn the_container_description_fits_the_reserve() { + let added = primary_description(usize::MAX).len(); + assert!(added <= XMP_RESERVE, "the container description is {added} bytes, the reserve {XMP_RESERVE}"); + // and a packet of exactly the room left is written whole + let room = crate::encode::JPEG_MAX_XMP - XMP_RESERVE; + let px = vec![128u8; 8 * 8 * 3]; + let base = EncodeImage::new(8, 8, 3, Samples::U8(&px)); + let gain = encode_gain(&GainImage { width: 4, height: 4, channels: 3, data: vec![100u8; 48] }, &meta3(), 90).unwrap(); + let open = ""; + let close = ""; + let pad = |len: usize| format!("{open}{}{close}", " ".repeat(len - open.len() - close.len())); + let ok = pad(room); + assert!(encode_with_gain(&base, &gain, 90, ChromaSubsampling::S444, &EncodeMeta { xmp: Some(&ok), ..Default::default() }).is_ok()); + } + fn meta3() -> GainMapMeta { GainMapMeta { multichannel: true, diff --git a/crates/codecs/src/jxl_encode.rs b/crates/codecs/src/jxl_encode.rs index c916376cf2..7a86c7c600 100644 --- a/crates/codecs/src/jxl_encode.rs +++ b/crates/codecs/src/jxl_encode.rs @@ -1,7 +1,8 @@ //! JPEG XL encode via `jixel` (pure Rust, BSD-3-Clause OR Apache-2.0; native targets with the `jxl` //! feature: it spawns threads of its own). Lossy files are VarDCT in XYB, tagged with an enum colour //! encoding the decoder renders back to; lossless files are Modular and keep their samples as they -//! are, tagged with the ICC profile when one is given. EXIF and XMP go in `Exif` / `xml ` boxes. +//! are, tagged with the ICC profile when one is given (HDR ones with the PQ enum encoding, whatever profile is given). +//! EXIF and XMP go in `Exif` / `xml ` boxes. use crate::encode::{EncodeImage, EncodeMeta}; #[cfg(not(target_arch = "wasm32"))] @@ -69,7 +70,7 @@ impl Default for JxlOptions { /// Encode JPEG XL from 8- or 16-bit samples (float samples only with [`JxlColour::Rec2020Pq`]). /// Gray is widened to RGB; alpha is kept only when some pixel is not opaque. The ICC profile in -/// `meta` is embedded in lossless files (lossy ones carry the enum encoding of `o.colour`); `ppi` +/// `meta` is embedded in lossless SDR files (lossy and HDR ones carry the enum encoding of `o.colour`); `ppi` /// has no place in the format. Returns [`Error::Encode`] on wasm32 or without the `jxl` feature. pub fn encode_jxl(img: &EncodeImage, o: &JxlOptions, meta: &EncodeMeta) -> Result> { img.validate()?; @@ -271,7 +272,11 @@ fn run(px: &Pixels, w: usize, h: usize, o: &JxlOptions, meta: &EncodeMeta, gain: if let Some(gain) = gain { c = c.with_gain_map(gain); } + // An HDR file's samples are PQ (this encoder writes them so): it says so with the enum encoding, as a lossy one does. + // A profile handed in describes the samples it was made for (the float TIFF's linear one), not these, and jixel + // signals an ICC instead of the enum (FX-195). if o.lossless + && o.colour != JxlColour::Rec2020Pq && let Some(icc) = meta.icc { c = c.with_icc_profile(icc.to_vec()); diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index f40b8fe3e3..6a40d0dc72 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -47,14 +47,15 @@ mod psd; mod sniff; pub mod space; mod tiff_codec; +mod tiff_exif; pub mod video; mod webp; pub use avif_gainmap::encode_avif_gain_map; pub use encode::{ - ChromaSubsampling, EncodeImage, EncodeMeta, HDR_REFERENCE_WHITE_NITS, HLG_REFERENCE_PEAK_NITS, HdrTransfer, Samples, TiffCompression, WEBP_LOSSY, - WEBP_MAX_SIDE, encode_avif, encode_avif_hdr, encode_avif_pq, encode_jpeg, encode_png, encode_png_pq, encode_psd, encode_tiff, - encode_tiff_associated, encode_webp_lossless, encode_webp_lossy, hlg_signal, + ChromaSubsampling, EncodeImage, EncodeMeta, HDR_REFERENCE_WHITE_NITS, HLG_REFERENCE_PEAK_NITS, HdrTransfer, Samples, TiffCompression, + WEBP_LOSSLESS_MAX_SIDE, WEBP_LOSSY, WEBP_MAX_SIDE, encode_avif, encode_avif_hdr, encode_avif_pq, encode_jpeg, encode_png, encode_png_pq, + encode_psd, encode_tiff, encode_tiff_associated, encode_webp_lossless, encode_webp_lossy, hlg_signal, webp_max_side, }; pub use exr_encode::{ACESCG, ExrOptions, encode_exr}; pub use jxl_encode::{JxlColour, JxlEffort, JxlOptions, encode_jxl, encode_jxl_gain_map}; diff --git a/crates/codecs/src/tiff_exif.rs b/crates/codecs/src/tiff_exif.rs new file mode 100644 index 0000000000..ba1c7939cd --- /dev/null +++ b/crates/codecs/src/tiff_exif.rs @@ -0,0 +1,154 @@ +//! The Exif block of a TIFF export (FX-188). A TIFF file has no Exif blob: its IFD0 holds the block's IFD0 tags (make, +//! model, artist, copyright, description, date, orientation) and points at an Exif IFD (capture settings, lens) and a +//! GPS IFD of its own. The block an encoder is given (`EncodeMeta::exif`, as `lcc_meta::write_exif` writes it) is +//! read with `lcc-tiff` and its entries are written again where the `tiff` encoder puts them. +//! +//! What a block's IFDs carry, and where each goes: +//! - IFD0 entries: into the image's IFD0, except the pointer tags (the file gets its own) and the image layout, +//! resolution, ICC profile and XMP ([`NOT_COPIED`]: the encoder writes the file's). +//! - Exif IFD (34665) and GPS IFD (34853): written as directories of their own, pointed at from IFD0. Every entry is +//! copied as typed; a maker note goes as its bytes (`write_exif` writes none). +//! - Interoperability IFD (40965), SubIFDs (330) and later IFDs (a thumbnail): left out, as are IFD-typed values. +//! `write_exif` writes none of them; their offsets point into the block, not the file. + +use crate::{Error, Result}; +use lcc_tiff::{Value, tags as t}; +use std::io::{Seek, Write}; +use tiff::encoder::{DirectoryEncoder, TiffEncoder, TiffKind}; +use tiff::tags::{Tag, Type}; + +/// The tags of the block's IFD0 that are not copied: the pointers (the file gets its own), and the image layout, +/// resolution, profile and XMP, which the encoder writes for the file (a block taken from a whole TIFF file would +/// otherwise describe that file's image). +const NOT_COPIED: [u16; 27] = [ + t::EXIF_IFD, + t::GPS_IFD, + t::INTEROP_IFD, + t::SUB_IFDS, + t::NEW_SUBFILE_TYPE, + t::IMAGE_WIDTH, + t::IMAGE_LENGTH, + t::BITS_PER_SAMPLE, + t::COMPRESSION, + t::PHOTOMETRIC, + t::STRIP_OFFSETS, + t::SAMPLES_PER_PIXEL, + t::ROWS_PER_STRIP, + t::STRIP_BYTE_COUNTS, + t::PLANAR_CONFIGURATION, + t::PREDICTOR, + t::TILE_WIDTH, + t::TILE_LENGTH, + t::TILE_OFFSETS, + t::TILE_BYTE_COUNTS, + t::EXTRA_SAMPLES, + t::SAMPLE_FORMAT, + t::X_RESOLUTION, + t::Y_RESOLUTION, + t::RESOLUTION_UNIT, + t::XMP, + t::ICC_PROFILE, +]; + +/// An Exif block's entries, sorted for a TIFF file. +pub(crate) struct TiffExif { + /// IFD0's own tags, written into the image's IFD0. + ifd0: Vec<(u16, Value)>, + exif: Vec<(u16, Value)>, + gps: Vec<(u16, Value)>, +} + +/// Where [`TiffExif::write_directories`] put the Exif and GPS IFDs. +pub(crate) struct Pointers { + exif: Option, + gps: Option, +} + +impl TiffExif { + /// Read `block` (a TIFF stream, with or without the `Exif\0\0` prefix). A block that doesn't read is an error: the + /// file is not written without the metadata it was asked to carry. + pub(crate) fn parse(block: &[u8]) -> Result { + let block = block.strip_prefix(b"Exif\0\0").unwrap_or(block); + let tiff = lcc_tiff::Tiff::parse(block).map_err(|e| Error::Encode(format!("TIFF: the Exif metadata does not read ({e})")))?; + let Some(ifd0) = tiff.ifds.first() else { + return Err(Error::Encode("TIFF: the Exif metadata has no IFD".into())); + }; + let entries = |ifd: &lcc_tiff::Ifd, skip: &[u16]| -> Vec<(u16, Value)> { + // an IFD-typed value is an offset into the block, meaningless in the file + ifd.entries + .iter() + .filter(|e| !skip.contains(&e.tag) && !matches!(e.value, Value::Ifd(_) | Value::Ifd8(_))) + .map(|e| (e.tag, e.value.clone())) + .collect() + }; + let pointers = [t::EXIF_IFD, t::GPS_IFD, t::INTEROP_IFD, t::SUB_IFDS]; + Ok(Self { + ifd0: entries(ifd0, &NOT_COPIED), + exif: ifd0.exif.as_deref().map(|i| entries(i, &pointers)).unwrap_or_default(), + gps: ifd0.gps.as_deref().map(|i| entries(i, &pointers)).unwrap_or_default(), + }) + } + + /// Write the Exif and GPS IFDs (those with entries) as directories outside the image chain; returns where they + /// are, for [`Self::write_ifd0`]. + pub(crate) fn write_directories>(&self, enc: &mut TiffEncoder) -> Result { + let mut dir = |entries: &[(u16, Value)]| -> Result> { + if entries.is_empty() { + return Ok(None); + } + let mut d = enc.extra_directory().map_err(tiff_error)?; + put(&mut d, entries)?; + Ok(Some(d.finish_with_offsets().map_err(tiff_error)?.offset)) + }; + Ok(Pointers { exif: dir(&self.exif)?, gps: dir(&self.gps)? }) + } + + /// Write IFD0's tags and the pointers to the directories [`Self::write_directories`] wrote into the image's IFD. + pub(crate) fn write_ifd0(&self, ifd: &mut DirectoryEncoder<'_, W, K>, at: &Pointers) -> Result<()> { + put(ifd, &self.ifd0)?; + for (tag, offset) in [(Tag::ExifDirectory, at.exif), (Tag::GpsDirectory, at.gps)] { + if let Some(offset) = offset { + ifd.write_tag(tag, offset).map_err(tiff_error)?; + } + } + Ok(()) + } +} + +fn tiff_error(e: tiff::TiffError) -> Error { + Error::Encode(format!("TIFF: {e}")) +} + +/// Write `entries` into `dir` as they are typed in the block. +fn put(dir: &mut DirectoryEncoder<'_, W, K>, entries: &[(u16, Value)]) -> Result<()> { + for (tag, value) in entries { + let (ty, bytes) = native(value).ok_or_else(|| Error::Encode(format!("TIFF: Exif tag {tag} has a type a classic TIFF can't hold")))?; + let entry = dir.write_entry_bytes(ty, &bytes).map_err(tiff_error)?; + dir.extend_from(&tiff::Directory::from_iter([(Tag::from_u16_exhaustive(*tag), entry)])); + } + Ok(()) +} + +/// `value` as the `tiff` encoder's field type and bytes, in the byte order it writes (the machine's own). Text keeps its +/// bytes as they are (UTF-8 where the user typed more than ASCII, as the JPEG's block does), NUL-terminated. `None` +/// for the 64-bit and IFD types, which a classic TIFF's Exif has none of. +fn native(value: &Value) -> Option<(Type, Vec)> { + fn ne(v: &[T], bytes: impl Fn(T) -> [u8; N]) -> Vec { + v.iter().flat_map(|&x| bytes(x)).collect() + } + Some(match value { + Value::Byte(v) => (Type::BYTE, v.clone()), + Value::Undefined(v) => (Type::UNDEFINED, v.clone()), + Value::SByte(v) => (Type::SBYTE, ne(v, i8::to_ne_bytes)), + Value::Ascii(s) => (Type::ASCII, s.bytes().chain([0]).collect()), + Value::Short(v) => (Type::SHORT, ne(v, u16::to_ne_bytes)), + Value::SShort(v) => (Type::SSHORT, ne(v, i16::to_ne_bytes)), + Value::Long(v) => (Type::LONG, ne(v, u32::to_ne_bytes)), + Value::SLong(v) => (Type::SLONG, ne(v, i32::to_ne_bytes)), + Value::Rational(v) => (Type::RATIONAL, v.iter().flat_map(|&(n, d)| [n.to_ne_bytes(), d.to_ne_bytes()]).flatten().collect()), + Value::SRational(v) => (Type::SRATIONAL, v.iter().flat_map(|&(n, d)| [n.to_ne_bytes(), d.to_ne_bytes()]).flatten().collect()), + Value::Float(v) => (Type::FLOAT, ne(v, f32::to_ne_bytes)), + Value::Double(v) => (Type::DOUBLE, ne(v, f64::to_ne_bytes)), + Value::Ifd(_) | Value::Long8(_) | Value::SLong8(_) | Value::Ifd8(_) => return None, + }) +} diff --git a/crates/codecs/tests/it/jpeg_segment_caps.rs b/crates/codecs/tests/it/jpeg_segment_caps.rs index 87b897b9ad..344c83fd37 100644 --- a/crates/codecs/tests/it/jpeg_segment_caps.rs +++ b/crates/codecs/tests/it/jpeg_segment_caps.rs @@ -1,6 +1,5 @@ -//! The JPEG APP1 size caps for EXIF and XMP, at, just below and just above each limit, on both encoders (the parallel -//! one for 4:4:4 and 4:2:0, `jpeg-encoder` for 4:2:2), and the parallel encoder's refusal of any segment whose 16-bit -//! length field would wrap. +//! The JPEG APP1 size caps for EXIF and XMP, at, just below and just above each limit, for each chroma subsampling, +//! and the parallel encoder's refusal of any segment whose 16-bit length field would wrap. //! //! A marker segment's length counts its own two bytes, so a payload holds at most 65 533 bytes. EXIF goes in after a //! 6-byte `Exif\0\0`, so EXIF itself holds at most 65 527; an XMP packet goes in after the 29-byte namespace, so it @@ -13,7 +12,7 @@ const EXIF_HEADER: &[u8] = b"Exif\0\0"; const XMP_NS: &[u8] = b"http://ns.adobe.com/xap/1.0/\0"; const MAX_EXIF: usize = MAX_SEGMENT_PAYLOAD - EXIF_HEADER.len(); const MAX_XMP_PACKET: usize = MAX_SEGMENT_PAYLOAD - XMP_NS.len(); -const SUBSAMPLINGS: [ChromaSubsampling; 3] = [ChromaSubsampling::S444, ChromaSubsampling::S420, ChromaSubsampling::S422]; +const SUBSAMPLINGS: [ChromaSubsampling; 2] = [ChromaSubsampling::S444, ChromaSubsampling::S420]; fn pixels() -> Vec { (0..16 * 16).flat_map(|i| [(i * 7 % 256) as u8, (i * 3 % 256) as u8, (i % 256) as u8]).collect() @@ -111,3 +110,28 @@ fn an_app_segment_too_long_for_its_length_field_is_refused() { assert!(r.is_err(), "{len} bytes: gave a JPEG of {:?} bytes", r.map(|j| j.len())); } } + +/// A refusal says which block it is and by how many bytes it is over what one segment holds, the same words for both +/// blocks and for each subsampling, so a caller (and the person reading its error) can see how much to cut (FX-215). +#[test] +fn the_refusal_names_the_block_and_how_far_over_the_cap_it_is() { + for sub in SUBSAMPLINGS { + for over in [1usize, 2, 1000] { + let exif = exif_of(MAX_EXIF + over); + let Err(Error::Encode(m)) = encode(sub, &EncodeMeta { exif: Some(&exif), ..Default::default() }) else { + panic!("{sub:?}: EXIF {over} over") + }; + assert!(m.contains("EXIF") && m.contains(&format!("{} bytes, {over} more than the {MAX_EXIF}", MAX_EXIF + over)), "{sub:?}: {m}"); + let xmp = xmp_of(MAX_XMP_PACKET + over); + let Err(Error::Encode(m)) = encode(sub, &EncodeMeta { xmp: Some(&xmp), ..Default::default() }) else { + panic!("{sub:?}: XMP {over} over") + }; + assert!( + m.contains("XMP") && m.contains(&format!("{} bytes, {over} more than the {MAX_XMP_PACKET}", MAX_XMP_PACKET + over)), + "{sub:?}: {m}" + ); + } + } + // the public limits are the ones the test derives from the segment length + assert_eq!((lcc_codecs::encode::JPEG_MAX_EXIF, lcc_codecs::encode::JPEG_MAX_XMP), (MAX_EXIF, MAX_XMP_PACKET)); +} diff --git a/crates/codecs/tests/it/roundtrip.rs b/crates/codecs/tests/it/roundtrip.rs index 667c41d485..475faae82c 100644 --- a/crates/codecs/tests/it/roundtrip.rs +++ b/crates/codecs/tests/it/roundtrip.rs @@ -37,7 +37,7 @@ fn jpeg_roundtrip_with_metadata() { let exif = minimal_exif(6); let xmp = r#""#; let meta = EncodeMeta { icc: Some(&icc), exif: Some(&exif), xmp: Some(xmp), ..Default::default() }; - for sub in [ChromaSubsampling::S444, ChromaSubsampling::S422, ChromaSubsampling::S420] { + for sub in [ChromaSubsampling::S444, ChromaSubsampling::S420] { let bytes = encode_jpeg(&EncodeImage::rgba8(&img), 95, sub, &meta).unwrap(); assert_eq!(sniff(&bytes), Some(Format::Jpeg)); let d = decode(&bytes, DecodeOptions::default()).unwrap(); @@ -244,6 +244,79 @@ fn tiff_depths_and_compressions() { } } +/// A TIFF carries the Exif block it is given (FX-188): IFD0 has the camera, creator, copyright and date, and points at +/// an Exif IFD (capture settings, lens) and a GPS IFD, for every sample type, with or without alpha and compression. +/// The image, ICC profile and XMP are unchanged; without a block there is no Exif IFD; a block that doesn't read is +/// an error, not a TIFF without it. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn tiff_carries_the_exif_block() { + let m = lcc_meta::Metadata { + make: Some("Synthetic".into()), + model: Some("X2".into()), + artist: Some("A. Person".into()), + copyright: Some("© 2026 Ünï Person".into()), + caption: Some("A caption".into()), + capture_time: lcc_meta::DateTime::parse_iso("2026-09-20T05:40:00.250+02:00"), + exposure_time: Some(1.0 / 250.0), + f_number: Some(2.8), + iso: Some(400), + lens_model: Some("35mm F2".into()), + exposure_bias: Some(-0.7), + gps: Some(lcc_meta::Gps { latitude: 43.7904, longitude: -110.6818, altitude: Some(2000.0) }), + ..Default::default() + }; + let block = lcc_meta::write_exif(&m).unwrap(); + let (w, h) = (24u32, 16u32); + let n = (w * h) as usize; + let u8s: Vec = (0..n * 3).map(|i| (i * 7 % 256) as u8).collect(); + let u16s: Vec = (0..n * 4).map(|i| (i * 977 % 65536) as u16).collect(); + let f32s: Vec = (0..n * 3).map(|i| i as f32 / 100.0 - 3.0).collect(); + let icc = write_named(NamedSpace::AdobeRgb); + let meta = EncodeMeta { icc: Some(&icc), exif: Some(&block), xmp: Some(""), ppi: Some(300) }; + for comp in [TiffCompression::None, TiffCompression::Deflate] { + for (label, img) in [ + ("8-bit", EncodeImage::new(w, h, 3, Samples::U8(&u8s))), + ("16-bit with alpha", EncodeImage::new(w, h, 4, Samples::U16(&u16s))), + ("float", EncodeImage::new(w, h, 3, Samples::F32(&f32s))), + ] { + for associated in [false, true] { + let at = format!("{label}, {comp:?}, associated {associated}"); + let file = if associated { encode_tiff_associated(&img, comp, &meta) } else { encode_tiff(&img, comp, &meta) }.unwrap(); + let back = lcc_meta::read_exif(&file); + assert_eq!((back.make.as_deref(), back.model.as_deref()), (Some("Synthetic"), Some("X2")), "{at}"); + assert_eq!((back.artist.as_deref(), back.copyright.as_deref()), (Some("A. Person"), m.copyright.as_deref()), "{at}"); + assert_eq!(back.caption.as_deref(), Some("A caption"), "{at}"); + assert_eq!(back.capture_time, m.capture_time, "{at}: date, offset and sub-seconds from the Exif IFD"); + assert_eq!((back.iso, back.lens_model.as_deref()), (Some(400), Some("35mm F2")), "{at}"); + assert!(back.f_number.is_some_and(|f| (f - 2.8).abs() < 1e-6), "{at}: {:?}", back.f_number); + assert!(back.exposure_time.is_some_and(|t| (t - 0.004).abs() < 1e-9), "{at}: {:?}", back.exposure_time); + assert!(back.exposure_bias.is_some_and(|b| (b + 0.7).abs() < 1e-3), "{at}: {:?}", back.exposure_bias); + let g = back.gps.unwrap_or_else(|| panic!("{at}: no GPS IFD")); + assert!((g.latitude - 43.7904).abs() < 1e-5 && (g.longitude + 110.6818).abs() < 1e-5, "{at}: {g:?}"); + assert!(g.altitude.is_some_and(|a| (a - 2000.0).abs() < 1e-3), "{at}: {g:?}"); + // the Exif and GPS IFDs are the file's own, pointed at from IFD0 + let t = lcc_tiff::Tiff::parse(&file).unwrap(); + let ifd0 = &t.ifds[0]; + assert!(ifd0.exif.is_some() && ifd0.gps.is_some(), "{at}"); + assert_eq!(ifd0.u32(lcc_tiff::tags::IMAGE_WIDTH), Some(w), "{at}: the block's IFD0 replaced the image's layout"); + // the image and the rest of the metadata are as before + let d = decode(&file, DecodeOptions::default()).unwrap(); + assert_eq!((d.width, d.height), (w, h), "{at}"); + assert_eq!(d.space.named, Some(NamedSpace::AdobeRgb), "{at}"); + assert_eq!(d.xmp.as_deref(), Some(""), "{at}"); + } + } + } + // no block, no Exif IFD + let plain = encode_tiff(&EncodeImage::new(w, h, 3, Samples::U8(&u8s)), TiffCompression::None, &EncodeMeta::default()).unwrap(); + let t = lcc_tiff::Tiff::parse(&plain).unwrap(); + assert!(t.ifds[0].exif.is_none() && t.ifds[0].gps.is_none()); + // a block that doesn't read is an error, not a TIFF without the metadata + let bad = EncodeMeta { exif: Some(b"not a TIFF stream"), ..Default::default() }; + assert!(matches!(encode_tiff(&EncodeImage::new(w, h, 3, Samples::U8(&u8s)), TiffCompression::None, &bad), Err(Error::Encode(_)))); +} + #[test] fn tiff_cmyk_and_orientation() { use tiff::encoder::{TiffEncoder, colortype}; @@ -530,6 +603,81 @@ fn webp_lossy_close_with_metadata() { assert!(encode_webp_lossy(&EncodeImage::new(4, 4, 3, Samples::U16(&deep)), 90, &meta).is_err()); } +/// Lossless WebP takes 16,384 pixels a side, one more than lossy WebP's [`WEBP_MAX_SIDE`]; one more pixel is refused. +#[test] +fn lossless_webp_takes_one_pixel_more_than_lossy() { + let meta = EncodeMeta::default(); + assert_eq!(WEBP_LOSSLESS_MAX_SIDE, WEBP_MAX_SIDE + 1); + for side in [WEBP_MAX_SIDE, WEBP_LOSSLESS_MAX_SIDE] { + let row = vec![0u8; side as usize * 3]; + assert!(encode_webp_lossless(&EncodeImage::new(side, 1, 3, Samples::U8(&row)), &meta).is_ok(), "{side} wide"); + } + let row = vec![0u8; (WEBP_LOSSLESS_MAX_SIDE as usize + 1) * 3]; + assert!(encode_webp_lossless(&EncodeImage::new(WEBP_LOSSLESS_MAX_SIDE + 1, 1, 3, Samples::U8(&row)), &meta).is_err()); +} + +/// The chunks of a WebP file after `RIFF size WEBP`, as (tag, payload). +fn riff_chunks(file: &[u8]) -> Vec<([u8; 4], Vec)> { + assert_eq!((&file[0..4], &file[8..12]), (&b"RIFF"[..], &b"WEBP"[..])); + let mut out = Vec::new(); + let mut at = 12; + while at + 8 <= file.len() { + let tag: [u8; 4] = file[at..at + 4].try_into().unwrap(); + let len = u32::from_le_bytes(file[at + 4..at + 8].try_into().unwrap()) as usize; + out.push((tag, file[at + 8..at + 8 + len].to_vec())); + at += 8 + len + len % 2; + } + out +} + +/// A WebP's metadata chunks are those it was given, each exactly once with its bytes, and its VP8X header declares +/// what it holds: the ICC (0x20), alpha (0x10, lossy: an `ALPH` chunk), EXIF (0x08) and XMP (0x04) bits match the +/// chunks, for every subset of ICC, EXIF and XMP, lossless and (where built) lossy, opaque and transparent (FX-241). +/// A reader that obeys the flags finds every chunk; a copyright in an EXIF-only file is not dropped. +#[test] +fn webp_metadata_chunks_and_vp8x_flags_match_what_it_was_given() { + let icc = write_named(NamedSpace::Srgb); + let exif = minimal_exif(6); + let xmp = ""; + let opaque = gradient(24, 16); + let mut clear = opaque.clone(); + clear.data.iter_mut().enumerate().for_each(|(i, p)| p[3] = if i % 2 == 0 { 255 } else { 0 }); + for (lossy, img) in [(false, &opaque), (false, &clear), (true, &opaque), (true, &clear)] { + if lossy && !WEBP_LOSSY { + continue; + } + for set in 0u8..8 { + let meta = EncodeMeta { + icc: (set & 1 != 0).then_some(&icc[..]), + exif: (set & 2 != 0).then_some(&exif[..]), + xmp: (set & 4 != 0).then_some(xmp), + ..Default::default() + }; + let at = format!("lossy {lossy}, transparent {}, icc {} exif {} xmp {}", img.data[1][3] == 0, set & 1, set & 2, set & 4); + let e = EncodeImage::rgba8(img); + let file = if lossy { encode_webp_lossy(&e, 80, &meta) } else { encode_webp_lossless(&e, &meta) }.unwrap(); + let chunks = riff_chunks(&file); + let all = |tag: &[u8; 4]| chunks.iter().filter(|(t, _)| t == tag).map(|(_, b)| b.clone()).collect::>(); + assert_eq!(all(b"ICCP"), meta.icc.map(<[u8]>::to_vec).into_iter().collect::>(), "{at}: ICC"); + assert_eq!(all(b"EXIF"), meta.exif.map(<[u8]>::to_vec).into_iter().collect::>(), "{at}: EXIF"); + assert_eq!(all(b"XMP "), meta.xmp.map(|x| x.as_bytes().to_vec()).into_iter().collect::>(), "{at}: XMP"); + let Some(vp8x) = all(b"VP8X").first().cloned() else { + // a simple file: no metadata to declare + assert_eq!(set, 0, "{at}: metadata without a VP8X header"); + continue; + }; + assert_eq!(chunks[0].0, *b"VP8X", "{at}: VP8X first"); + let flag = |bit: u8| vp8x[0] & bit != 0; + assert_eq!(flag(0x20), meta.icc.is_some(), "{at}: ICC flag"); + assert_eq!(flag(0x08), meta.exif.is_some(), "{at}: EXIF flag"); + assert_eq!(flag(0x04), meta.xmp.is_some(), "{at}: XMP flag"); + if lossy { + assert_eq!(flag(0x10), !all(b"ALPH").is_empty(), "{at}: alpha flag"); + } + } + } +} + #[test] fn gif_and_bmp_decode() { use image::ImageEncoder; @@ -811,7 +959,7 @@ fn print_resolution_is_written() { let data = vec![128u8; 4 * 4 * 3]; let img = EncodeImage::new(4, 4, 3, Samples::U8(&data)); let meta = EncodeMeta { ppi: Some(300), ..Default::default() }; - for sub in [ChromaSubsampling::S444, ChromaSubsampling::S422] { + for sub in [ChromaSubsampling::S444, ChromaSubsampling::S420] { let j = encode_jpeg(&img, 90, sub, &meta).unwrap(); // SOI, APP0 "JFIF\0" v1.2, units = 1 (dpi), Xdensity, Ydensity assert_eq!(&j[2..4], &[0xFF, 0xE0], "{sub:?}"); @@ -870,6 +1018,23 @@ fn pq_png_is_16_bit_rec2020_pq_with_cicp_and_content_light() { assert!(!bytes.windows(4).any(|w| w == b"iCCP"), "no ICC profile next to cICP"); } +/// A PQ (HDR) PNG carries the EXIF it is given (FX-241): one `eXIf` chunk with its bytes, read back by the decoder, +/// next to the XMP; without EXIF it has none. +#[test] +fn pq_png_carries_its_exif() { + let (w, h) = (8u32, 4u32); + let rgb: Vec = (0..w * h * 3).map(|i| (i % 7) as f32 * 0.5).collect(); + let exif = minimal_exif(1); + let xmp = r#""#; + let bytes = encode_png_pq(w, h, &rgb, &EncodeMeta { exif: Some(&exif), xmp: Some(xmp), ..Default::default() }).unwrap(); + assert_eq!(bytes.windows(4).filter(|w| w == b"eXIf").count(), 1, "one eXIf chunk"); + let d = decode(&bytes, DecodeOptions::default()).unwrap(); + assert_eq!(d.exif.as_deref(), Some(&exif[..]), "the EXIF reads back"); + assert!(bytes.windows(17).any(|w| w == b"XML:com.adobe.xmp"), "XMP kept"); + let plain = encode_png_pq(w, h, &rgb, &EncodeMeta::default()).unwrap(); + assert!(!plain.windows(4).any(|w| w == b"eXIf"), "no EXIF given, none written"); +} + #[test] fn pq_png_rejects_short_buffers_and_survives_hostile_samples() { assert!(encode_png_pq(4, 4, &[1.0; 3], &EncodeMeta::default()).is_err()); @@ -1015,6 +1180,34 @@ fn jxl_hdr_pq() { assert!(matches!(sdr, Err(Error::Encode(_)))); } +/// HDR JPEG XL says PQ with Lossless on too (FX-195): a profile handed in with the metadata (the export passes the +/// float TIFF's linear Rec. 2020 one) is not embedded in place of the PQ colour encoding, so the file never declares its +/// PQ code values linear. An SDR lossless file still carries the profile it is given. +#[test] +#[cfg(feature = "jxl")] +fn jxl_hdr_lossless_says_pq_whatever_profile_it_is_given() { + let (w, h) = (32usize, 16usize); + let px: Vec = (0..w * h).flat_map(|i| [if i % w < w / 2 { 1.0 } else { 4.0 }; 3]).collect(); + let linear = icc::write_matrix_trc(&REC2020, &Trc::Linear); + let meta = EncodeMeta { icc: Some(&linear), ..Default::default() }; + let header = |b: &[u8]| { + let img = jxl_oxide::JxlImage::builder().read(std::io::Cursor::new(b)).unwrap(); + format!("{:?}", img.image_header().metadata.colour_encoding) + }; + for lossless in [false, true] { + let o = JxlOptions { lossless, quality: 95, colour: JxlColour::Rec2020Pq, ..Default::default() }; + let b = encode_jxl(&EncodeImage::new(w as u32, h as u32, 3, Samples::F32(&px)), &o, &meta).unwrap(); + let c = header(&b); + assert!(c.contains("Pq") && !c.contains("IccProfile"), "lossless={lossless}: {c}"); + } + // SDR lossless keeps the profile it is given + let g = gradient(16, 8); + let p3 = write_named(NamedSpace::DisplayP3); + let o = JxlOptions { lossless: true, colour: JxlColour::DisplayP3, ..Default::default() }; + let b = encode_jxl(&EncodeImage::rgba8(&g), &o, &EncodeMeta { icc: Some(&p3), ..Default::default() }).unwrap(); + assert!(header(&b).contains("IccProfile"), "{}", header(&b)); +} + #[test] #[cfg(feature = "jxl")] fn jxl_bad_input_is_an_error() { diff --git a/crates/color/src/cube.rs b/crates/color/src/cube.rs new file mode 100644 index 0000000000..cae380a94c --- /dev/null +++ b/crates/color/src/cube.rs @@ -0,0 +1,63 @@ +//! The text of a `.cube` LUT file's `TITLE` line, which every writer of one shares (FX-196). +//! +//! A `.cube` file is read line by line, so a title holding a line break would end its `TITLE` line early and the rest +//! would be read as lines of the file itself: an injected `DOMAIN_MAX` changes how the look applies with no error, an +//! injected size or data line makes the file refused. Titles come from file names (a Unix name may hold a newline), +//! from users and from other apps' files, so a writer never puts one on its line as it is: it goes through +//! [`title_text`]. + +/// A title as it may stand between the quotes of a `TITLE "…"` line, or `None` when nothing is left of it. +/// +/// - Every control character (`\n`, `\r`, tab, NUL, the C1 controls, …) and the Unicode line and paragraph separators +/// (U+2028, U+2029) become a space, so that no reader, whatever it counts as a line break, sees a second line. +/// - Double quotes are removed (the line is quoted, and the format has no escape for one). +/// - Runs of white space collapse to one space and the ends are trimmed. +pub fn title_text(title: &str) -> Option { + let mapped: String = + title.chars().filter(|&c| c != '"').map(|c| if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') { ' ' } else { c }).collect(); + let clean = mapped.split_whitespace().collect::>().join(" "); + (!clean.is_empty()).then_some(clean) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn line_breaks_and_other_controls_become_one_space() { + assert_eq!(title_text("a\nb").as_deref(), Some("a b")); + assert_eq!(title_text("a\rb").as_deref(), Some("a b")); + assert_eq!(title_text("a\r\nb").as_deref(), Some("a b"), "a Windows line break is one space"); + assert_eq!(title_text("a\n\n\rb").as_deref(), Some("a b")); + assert_eq!(title_text("a\tb\0c\u{85}d\u{b}e\u{c}f").as_deref(), Some("a b c d e f")); + assert_eq!(title_text("a\u{2028}b\u{2029}c").as_deref(), Some("a b c"), "separators other readers split lines on"); + } + + #[test] + fn an_injected_keyword_line_stays_inside_the_title() { + let t = title_text("x\nDOMAIN_MAX 8 8 8\nLUT_3D_SIZE 2").unwrap(); + assert!(!t.contains(['\n', '\r']), "{t:?}"); + assert_eq!(t, "x DOMAIN_MAX 8 8 8 LUT_3D_SIZE 2"); + } + + #[test] + fn quotes_are_removed() { + assert_eq!(title_text("My \"Cam\"\n").as_deref(), Some("My Cam")); + assert_eq!(title_text("\"").as_deref(), None); + assert_eq!(title_text("a\"\nb").as_deref(), Some("a b")); + } + + #[test] + fn a_title_of_nothing_but_such_characters_is_none() { + for t in ["", " ", "\n", "\r\n", "\"\"", " \t\n\r\"\u{2028}\0 ", "\u{a0}"] { + assert_eq!(title_text(t), None, "{t:?}"); + } + } + + #[test] + fn an_ordinary_title_is_kept_and_trimmed() { + assert_eq!(title_text("Warm look: IMG_0001.CR3").as_deref(), Some("Warm look: IMG_0001.CR3")); + assert_eq!(title_text(" Warm fade \u{e9}\u{4e2d}").as_deref(), Some("Warm fade \u{e9}\u{4e2d}")); + assert_eq!(title_text("it's").as_deref(), Some("it's"), "single quotes are fine"); + } +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 0cacefe54e..e827b85f5a 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -7,12 +7,14 @@ //! - Perceptual spaces: OkLab / OkLCh, HSL/HSV in [`perceptual`]. //! - CIE L*a*b* (D50) for colour readouts in [`lab`]. //! - Tone-curve splines in [`spline`]. +//! - The `TITLE` text every `.cube` LUT writer shares ([`cube::title_text`]). //! //! The pipeline's working space is **linear Rec.2020, D65** ([`WORKING`]). #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod cct; +pub mod cube; pub mod lab; pub mod perceptual; pub mod spline; diff --git a/crates/dnglab/Cargo.toml b/crates/dnglab/Cargo.toml new file mode 100644 index 0000000000..283672638d --- /dev/null +++ b/crates/dnglab/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "lcc-dnglab" +version.workspace = true +edition.workspace = true +# rawler (dnglab's decoder library) is LGPL-2.1, which GPL-3.0-or-later builds may carry: a binary built with this +# crate is offered under GPL-3.0-or-later (see NOTICE). +license = "GPL-3.0-or-later" +description = "dnglab (L0, opt-in): reads a raw file's unpacked mosaic and levels with rawler, the pure-Rust decoder library of the dnglab project. Built only with the engine's `dnglab` feature; the app develops the mosaic itself." + +# rawler does not build for wasm32 (its uuid needs a randomness source there); the web has no dnglab +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# Pinned to a minor version: the decoder's name and version are part of the render cache keys +# (`lcc_engine::raw_decoder::key`), so a new rawler re-renders thumbnails read by it. Keep RAWLER_VERSION in step. +rawler = { workspace = true } + +[lints] +workspace = true diff --git a/crates/dnglab/LICENSE-rawler-LGPL-2.1.txt b/crates/dnglab/LICENSE-rawler-LGPL-2.1.txt new file mode 100644 index 0000000000..86cd459cd2 --- /dev/null +++ b/crates/dnglab/LICENSE-rawler-LGPL-2.1.txt @@ -0,0 +1,504 @@ +GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +(This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.) + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random + Hacker. + + {signature of Ty Coon}, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! \ No newline at end of file diff --git a/crates/dnglab/src/lib.rs b/crates/dnglab/src/lib.rs new file mode 100644 index 0000000000..3f469a1fda --- /dev/null +++ b/crates/dnglab/src/lib.rs @@ -0,0 +1,110 @@ +//! Reads a raw file with [rawler](https://github.com/dnglab/dnglab), the decoder library of the dnglab project: its +//! unpacked mosaic, colour filter layout, black and white levels, as-shot multipliers and rawler's D65 camera +//! matrix. Nothing more: rawler's own processing (scaling, demosaic, colour) is never run, the app develops the mosaic +//! itself. +//! +//! rawler is pure Rust (LGPL-2.1, see `NOTICE`), so unlike LibRaw it needs nothing at build time; the engine uses this +//! crate only with its `dnglab` feature (the desktop app and the CLI). It is left out of the web build, where a panic +//! inside a decoder aborts the page instead of being caught. +//! +//! Everything rawler reports is read from an untrusted file and checked here ([`unpack`]): sizes, the pattern, the +//! levels and the matrix. A panic inside rawler is caught (rawler catches its own too) and becomes an error. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +// the web build has no reader (see `read`), so the checks it uses go unused there +#![cfg_attr(target_arch = "wasm32", allow(dead_code))] + +/// The rawler release this crate builds against (Cargo.toml pins the minor version). +pub const RAWLER_VERSION: &str = "0.8"; + +/// The decoder's name, as Settings and logs show it. +pub fn name() -> String { + format!("dnglab (rawler {RAWLER_VERSION})") +} + +/// A colour filter pattern: `width × height` colour indices (0 red, 1 green, 2 blue), row-major, anchored at the +/// data's sample (0, 0). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Pattern { + pub width: usize, + pub height: usize, + pub colors: Vec, +} + +/// The black level as a `rows × cols` grid repeating from the image area's top-left sample. +#[derive(Clone, Debug, PartialEq)] +pub struct BlackGrid { + pub rows: usize, + pub cols: usize, + pub values: Vec, +} + +/// A raw file's mosaic as rawler unpacked it. +#[derive(Clone, Debug, PartialEq)] +pub struct Unpacked { + /// The whole data, masked borders included. + pub width: usize, + pub height: usize, + /// `width × height` samples. + pub data: Vec, + /// The image area: x, y, width, height. + pub image_area: [usize; 4], + /// The default crop within the image area (x, y, width, height), when rawler's camera data has one. + pub crop: Option<[usize; 4]>, + /// `None`: a monochrome sensor. + pub pattern: Option, + pub black: BlackGrid, + pub white: f32, + pub bits: u32, + /// As-shot multipliers, green = 1. + pub as_shot: Option<[f32; 3]>, + /// XYZ (D65) → camera. + pub xyz_to_camera: Option<[[f64; 3]; 3]>, +} + +/// The most samples taken from rawler: 600 MP, above any sensor made. +pub const MAX_SAMPLES: usize = 600_000_000; +/// The largest repeat (rows or columns) of a pattern or black grid. +const MAX_REPEAT: usize = 16; + +#[cfg(not(target_arch = "wasm32"))] +mod read; +#[cfg(not(target_arch = "wasm32"))] +pub use read::{decode, unpack}; + +/// Unpack a raw file held in memory: never on the web, where rawler is not built. +#[cfg(target_arch = "wasm32")] +pub fn decode(_bytes: &[u8]) -> Result { + Err("dnglab is not part of the web version".into()) +} + +/// The significant bits of a clip level. +fn bits_for(white: f32) -> u32 { + let mut bits = 1; + while bits < 16 && f64::from(white) >= f64::from(1u32 << bits) { + bits += 1; + } + bits +} + +/// rawler's as-shot coefficients (RGBE, NaN when the file has none) as multipliers with green = 1. +fn as_shot(c: [f32; 4]) -> Option<[f32; 3]> { + let [r, g, b, _] = c; + [r, g, b].iter().all(|v| v.is_finite() && *v > 0.0).then(|| [r / g, 1.0, b / g]) +} + +/// A 3 × 3 matrix from rawler's flat one (a 4-colour matrix is not taken), when finite and not all zero. +fn matrix3(m: &[f32]) -> Option<[[f64; 3]; 3]> { + if m.len() != 9 || m.iter().any(|v| !v.is_finite()) || m.iter().all(|v| *v == 0.0) { + return None; + } + let mut out = [[0.0; 3]; 3]; + for (i, v) in m.iter().enumerate() { + *out.get_mut(i / 3)?.get_mut(i % 3)? = f64::from(*v); + } + Some(out) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests; diff --git a/crates/dnglab/src/read.rs b/crates/dnglab/src/read.rs new file mode 100644 index 0000000000..3ecffa5340 --- /dev/null +++ b/crates/dnglab/src/read.rs @@ -0,0 +1,115 @@ +//! The reading itself, through rawler (not on the web: rawler doesn't build for wasm32, and a panic there aborts). + +use super::{BlackGrid, MAX_REPEAT, MAX_SAMPLES, Pattern, Unpacked, as_shot, bits_for, matrix3}; + +use rawler::RawImage; +use rawler::decoders::RawDecodeParams; +use rawler::rawimage::{RawImageData, RawPhotometricInterpretation}; +use rawler::rawsource::RawSource; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +/// Unpack a raw file held in memory. +pub fn decode(bytes: &[u8]) -> Result { + let caught = catch_unwind(AssertUnwindSafe(|| { + let source = RawSource::new_from_slice(bytes); + rawler::decode(&source, &RawDecodeParams::default()) + })); + match caught { + Ok(Ok(raw)) => unpack(raw), + Ok(Err(e)) => Err(format!("dnglab could not read the file: {e}")), + Err(_) => Err("dnglab stopped on this file (an internal error, caught)".into()), + } +} + +/// rawler's image in the app's terms, every number checked. +pub fn unpack(raw: RawImage) -> Result { + if raw.fuji_rotation_width.is_some() { + return Err("dnglab reads this SuperCCD file in its rotated layout, which the app doesn't take from dnglab".into()); + } + if raw.cpp != 1 { + return Err(format!("dnglab read {} colours per pixel; the app takes only mosaic or monochrome data from it", raw.cpp)); + } + let (width, height) = (raw.width, raw.height); + let samples = width.checked_mul(height).ok_or("dnglab's image size overflows")?; + if width == 0 || height == 0 || samples > MAX_SAMPLES { + return Err(format!("dnglab's image is {width} x {height}, outside the sizes the app reads")); + } + let data = match raw.data { + RawImageData::Integer(d) => d, + RawImageData::Float(_) => return Err("dnglab read floating-point samples; the app reads those files itself".into()), + }; + if data.len() != samples { + return Err(format!("dnglab returned {} samples for {width} x {height}", data.len())); + } + + let area = raw.active_area.unwrap_or_else(|| rawler::imgop::Rect::new(rawler::imgop::Point::zero(), rawler::imgop::Dim2::new(width, height))); + let (ax, ay, aw, ah) = (area.p.x, area.p.y, area.d.w, area.d.h); + let fits = aw > 0 && ah > 0 && ax.checked_add(aw).is_some_and(|r| r <= width) && ay.checked_add(ah).is_some_and(|b| b <= height); + if !fits { + return Err("dnglab's image area lies outside its data".into()); + } + + let pattern = match &raw.photometric { + RawPhotometricInterpretation::Cfa(config) => Some(pattern(&config.cfa)?), + RawPhotometricInterpretation::BlackIsZero | RawPhotometricInterpretation::LinearRaw => None, + }; + let black = black_grid(&raw.blacklevel, ax, ay)?; + // one clip level for every channel: the lowest, so no channel clips above it + let white = raw.whitelevel.0.iter().copied().min().map(|w| w as f32).ok_or("dnglab reported no white level")?; + let black_mean = black.values.iter().sum::() / black.values.len().max(1) as f32; + if !white.is_finite() || white <= black_mean || white > 65535.0 { + return Err(format!("dnglab reported unusable levels (black {black_mean}, white {white})")); + } + // rawler reports the container's 16 bits; the significant bits follow from the clip level + let bits = bits_for(white); + let crop = raw.crop_area.and_then(|c| { + let (x, y) = (c.p.x.checked_sub(ax)?, c.p.y.checked_sub(ay)?); + let fits = c.d.w > 0 && c.d.h > 0 && x.checked_add(c.d.w)? <= aw && y.checked_add(c.d.h)? <= ah; + fits.then_some([x, y, c.d.w, c.d.h]) + }); + let as_shot = as_shot(raw.wb_coeffs); + let xyz_to_camera = raw.color_matrix.get(&rawler::imgop::xyz::Illuminant::D65).and_then(|m| matrix3(m)); + + Ok(Unpacked { width, height, data, image_area: [ax, ay, aw, ah], crop, pattern, black, white, bits, as_shot, xyz_to_camera }) +} + +/// The colour filter pattern, red, green and blue only (4-colour sensors are left to the app's own decoder). +pub(crate) fn pattern(cfa: &rawler::CFA) -> Result { + let (w, h) = (cfa.width, cfa.height); + if w == 0 || h == 0 || w > MAX_REPEAT || h > MAX_REPEAT { + return Err(format!("dnglab reported a {w} x {h} colour filter pattern, which the app doesn't read")); + } + let mut colors = Vec::with_capacity(w * h); + for row in 0..h { + for col in 0..w { + let c = cfa.color_at(row, col); + let c = u8::try_from(c).ok().filter(|c| *c <= 2).ok_or("dnglab reported a colour filter beyond red, green and blue")?; + colors.push(c); + } + } + Ok(Pattern { width: w, height: h, colors }) +} + +/// rawler's black level (a grid anchored at the data's first sample) re-anchored at the image area. +pub(crate) fn black_grid(b: &rawler::rawimage::BlackLevel, ax: usize, ay: usize) -> Result { + let bad = || "dnglab reported an unusable black level".to_string(); + let values: Vec = b.levels.iter().map(|r| if r.d == 0 { f32::NAN } else { r.n as f32 / r.d as f32 }).collect(); + if values.iter().any(|v| !v.is_finite() || *v < 0.0) { + return Err(bad()); + } + if values.len() == 1 { + return Ok(BlackGrid { rows: 1, cols: 1, values }); + } + let (w, h, cpp) = (b.width, b.height, b.cpp); + if cpp != 1 || w == 0 || h == 0 || w > MAX_REPEAT || h > MAX_REPEAT || w.checked_mul(h) != Some(values.len()) { + return Err(bad()); + } + let mut out = Vec::with_capacity(values.len()); + for row in 0..h { + for col in 0..w { + let v = values.get(((row + ay % h) % h) * w + (col + ax % w) % w).copied().ok_or_else(bad)?; + out.push(v); + } + } + Ok(BlackGrid { rows: h, cols: w, values: out }) +} diff --git a/crates/dnglab/src/tests.rs b/crates/dnglab/src/tests.rs new file mode 100644 index 0000000000..3f0695f37d --- /dev/null +++ b/crates/dnglab/src/tests.rs @@ -0,0 +1,73 @@ +use super::read::{black_grid, pattern}; +use super::*; + +#[test] +fn hostile_bytes_are_errors_not_panics() { + let mut tiff_le = b"II*\0\x08\0\0\0".to_vec(); + tiff_le.extend([0xff; 64]); + let mut many_entries = b"MM\0*\0\0\0\x08\xff\xff".to_vec(); + many_entries.extend([0x01; 200]); + let cases: Vec<(&str, Vec)> = vec![ + ("empty", vec![]), + ("one byte", vec![0]), + ("text", b"not a raw file at all".to_vec()), + ("tiff header, garbage IFD", tiff_le), + ("tiff, huge entry count", many_entries), + ("cr3-ish box", b"\0\0\0\x18ftypcrx \0\0\0\x01crx isom".to_vec()), + ("fuji-ish", b"FUJIFILMCCD-RAW 0201FF383501".iter().copied().chain([0xff; 256]).collect()), + ("noise", (0..4096u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect()), + ]; + for (what, bytes) in cases { + assert!(decode(&bytes).is_err(), "{what}: decoded"); + } +} + +#[test] +fn black_grid_moves_to_the_image_area() { + let r = |n| rawler::formats::tiff::Rational::new(n, 1); + let b = rawler::rawimage::BlackLevel { levels: vec![r(10), r(20), r(30), r(40)], cpp: 1, width: 2, height: 2 }; + assert_eq!(black_grid(&b, 0, 0).unwrap().values, vec![10.0, 20.0, 30.0, 40.0]); + // an image area starting one column and one row in starts at the data's (1, 1) sample + assert_eq!(black_grid(&b, 1, 1).unwrap().values, vec![40.0, 30.0, 20.0, 10.0]); + assert_eq!(black_grid(&b, 3, 0).unwrap().values, vec![20.0, 10.0, 40.0, 30.0]); + let one = rawler::rawimage::BlackLevel { levels: vec![r(512)], cpp: 1, width: 1, height: 1 }; + assert_eq!(black_grid(&one, 7, 3).unwrap(), BlackGrid { rows: 1, cols: 1, values: vec![512.0] }); +} + +#[test] +fn hostile_black_levels_are_refused() { + let r = |n, d| rawler::formats::tiff::Rational { n, d }; + let zero_den = rawler::rawimage::BlackLevel { levels: vec![r(1, 0)], cpp: 1, width: 1, height: 1 }; + assert!(black_grid(&zero_den, 0, 0).is_err()); + let wrong_count = rawler::rawimage::BlackLevel { levels: vec![r(1, 1); 3], cpp: 1, width: 2, height: 2 }; + assert!(black_grid(&wrong_count, 0, 0).is_err()); + let zero_dim = rawler::rawimage::BlackLevel { levels: vec![r(1, 1); 4], cpp: 1, width: 0, height: 4 }; + assert!(black_grid(&zero_dim, 0, 0).is_err()); + let rgb = rawler::rawimage::BlackLevel { levels: vec![r(1, 1); 12], cpp: 3, width: 2, height: 2 }; + assert!(black_grid(&rgb, 0, 0).is_err()); +} + +#[test] +fn patterns_are_rgb_only() { + let p = pattern(&rawler::CFA::new("RGGB")).unwrap(); + assert_eq!(p, Pattern { width: 2, height: 2, colors: vec![0, 1, 1, 2] }); + let x = pattern(&rawler::CFA::new(&"RGBGBR".repeat(6))).unwrap(); + assert_eq!((x.width, x.height, x.colors.len()), (6, 6, 36)); + assert!(pattern(&rawler::CFA::new("RGBE")).is_err(), "four colours"); + assert!(pattern(&rawler::CFA::new("")).is_err(), "no pattern"); +} + +#[test] +fn multipliers_and_matrices_are_checked() { + assert_eq!(as_shot([2.0, 1.0, 1.5, f32::NAN]), Some([2.0, 1.0, 1.5])); + assert_eq!(as_shot([4.0, 2.0, 3.0, 2.0]), Some([2.0, 1.0, 1.5])); + assert_eq!(as_shot([f32::NAN; 4]), None); + assert_eq!(as_shot([1.0, 0.0, 1.0, 0.0]), None); + assert!(matrix3(&[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_some()); + assert!(matrix3(&[0.0; 9]).is_none()); + assert!(matrix3(&[1.0; 12]).is_none()); + assert!(matrix3(&[f32::INFINITY; 9]).is_none()); + assert_eq!(bits_for(4095.0), 12); + assert_eq!(bits_for(16383.0), 14); + assert_eq!(bits_for(65535.0), 16); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index acb61b253f..4afc3618a8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] lcc-libraw = { workspace = true, optional = true } +lcc-dnglab = { workspace = true, optional = true } # Paths stored in a Lightroom catalog: local files or the catalog's share (the fork also follows other shares). craft-docpath = { workspace = true } lcc-filters = { workspace = true } @@ -135,6 +136,9 @@ test-support = [] # LibRaw as a raw decoder a camera can be set to (`raw_decoder`): links the LibRaw C++ library when its build finds # one (`LIBRAW_DIR` / `LIBRAW_SYSTEM=1`, crates/libraw/build.rs), otherwise a stub. Desktop app and CLI only. libraw = ["dep:lcc-libraw"] +# dnglab's decoder (`rawler`, pure Rust, LGPL-2.1) as a raw decoder a camera can be set to (`raw_decoder`). Desktop app +# and CLI; not the web build, where a panic inside a decoder aborts the page instead of being caught. +dnglab = ["dep:lcc-dnglab"] [dev-dependencies] # tests/net_fetch_parity.rs runs both HTTP stacks on the same inputs diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 5ceb1fb024..fff77e5861 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -424,6 +424,12 @@ impl Activity { lock(&self.inner.tasks).iter().find(|e| e.parent.is_none() && (e.batch || KINDS.contains(&e.kind))).map(|e| e.kind) } + /// Whether a task of `kind` that is not a photo's row under a batch is in flight (one being stopped counts: it + /// holds its files until it ends). + pub fn is_running(&self, kind: &str) -> bool { + lock(&self.inner.tasks).iter().any(|e| e.parent.is_none() && e.kind == kind) + } + /// Register a task; it is listed until the returned guard is dropped. `label` is English (the frontend /// translates it). pub fn start(&self, kind: &'static str, label: &str, cancel: Cancel) -> TaskGuard { diff --git a/crates/engine/src/cmd/edit_in.rs b/crates/engine/src/cmd/edit_in.rs index 8bcf18f47d..116bc01c2a 100644 --- a/crates/engine/src/cmd/edit_in.rs +++ b/crates/engine/src/cmd/edit_in.rs @@ -473,15 +473,33 @@ fn out_dir(src: &Source, p: &Value, cmd: &str) -> Result { /// `dir/stem.ext`, or `dir/stem-2.ext`, … when taken. fn unique_path(dir: &str, stem: &str, ext: &str) -> Result { + unique_path_group(dir, stem, &[ext]) +} + +/// [`unique_path`] for a file with sidecars: `dir/stem.ext` with `dir/stem.` for each of `exts[1..]`, or the +/// first `stem-N` at which none of the names `exts` gives is taken, so a sidecar is named for the file it goes with +/// (FX-235). `exts[0]` is the file's own; the path returned is that file's. +fn unique_path_group(dir: &str, stem: &str, exts: &[&str]) -> Result { + unique_path_below(dir, stem, exts, lcc_catalog::safe_file::NUMBERED_NAME_TRIES) +} + +/// [`unique_path_group`] trying the numbers below `below` only. +fn unique_path_below(dir: &str, stem: &str, exts: &[&str], below: u32) -> Result { + use lcc_catalog::safe_file::{first_free_numbered_below, split_extension}; let d = Path::new(dir); - for i in 1..10_000u32 { - let name = if i == 1 { format!("{stem}.{ext}") } else { format!("{stem}-{i}.{ext}") }; - let p = d.join(name); - if !p.exists() { - return Ok(p); - } + let first = exts.first().copied().unwrap_or_default(); + // whether the file `name` (`stem.first`, `stem-N.first`) or a sidecar named for it is there + let taken = |name: &str| { + let sidecar_stem = split_extension(name).0; + d.join(name).exists() || exts.iter().skip(1).any(|x| d.join(format!("{sidecar_stem}.{x}")).exists()) + }; + let plain = format!("{stem}.{first}"); + if !taken(&plain) { + return Ok(d.join(plain)); } - Err(bad("photo.editIn", format!("no free file name for {stem}.{ext} in {dir}"))) + first_free_numbered_below(stem, Some(first), 2, below, |n| !taken(n)) + .map(|n| d.join(n)) + .ok_or_else(|| bad("photo.editIn", format!("no free file name for {stem}.{first} in {dir}"))) } /// The file name stem (no extension) of the copy an editor gets of `ph`, from the naming template: @@ -757,19 +775,18 @@ fn linked_xmp(s: &Session, id: PhotoId, seed: &str) -> Option { fn linked_tiff(s: &mut Session, id: PhotoId, space: lcc_pipeline::OutputSpace, depth: u8, seed: &str, cmd: &str) -> Result> { let ph = s.catalog.photo(id).cloned().ok_or_else(|| bad(cmd, "no photo"))?; let meta = crate::export::export_metadata(&ph, &s.catalog, &crate::export::ExportOptions::default()); - let exif = meta.as_ref().map(lcc_meta::write_exif); + let exif = crate::export::exif_block(meta.as_ref()).map_err(|e| bad(cmd, e))?; let xmp = linked_xmp(s, id, seed); if depth == 32 { // 32-bit float TIFF is linear light (as an editor's float files are): rendered through // the float export and encoded with the metadata let r = render32(s, id, space, cmd)?; - let profile = r.icc.clone().unwrap_or_else(|| lcc_codecs::icc::write_named(crate::export::named_space(space))); + let embedded = crate::export::Embedded::new(space, r.icc.clone(), exif, xmp, None); let img = lcc_codecs::EncodeImage::new(r.width, r.height, 3, lcc_codecs::Samples::F32(&r.rgb)); - let em = lcc_codecs::EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: None }; - return lcc_codecs::encode_tiff(&img, lcc_codecs::TiffCompression::Deflate, &em).map_err(|e| bad(cmd, e.to_string())); + return lcc_codecs::encode_tiff(&img, lcc_codecs::TiffCompression::Deflate, &embedded.encode_meta()).map_err(|e| bad(cmd, e.to_string())); } let r = render16(s, id, space, cmd)?; - let profile = r.icc.clone().unwrap_or_else(|| lcc_codecs::icc::write_named(crate::export::named_space(space))); + let embedded = crate::export::Embedded::new(space, r.icc.clone(), exif, xmp, None); let eight: Vec; let img = if depth == 8 { eight = r.rgb.iter().map(|x| ((u32::from(*x) * 255 + 32_767) / 65_535) as u8).collect(); @@ -777,8 +794,7 @@ fn linked_tiff(s: &mut Session, id: PhotoId, space: lcc_pipeline::OutputSpace, d } else { lcc_codecs::EncodeImage::new(r.width, r.height, 3, lcc_codecs::Samples::U16(&r.rgb)) }; - let em = lcc_codecs::EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: None }; - lcc_codecs::encode_tiff(&img, lcc_codecs::TiffCompression::Deflate, &em).map_err(|e| bad(cmd, e.to_string())) + lcc_codecs::encode_tiff(&img, lcc_codecs::TiffCompression::Deflate, &embedded.encode_meta()).map_err(|e| bad(cmd, e.to_string())) } /// A PNG of `id` rendered with its edits (8 or 16 bits in `space`), with the export metadata @@ -787,10 +803,9 @@ fn linked_png(s: &mut Session, id: PhotoId, space: lcc_pipeline::OutputSpace, de let r = render16(s, id, space, cmd)?; let ph = s.catalog.photo(id).cloned().ok_or_else(|| bad(cmd, "no photo"))?; let meta = crate::export::export_metadata(&ph, &s.catalog, &crate::export::ExportOptions::default()); - let exif = meta.as_ref().map(lcc_meta::write_exif); + let exif = crate::export::exif_block(meta.as_ref()).map_err(|e| bad(cmd, e))?; let xmp = linked_xmp(s, id, seed); - let profile = r.icc.clone().unwrap_or_else(|| lcc_codecs::icc::write_named(crate::export::named_space(space))); - let em = lcc_codecs::EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: None }; + let embedded = crate::export::Embedded::new(space, r.icc.clone(), exif, xmp, None); let eight: Vec; let img = if depth == 8 { eight = r.rgb.iter().map(|x| ((u32::from(*x) * 255 + 32_767) / 65_535) as u8).collect(); @@ -798,7 +813,7 @@ fn linked_png(s: &mut Session, id: PhotoId, space: lcc_pipeline::OutputSpace, de } else { lcc_codecs::EncodeImage::new(r.width, r.height, 3, lcc_codecs::Samples::U16(&r.rgb)) }; - lcc_codecs::encode_png(&img, &em).map_err(|e| bad(cmd, e.to_string())) + lcc_codecs::encode_png(&img, &embedded.encode_meta()).map_err(|e| bad(cmd, e.to_string())) } /// A scene-linear OpenEXR of `id` with its edits: Rec. 2020 primaries (the pipeline's working @@ -876,15 +891,15 @@ fn edit_in(s: &mut Session, p: &Value) -> Result { dest } Format::Exr => { - let dest = unique_path(&dir, &stem, "exr")?; + // (the sidecar's name is reserved with the file's: the link goes with the file it is named for) + let dest = unique_path_group(&dir, &stem, &["exr", "xmp"])?; let bytes = exr_copy(s, id, pr.bit_depth, C)?; write_durable(&dest, &bytes, C)?; // EXR carries no metadata packet: the linked XMP goes to a sidecar beside it if let Some(x) = linked_xmp(s, id, &dest.to_string_lossy()) && !x.is_empty() { - let side = unique_path(&dir, &stem, "xmp")?; - write_durable(&side, x.as_bytes(), C)?; + write_durable(&dest.with_extension("xmp"), x.as_bytes(), C)?; } dest } @@ -1189,6 +1204,39 @@ pub(super) fn specs() -> Vec { mod tests { use super::*; + /// A copy takes the first free `stem-N`, and a file with a sidecar takes a number at which neither the file's name + /// nor its sidecar's is taken: the sidecar is named for its file, never for an older one (FX-235). + #[test] + fn a_copy_takes_the_first_free_number_and_a_sidecar_goes_with_its_file() { + let d = std::env::temp_dir().join(format!("lcc-editin-names-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let dir = d.to_string_lossy().to_string(); + let put = |n: &str| std::fs::write(d.join(n), b"x").unwrap(); + assert_eq!(unique_path(&dir, "lake-Edit", "tif").unwrap(), d.join("lake-Edit.tif")); + put("lake-Edit.tif"); + put("lake-Edit-3.tif"); + assert_eq!(unique_path(&dir, "lake-Edit", "tif").unwrap(), d.join("lake-Edit-2.tif")); + // an OpenEXR copy and its XMP: the sidecar name taken (by another file) moves the pair to the next number + assert_eq!(unique_path_group(&dir, "lake-Edit", &["exr", "xmp"]).unwrap(), d.join("lake-Edit.exr")); + put("lake-Edit.xmp"); + assert_eq!(unique_path_group(&dir, "lake-Edit", &["exr", "xmp"]).unwrap(), d.join("lake-Edit-2.exr")); + put("lake-Edit-2.xmp"); + assert_eq!(unique_path_group(&dir, "lake-Edit", &["exr", "xmp"]).unwrap(), d.join("lake-Edit-3.exr")); + // …and the file's name taken with the sidecar's free: the pair still moves on together + put("lake-Edit-3.exr"); + assert_eq!(unique_path_group(&dir, "lake-Edit", &["exr", "xmp"]).unwrap(), d.join("lake-Edit-4.exr")); + // the bound: below / at / above the last number tried + put("lake-Edit-2.tif"); + put("lake-Edit-4.tif"); + put("lake-Edit-5.tif"); + assert_eq!(unique_path_below(&dir, "lake-Edit", &["tif"], 7).unwrap(), d.join("lake-Edit-6.tif")); + put("lake-Edit-6.tif"); + assert!(unique_path_below(&dir, "lake-Edit", &["tif"], 7).is_err(), "every number below the bound is taken"); + assert!(unique_path_below(&dir, "lake-Edit", &["tif"], 8).is_ok(), "one more number to try"); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn command_line_places_the_file_and_the_default_opener_takes_it_without_a_shell() { // the command line places the file diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs index 1234c13263..db224844e2 100644 --- a/crates/engine/src/cmd/export.rs +++ b/crates/engine/src/cmd/export.rs @@ -44,6 +44,21 @@ impl Session { o.insert(k.clone(), v.clone()); } } + // The preset's format against the caller's exact path: `{preset: "JPEG (Small)", path: + // "a.png"}` wrote JPEG bytes to `a.png` (FX-191). The caller's own `format` is theirs to + // set beside their own `path`, as it always was; a preset's is refused, not let beat the + // path the caller wrote. A preset without `format` follows the path. + let own_format = p.get("format").is_some_and(Value::is_string); + if let (false, Some(path), Some(format)) = (own_format, p.get("path").and_then(Value::as_str), out.get("format").and_then(Value::as_str)) { + let wanted = crate::export::ExportFormat::parse(format); + if let Some((w, ext)) = wanted.and_then(|w| crate::export::ExportOptions::extension_naming_another_format(path, w).map(|e| (w, e))) { + return Err(format!( + "preset `{}` exports {format}, but `path` ends in `.{ext}`: give a path ending in `.{}`, a preset of that format, or the `format` the path names", + preset.name, + w.extension() + )); + } + } // the preset's depth is judged against the format written, known only now (`path`); a // depth the call passes itself is the caller's, and validated as such if p.get("bitDepth").is_none_or(|d| d.is_null()) { @@ -87,7 +102,7 @@ fn save(s: &mut Session, p: &Value) -> Result { // it is judged when the preset exports None => { let last = s.last_export.as_ref().ok_or_else(|| bad(ID, "no `params` and no previous export to save"))?; - let mut last = crate::export::ExportOptions::known_keys(last); + let mut last = crate::export::ExportOptions::without_chosen_folder(crate::export::ExportOptions::known_keys(last)); if last.get("format").is_some_and(Value::is_string) { crate::export::ExportOptions::drop_unfit_depth(&mut last, Default::default()); } @@ -208,11 +223,12 @@ pub fn specs() -> Vec { #[allow(unused_mut)] let mut v = vec![ cmd!(query "export.contactSheet", "Export Contact Sheet PDF", [], None, - "{path, ids?: photo ids (default selection), paper?: a4|letter, landscape?: bool, columns?: 1..8, rows?: 1..10, captions?: bool} → {path, pages, photos, bytes}; replaces an existing output, never an original", + "{path, ids?: photo ids (default selection), paper?: a4|letter, landscape?: bool, columns?: 1..8, rows?: 1..10, captions?: bool} → {path, pages, photos, bytes}; replaces an existing output, never an original; one activity row (✕ stops it between photos, and then no file is written); refused while another export is running", always, |s, p| { let path = p.get("path").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad("export.contactSheet", "missing path"))?; s.check_write_target(path).map_err(|e| bad("export.contactSheet", e))?; - let doc = crate::contact_sheet::prepare(s, p).and_then(|work| work.run(&mut |_, _| true)).map_err(|e| bad("export.contactSheet", e))?; + crate::export::ensure_none_running(&s.activity).map_err(|e| bad("export.contactSheet", e))?; + let doc = crate::contact_sheet::prepare(s, p).and_then(|work| work.run_with_row(&s.activity)).map_err(|e| bad("export.contactSheet", e))?; s.check_write_target(path).map_err(|e| bad("export.contactSheet", e))?; crate::export::write_file(path, &doc.bytes).map_err(|e| bad("export.contactSheet", e))?; Ok(json!({"path": path, "pages": doc.pages, "photos": doc.photos, "bytes": doc.bytes.len()})) @@ -266,7 +282,7 @@ pub fn specs() -> Vec { "Export with Several Presets", [], None, - "{presetIds: [export preset names, 1..32, distinct], ids?: photo ids (default: the selection), dir?: one folder for every preset (default: each preset's own), fallbackDir?: the folder for the presets that name none (the others keep theirs)} → {presets: [{preset, files}], photos, decodes, written, cancelled}; photo by photo, each decoded once and rendered with every preset; one activity row (✕ stops it between steps, the files written stay); every argument is checked before anything is written; no file of the run replaces another of the run (names compared ignoring case and Unicode form); a preset that adds to Apple Photos is refused", + "{presetIds: [export preset names, 1..32, distinct], ids?: photo ids (default: the selection), dir?: one folder for every preset (default: each preset's own), fallbackDir?: the folder for the presets that name none (the others keep theirs), pluginDestination?: {plugin, destination, args?}: a plug-in export destination that gets every file of every preset} → {presets: [{preset, files}], photos, decodes, written, cancelled, plugins?: [{plugin, destination?, ok | error}] (the enabled export hooks, then the destination)}; photo by photo, each decoded once and rendered with every preset; one activity row (✕ stops it between steps, the files written stay); refused while another export is running; afterwards the photos are marked exported and become Previous Export, and the plug-in export hooks run (not Export with Previous: a run has no single set of options to repeat); every argument is checked before anything is written; no file of the run replaces another of the run (names compared ignoring case and Unicode form); a preset that adds to Apple Photos is refused", always, |s, p| crate::run_presets::run_command(s, p).map_err(|e| bad("export.runPresets", e)) )); diff --git a/crates/engine/src/cmd/export_preset_files.rs b/crates/engine/src/cmd/export_preset_files.rs index 42b2e71b7a..4408ecaaac 100644 --- a/crates/engine/src/cmd/export_preset_files.rs +++ b/crates/engine/src/cmd/export_preset_files.rs @@ -4,14 +4,15 @@ //! //! Read from the formats' public structure (Lua's table syntax) and black-box observation of files //! the person exported; no other program's code. Settings with no counterpart here are reported by -//! name, never a reason to refuse the file. +//! name (every key of the preset nothing read, bar those of formats and switches the preset doesn't +//! use), never a reason to refuse the file. use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use super::metadata_files::{FreeNames, ext_of, stem_of, strings}; use super::{CommandSpec, always, bad, cmd, str_param}; -use crate::export::{ExportOptions, ExportPreset, builtin_presets, subfolder_problem}; +use crate::export::{ExportOptions, ExportPreset, LIMIT_KB_RANGE, OutputSpace, PPI_RANGE, START_NUMBER_RANGE, builtin_presets, subfolder_problem}; use crate::preset_import::{Lua, delocalize, parse_lua, read_zip}; use crate::{Result, Session}; @@ -38,6 +39,54 @@ pub struct Found { pub file: String, } +/// Most skipped presets or entries one file's report lists by name; the rest are counted in one line. +pub const MAX_SKIPPED_LISTED: usize = 100; + +/// The presets and zip entries a file held that were left out, each with its reason (FX-221): the +/// import reports them in `failed`, so a file whose presets were all refused does not look like +/// one that had nothing in it. +#[derive(Clone, Debug, Default)] +pub struct Skipped { + /// `(file or zip entry, reason)`, at most [`MAX_SKIPPED_LISTED`]. + pub listed: Vec<(String, String)>, + /// Those past the limit, not listed. + pub more: usize, +} + +impl Skipped { + fn add(&mut self, what: String, why: String) { + if self.listed.len() < MAX_SKIPPED_LISTED { + self.listed.push((what, why)); + } else { + self.more += 1; + } + } + + fn append(&mut self, other: Skipped) { + self.more += other.more; + for (what, why) in other.listed { + self.add(what, why); + } + } + + fn is_empty(&self) -> bool { + self.listed.is_empty() && self.more == 0 + } + + /// The `failed` rows `[file or entry, reason]`; `file` is named on the line that counts the rest. + fn rows(self, file: &str) -> Vec { + let more = (self.more > 0).then(|| json!([file, format!("and {} more export presets or entries were skipped (not listed)", self.more)])); + self.listed.into_iter().map(|(what, why)| json!([what, why])).chain(more).collect() + } +} + +/// What reading one file gave: the export presets in it and what it held that was left out. +#[derive(Clone, Debug, Default)] +pub struct Parsed { + pub found: Vec, + pub skipped: Skipped, +} + /// A Lightroom file-naming template (`{{image_name}}-{{naming_sequenceNumber_3Digits}}`) as ours /// (`{name}-{seq:3}`), with the tokens we have no counterpart for (left out). pub fn lr_naming(tokens: &str) -> (String, Vec) { @@ -126,8 +175,8 @@ pub fn lr_naming(tokens: &str) -> (String, Vec) { /// Look up an export preset key in `v`: Lightroom Classic `.lrtemplate` files on disk store keys /// without the `LR_` prefix (e.g. `format`, `jpeg_quality`, `size_doConstrain`, `collisionHandling`) /// or with `export_` (`export_colorSpace`, `export_bitDepth`, `export_destinationType`), while -/// SDK / publish templates prefix them with `LR_`. -fn lget<'a>(v: &'a Lua, k: &str) -> Option<&'a Lua> { +/// SDK / publish templates prefix them with `LR_`. Gives the key as the file spells it, too. +fn lfind<'a>(v: &'a Lua, k: &str) -> Option<(&'a str, &'a Lua)> { let base = k.strip_prefix("LR_").unwrap_or(k); let short = base.strip_prefix("export_").unwrap_or(base); let candidates = [ @@ -139,35 +188,34 @@ fn lget<'a>(v: &'a Lua, k: &str) -> Option<&'a Lua> { format!("export_{short}"), format!("LR_export_{short}"), ]; + let Lua::Table(_, m) = v else { return None }; for c in &candidates { - if let Some(found) = v.get(c) { - return Some(found); + if let Some((key, found)) = m.iter().find(|(key, _)| key == c) { + return Some((key, found)); } } - if let Lua::Table(_, m) = v { - for c in &candidates { - if let Some((_, found)) = m.iter().find(|(key, _)| key.eq_ignore_ascii_case(c)) { - return Some(found); - } + for c in &candidates { + if let Some((key, found)) = m.iter().find(|(key, _)| key.eq_ignore_ascii_case(c)) { + return Some((key, found)); } } None } -fn lstr<'a>(v: &'a Lua, k: &str) -> Option<&'a str> { - lget(v, k).and_then(Lua::str) +fn lget<'a>(v: &'a Lua, k: &str) -> Option<&'a Lua> { + lfind(v, k).map(|(_, found)| found) } -fn lnum(v: &Lua, k: &str) -> Option { - match lget(v, k)? { +fn num_of(v: &Lua) -> Option { + match v { Lua::Num(n) if n.is_finite() => Some(*n), Lua::Str(s) => s.trim().parse::().ok().filter(|n| n.is_finite()), _ => None, } } -fn lbool(v: &Lua, k: &str) -> Option { - match lget(v, k)? { +fn bool_of(v: &Lua) -> Option { + match v { Lua::Bool(b) => Some(*b), Lua::Num(n) => Some(*n != 0.0), Lua::Str(s) => match s.trim().to_ascii_lowercase().as_str() { @@ -179,17 +227,156 @@ fn lbool(v: &Lua, k: &str) -> Option { } } +/// The name two spellings of one Lightroom key share (`LR_export_colorSpace`, `export_colorSpace`, +/// `colorSpace`), lower-cased. +fn canon(key: &str) -> String { + let k = key.to_ascii_lowercase(); + let k = k.strip_prefix("lr_").unwrap_or(&k); + k.strip_prefix("export_").unwrap_or(k).to_string() +} + +/// Most settings with no counterpart here one preset's report names; the rest are counted. +pub const MAX_UNREAD_LISTED: usize = 50; + +/// What the report says of a Lightroom key that has no counterpart here and needs more than its +/// name said (keyed by [`canon`]). The person-name settings are privacy settings: the files may +/// carry names the preset meant to leave out. +const UNREAD_NOTES: &[(&str, &str)] = &[ + ( + "includefacetagsaskeywords", + "person names as keywords: not carried over; turn on Remove Person Info in the Export dialog to keep names out of the files", + ), + ( + "includefacetagsiniptc", + "person names in IPTC: not carried over; turn on Remove Person Info in the Export dialog to keep names out of the files", + ), +]; + +/// A Lightroom preset's settings table that remembers which keys were looked at, so the keys +/// nothing looked at can be reported by name (FX-222) instead of dropped. +struct Src<'a> { + v: &'a Lua, + /// [`canon`] of every key read. + read: std::cell::RefCell>, + /// Keys that don't apply to this preset (another format's, a switch that is off): not reported. + quiet: std::cell::RefCell>, +} + +impl<'a> Src<'a> { + fn new(v: &'a Lua) -> Self { + Src { v, read: Default::default(), quiet: Default::default() } + } + + fn get(&self, k: &str) -> Option<&'a Lua> { + let (key, found) = lfind(self.v, k)?; + self.read.borrow_mut().insert(canon(key)); + Some(found) + } + + fn str(&self, k: &str) -> Option<&'a str> { + self.get(k).and_then(Lua::str) + } + + fn num(&self, k: &str) -> Option { + num_of(self.get(k)?) + } + + fn bool(&self, k: &str) -> Option { + bool_of(self.get(k)?) + } + + /// These keys, which this preset's other settings make irrelevant, are not reported. + fn quiet(&self, keys: &[&str]) { + self.quiet.borrow_mut().extend(keys.iter().map(|k| canon(k))); + } + + /// Every key starting with `prefix` (after [`canon`]) is not reported. + fn quiet_prefix(&self, prefix: &str) { + self.quiet.borrow_mut().push(format!("{prefix}*")); + } + + /// The report rows for the settings nothing read: `(key as the file spells it, row)`, in file + /// order, a key once however it is spelled, and how many there are in all. + fn unread(&self) -> (Vec, usize) { + let Lua::Table(items, fields) = self.v else { return (Vec::new(), 0) }; + let read = self.read.borrow(); + let quiet = self.quiet.borrow(); + let silent = |c: &str| { + quiet.iter().any(|q| match q.strip_suffix('*') { + Some(prefix) => c.starts_with(prefix), + None => q == c, + }) + }; + let mut seen = std::collections::HashSet::new(); + let mut rows = Vec::new(); + let mut total = 0; + for (key, value) in fields { + let c = canon(key); + if matches!(value, Lua::Nil) || read.contains(&c) || silent(&c) || !seen.insert(c.clone()) { + continue; + } + total += 1; + if rows.len() < MAX_UNREAD_LISTED { + let name: String = key.chars().take(64).collect(); + let what = match UNREAD_NOTES.iter().find(|(k, _)| *k == c) { + Some((_, note)) => (*note).to_string(), + None => "no counterpart here".to_string(), + }; + let value = match value { + Lua::Bool(b) => format!(" = {b}"), + Lua::Num(n) if n.is_finite() => format!(" = {n}"), + _ => String::new(), + }; + rows.push(format!("setting `{name}`{value} ({what})")); + } + } + if !items.is_empty() { + total += 1; + if rows.len() < MAX_UNREAD_LISTED { + rows.push(format!("{} unnamed entries in the settings (no counterpart here)", items.len())); + } + } + (rows, total) + } +} + +/// The colour space a Lightroom Classic preset names: the spellings only Lightroom uses, then +/// whatever [`OutputSpace::parse`] takes, so a name the exporter accepts is never reported as +/// unknown here (FX-223). +fn lr_color_space(name: &str) -> Option { + // Lightroom-only spellings, as `parse` reads names: letters and digits, lower case + let key: String = name.chars().filter(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase(); + match key.as_str() { + "srgbiec6196621" => Some(OutputSpace::Srgb), + "p3d65" => Some(OutputSpace::DisplayP3), + "hdrrec2020" => Some(OutputSpace::Rec2020), + _ => OutputSpace::parse(name), + } +} + +/// A colour space as the export parameter `colorSpace` names it. +fn color_space_param(space: OutputSpace) -> &'static str { + match space { + OutputSpace::Srgb => "srgb", + OutputSpace::DisplayP3 => "displayP3", + OutputSpace::AdobeRgb => "adobeRgb", + OutputSpace::ProPhoto => "proPhoto", + OutputSpace::Rec2020 => "rec2020", + } +} + /// The settings of a Lightroom Classic export preset's `value` table as `app.export` params, with /// what couldn't be carried over. pub fn lr_export_params(v: &Lua) -> (Map, Vec) { + let src = &Src::new(v); let mut o = Map::new(); let mut unmapped: Vec = Vec::new(); // ---- where to - if let Some(service) = lstr(v, "exportServiceProvider").filter(|s| !s.eq_ignore_ascii_case("com.adobe.ag.export.file")) { + if let Some(service) = src.str("exportServiceProvider").filter(|s| !s.eq_ignore_ascii_case("com.adobe.ag.export.file")) { unmapped.push(format!("export service `{service}` (exported to files instead)")); } - let folder = lstr(v, "export_destinationPathPrefix").map(str::trim).filter(|p| !p.is_empty()); - match lstr(v, "export_destinationType").map(str::to_ascii_lowercase).as_deref() { + let folder = src.str("export_destinationPathPrefix").map(str::trim).filter(|p| !p.is_empty()); + match src.str("export_destinationType").map(str::to_ascii_lowercase).as_deref() { Some("sourcefolder" | "sameasoriginal") => { o.insert("destinationMode".into(), json!("sameAsOriginal")); } @@ -207,11 +394,14 @@ pub fn lr_export_params(v: &Lua) -> (Map, Vec) { } Some(other) => unmapped.push(format!("destination `{other}` (choose the folder in the Export dialog)")), } - if lbool(v, "export_useParentFolder") == Some(true) { + if src.bool("export_useParentFolder") == Some(true) { unmapped.push("put in parent folder".into()); } - if lbool(v, "export_useSubfolder") == Some(true) - && let Some(sub) = lstr(v, "export_destinationPathSuffix").map(str::trim).filter(|s| !s.is_empty()) + if src.bool("export_useSubfolder") != Some(true) { + src.quiet(&["export_destinationPathSuffix"]); + } + if src.bool("export_useSubfolder") == Some(true) + && let Some(sub) = src.str("export_destinationPathSuffix").map(str::trim).filter(|s| !s.is_empty()) { match subfolder_problem(sub) { None => { @@ -220,7 +410,7 @@ pub fn lr_export_params(v: &Lua) -> (Map, Vec) { Some(why) => unmapped.push(format!("subfolder `{sub}` ({why})")), } } - match lstr(v, "export_collisionHandling").map(str::to_ascii_lowercase).as_deref() { + match src.str("export_collisionHandling").map(str::to_ascii_lowercase).as_deref() { Some("overwrite" | "overwritewithoutwarning") => { o.insert("conflict".into(), json!("overwrite")); } @@ -231,33 +421,39 @@ pub fn lr_export_params(v: &Lua) -> (Map, Vec) { Some(other) => unmapped.push(format!("existing files `{other}`")), } // ---- file naming - if lbool(v, "renamingTokensOn") == Some(true) { + // the archived form of the tokens says what `tokens` does + src.quiet(&["tokensArchivedToString2"]); + if src.bool("renamingTokensOn") != Some(true) { + src.quiet(&["tokens", "tokenCustomString", "initialSequenceNumber"]); + } + if src.bool("renamingTokensOn") == Some(true) { let tokens = - lstr(v, "tokens").filter(|t| !t.trim().is_empty()).or_else(|| lstr(v, "tokensArchivedToString2").filter(|t| !t.trim().is_empty())); + src.str("tokens").filter(|t| !t.trim().is_empty()).or_else(|| src.str("tokensArchivedToString2").filter(|t| !t.trim().is_empty())); if let Some(tokens) = tokens { let (naming, unknown) = lr_naming(tokens); o.insert("naming".into(), json!(naming)); unmapped.extend(unknown.into_iter().map(|t| format!("file name token `{t}`"))); } - if let Some(c) = lstr(v, "tokenCustomString") { + if let Some(c) = src.str("tokenCustomString") { o.insert("customText".into(), json!(c)); } - if let Some(n) = lnum(v, "initialSequenceNumber").filter(|n| (0.0..=999_999.0).contains(n)) { + if let Some(n) = src.num("initialSequenceNumber").filter(|n| (f64::from(START_NUMBER_RANGE.0)..=f64::from(START_NUMBER_RANGE.1)).contains(n)) + { o.insert("startNumber".into(), json!(n.round() as i64)); } } - if lstr(v, "extensionCase").is_some_and(|c| c.eq_ignore_ascii_case("uppercase") || c.eq_ignore_ascii_case("ucase")) { + if src.str("extensionCase").is_some_and(|c| c.eq_ignore_ascii_case("uppercase") || c.eq_ignore_ascii_case("ucase")) { unmapped.push("uppercase file extension (lowercase written instead)".into()); } // ---- file settings - let format = lstr(v, "format").unwrap_or("JPEG"); + let format = src.str("format").unwrap_or("JPEG"); let ours = match format.trim().to_ascii_uppercase().as_str() { "JPEG" | "JPG" => Some("jpeg"), "TIFF" | "TIF" => Some("tiff"), "PSD" => Some("psd"), "PNG" => Some("png"), "DNG" => { - if lstr(v, "dng_conversionMethod").is_some_and(|m| m.eq_ignore_ascii_case("convertToLinear")) { + if src.str("dng_conversionMethod").is_some_and(|m| m.eq_ignore_ascii_case("convertToLinear")) { Some("renderedDng") } else { Some("dng") @@ -275,45 +471,53 @@ pub fn lr_export_params(v: &Lua) -> (Map, Vec) { } None => unmapped.push(format!("format `{format}` (JPEG instead)")), } + // Lightroom stores every format's settings in each preset: those of the formats not chosen are + // not about this preset (a format we don't know leaves them all to be reported) + if let Some(ours) = ours { + let own = match ours { + "renderedDng" => "dng", + "original" => "", + f => f, + }; + for other in ["jpeg", "tiff", "psd", "png", "dng", "jxl", "avif", "heic", "webp"] { + if other != own { + src.quiet_prefix(&format!("{other}_")); + } + } + } let quality_keys: &[&str] = match ours { Some("avif") => &["avif_quality", "jpeg_quality", "jxl_quality", "heic_quality", "quality"], Some("jxl") => &["jxl_quality", "jpeg_quality", "avif_quality", "heic_quality", "quality"], _ => &["jpeg_quality", "avif_quality", "jxl_quality", "heic_quality", "quality"], }; - let quality = quality_keys.iter().find_map(|k| lnum(v, k)); + let quality = quality_keys.iter().find_map(|k| src.num(k)); + // the other formats' quality settings, which Lightroom stores in every preset + src.quiet(quality_keys); if let Some(q) = quality.filter(|q| *q >= 0.0) { // 0..1 in Lightroom; tolerate 0..100 let q = if q <= 1.0 { q * 100.0 } else { q }; o.insert("quality".into(), json!(q.round().clamp(1.0, 100.0) as i64)); } - if lbool(v, "jpeg_useLimitSize") == Some(true) - && let Some(kb) = lnum(v, "jpeg_limitSize").filter(|k| *k >= 1.0 && *k <= u32::MAX as f64) + if src.bool("jpeg_useLimitSize") != Some(true) { + src.quiet(&["jpeg_limitSize"]); + } + if src.bool("jpeg_useLimitSize") == Some(true) + && let Some(kb) = src.num("jpeg_limitSize").filter(|k| *k >= 1.0 && *k <= f64::from(LIMIT_KB_RANGE.1)) { o.insert("limitKb".into(), json!(kb.round() as i64)); } - match lstr(v, "export_colorSpace").map(|s| s.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "")).as_deref() { - Some("srgb" | "srgbiec6196621") => { - o.insert("colorSpace".into(), json!("srgb")); - } - Some("adobergb" | "adobergb1998") => { - o.insert("colorSpace".into(), json!("adobeRgb")); - } - Some("prophotorgb" | "prophoto") => { - o.insert("colorSpace".into(), json!("proPhoto")); - } - Some("displayp3" | "p3" | "p3d65") => { - o.insert("colorSpace".into(), json!("displayP3")); - } - Some("rec2020" | "hdrrec2020" | "bt2020") => { - o.insert("colorSpace".into(), json!("rec2020")); + if let Some(space) = src.str("export_colorSpace") { + match lr_color_space(space) { + Some(ours) => { + o.insert("colorSpace".into(), json!(color_space_param(ours))); + } + None => unmapped.push(format!("colour space `{}` (sRGB instead)", space.chars().take(64).collect::())), } - None => {} - Some(other) => unmapped.push(format!("colour space `{other}` (sRGB instead)")), } - if let Some(b) = lnum(v, "export_bitDepth").map(|b| b.round() as i64).filter(|b| matches!(b, 8 | 10 | 16 | 32)) { + if let Some(b) = src.num("export_bitDepth").map(|b| b.round() as i64).filter(|b| matches!(b, 8 | 10 | 16 | 32)) { o.insert("bitDepth".into(), json!(b)); } - match lstr(v, "tiff_compressionMethod").map(str::to_ascii_lowercase).as_deref() { + match src.str("tiff_compressionMethod").map(str::to_ascii_lowercase).as_deref() { Some(m) if m.ends_with("none") => { o.insert("tiffCompression".into(), json!("none")); } @@ -326,36 +530,41 @@ pub fn lr_export_params(v: &Lua) -> (Map, Vec) { _ => {} } if ours == Some("dng") { - if lbool(v, "dng_lossyCompression") == Some(true) { + if src.bool("dng_lossyCompression") == Some(true) { o.insert("dngCompression".into(), json!("lossy")); - } else if lbool(v, "dng_compressed") == Some(false) { + } else if src.bool("dng_compressed") == Some(false) { o.insert("dngCompression".into(), json!("uncompressed")); - } else if lbool(v, "dng_compressed") == Some(true) { + } else if src.bool("dng_compressed") == Some(true) { o.insert("dngCompression".into(), json!("lossless")); } - if lbool(v, "dng_embedRAW") == Some(true) { + if src.bool("dng_embedRAW") == Some(true) { unmapped.push("embed original raw file in DNG".into()); } } - if lbool(v, "hdrOutput") == Some(true) { + if src.bool("hdrOutput") == Some(true) { o.insert("hdr".into(), json!(true)); } - if lbool(v, "jxl_lossless") == Some(true) { + if src.bool("jxl_lossless") == Some(true) { o.insert("jxlLossless".into(), json!(true)); } // ---- image sizing: pixels from the units and resolution - let res = lnum(v, "size_resolution").filter(|r| *r > 0.0 && *r < 1.0e6); - let per_cm = lstr(v, "size_resolutionUnits").is_some_and(|u| { + let res = src.num("size_resolution").filter(|r| *r > 0.0 && *r < 1.0e6); + let per_cm = src.str("size_resolutionUnits").is_some_and(|u| { let u = u.to_ascii_lowercase(); u.starts_with("cm") || u == "centimeters" || u == "pixelspercentimeter" || u == "ppc" }); let ppi = res.map(|r| if per_cm { r * 2.54 } else { r }); if let Some(p) = ppi { - o.insert("ppi".into(), json!(p.round().clamp(1.0, u16::MAX as f64) as i64)); + o.insert("ppi".into(), json!(p.round().clamp(f64::from(PPI_RANGE.0), f64::from(PPI_RANGE.1)) as i64)); + } + let constrain = src.bool("size_doConstrain").or_else(|| src.bool("size_userWantsConstrain")); + // the other spelling of the switch, and the sizes of the kinds of resizing not asked for + src.quiet(&["size_userWantsConstrain", "size_dimension", "size_megapixels", "size_percentage"]); + if constrain != Some(true) { + src.quiet(&["size_units", "size_maxWidth", "size_maxHeight", "size_resizeType", "size_doNotEnlarge"]); } - let constrain = lbool(v, "size_doConstrain").or_else(|| lbool(v, "size_userWantsConstrain")); if constrain == Some(true) { - let units = lstr(v, "size_units").map(str::to_ascii_lowercase).unwrap_or_else(|| "pixels".into()); + let units = src.str("size_units").map(str::to_ascii_lowercase).unwrap_or_else(|| "pixels".into()); let px = |n: f64| -> f64 { let r = ppi.unwrap_or(240.0); match units.as_str() { @@ -364,10 +573,10 @@ pub fn lr_export_params(v: &Lua) -> (Map, Vec) { _ => n, } }; - let w = lnum(v, "size_maxWidth").or_else(|| lnum(v, "size_dimension")).filter(|n| *n > 0.0).map(px); - let h = lnum(v, "size_maxHeight").or_else(|| lnum(v, "size_dimension")).filter(|n| *n > 0.0).map(px); + let w = src.num("size_maxWidth").or_else(|| src.num("size_dimension")).filter(|n| *n > 0.0).map(px); + let h = src.num("size_maxHeight").or_else(|| src.num("size_dimension")).filter(|n| *n > 0.0).map(px); let whole = |n: f64| json!(n.round().clamp(1.0, 1.0e6) as i64); - match lstr(v, "size_resizeType").map(str::to_ascii_lowercase).as_deref() { + match src.str("size_resizeType").map(str::to_ascii_lowercase).as_deref() { Some("longedge" | "long" | "l") => { if let Some(n) = w.into_iter().chain(h).reduce(f64::max) { o.insert("longEdge".into(), whole(n)); @@ -389,12 +598,12 @@ pub fn lr_export_params(v: &Lua) -> (Map, Vec) { } } Some("megapixels" | "mp") => { - if let Some(mp) = lnum(v, "size_megapixels").filter(|m| *m > 0.0 && *m < 1.0e4) { + if let Some(mp) = src.num("size_megapixels").filter(|m| *m > 0.0 && *m < 1.0e4) { o.insert("megapixels".into(), json!(mp)); } } Some("percentage" | "percent" | "pct") => { - if let Some(pc) = lnum(v, "size_percentage").filter(|m| *m > 0.0 && *m <= 1.0e4) { + if let Some(pc) = src.num("size_percentage").filter(|m| *m > 0.0 && *m <= 1.0e4) { o.insert("percent".into(), json!(pc)); } } @@ -429,37 +638,40 @@ pub fn lr_export_params(v: &Lua) -> (Map, Vec) { }, Some(other) => unmapped.push(format!("resize to `{other}` (full size instead)")), } - if let Some(b) = lbool(v, "size_doNotEnlarge") { + if let Some(b) = src.bool("size_doNotEnlarge") { o.insert("dontEnlarge".into(), json!(b)); } - } else if constrain == Some(false) || lstr(v, "format").is_some() { + } else if constrain == Some(false) || src.str("format").is_some() { o.insert("longEdge".into(), json!(0)); // full size } // ---- output sharpening - if lbool(v, "outputSharpeningOn") == Some(true) { - let media = lstr(v, "outputSharpeningMedia").map(str::to_ascii_lowercase).unwrap_or_else(|| "screen".into()); + if src.bool("outputSharpeningOn") != Some(true) { + src.quiet(&["outputSharpeningMedia", "outputSharpeningLevel"]); + } + if src.bool("outputSharpeningOn") == Some(true) { + let media = src.str("outputSharpeningMedia").map(str::to_ascii_lowercase).unwrap_or_else(|| "screen".into()); let media = match media.as_str() { "matte" | "mattepaper" | "matte_paper" => "matte", "glossy" | "glossypaper" | "glossy_paper" => "glossy", _ => "screen", }; o.insert("sharpen".into(), json!(media)); - let level = match lnum(v, "outputSharpeningLevel").map(|l| l.round() as i64) { + let level = match src.num("outputSharpeningLevel").map(|l| l.round() as i64) { Some(1) => "low", Some(3) => "high", Some(_) => "standard", - None => match lstr(v, "outputSharpeningLevel").map(str::to_ascii_lowercase).as_deref() { + None => match src.str("outputSharpeningLevel").map(str::to_ascii_lowercase).as_deref() { Some("low") => "low", Some("high") => "high", _ => "standard", }, }; o.insert("sharpenAmount".into(), json!(level)); - } else if lbool(v, "outputSharpeningOn") == Some(false) { + } else if src.bool("outputSharpeningOn") == Some(false) { o.insert("sharpen".into(), json!("none")); } // ---- metadata - let policy = lstr(v, "embeddedMetadataOption").map(|s| s.to_ascii_lowercase()); + let policy = src.str("embeddedMetadataOption").map(|s| s.to_ascii_lowercase()); match policy.as_deref() { Some("all") => { o.insert("metadata".into(), json!("all")); @@ -481,61 +693,74 @@ pub fn lr_export_params(v: &Lua) -> (Map, Vec) { o.insert("metadata".into(), json!("none")); unmapped.push(format!("metadata `{other}` (not known: no metadata is embedded; choose a setting in the Export dialog)")); } - None if lget(v, "embeddedMetadataOption").is_some() => { + None if src.get("embeddedMetadataOption").is_some() => { o.insert("metadata".into(), json!("none")); unmapped.push("metadata (not readable: no metadata is embedded; choose a setting in the Export dialog)".into()); } None => {} } - if lbool(v, "minimizeEmbeddedMetadata") == Some(true) + if src.bool("minimizeEmbeddedMetadata") == Some(true) && !matches!(policy.as_deref(), Some("copyrightonly" | "copyright" | "copyrightandcontactonly" | "copyrightandcontact" | "none")) { o.insert("metadata".into(), json!("copyright")); } - match lbool(v, "removeLocationMetadata") { + match src.bool("removeLocationMetadata") { Some(b) => { o.insert("removeLocation".into(), json!(b)); } // stated but not readable as on or off: location is removed, and the report says so (FX-184) - None if lget(v, "removeLocationMetadata").is_some() => { + None if src.get("removeLocationMetadata").is_some() => { o.insert("removeLocation".into(), json!(true)); unmapped.push("remove location info (not readable as on or off: location is removed)".into()); } None => {} } // ---- what the app can't do (reported when it is on) - if lbool(v, "useWatermark") == Some(true) { + if src.bool("useWatermark") == Some(true) { unmapped.push("watermark (pick one in the Export dialog)".into()); } - if matches!(lget(v, "exportFiltersFromPlugins"), Some(Lua::Table(a, m)) if !a.is_empty() || !m.is_empty()) { + // the watermark's id is said by that row, or means nothing with the watermark off + if src.get("useWatermark").is_some() { + src.quiet_prefix("watermark"); + } + if matches!(src.get("exportFiltersFromPlugins"), Some(Lua::Table(a, m)) if !a.is_empty() || !m.is_empty()) { unmapped.push("post-processing plug-in actions".into()); } - if lstr(v, "export_postProcessing") + if src + .str("export_postProcessing") .map(str::trim) .filter(|p| !p.is_empty()) .is_some_and(|p| !p.eq_ignore_ascii_case("doNothing") && !p.eq_ignore_ascii_case("none")) { unmapped.push("after export action".into()); } - if lbool(v, "reimportExportedPhoto") == Some(true) { + if src.bool("reimportExportedPhoto") == Some(true) { unmapped.push("add to this catalog".into()); } // Remove Person Info: person keywords stay out of the files (FX-142); with it off they go out // as keywords, but face regions are never written - match lbool(v, "removeFaceMetadata") { + match src.bool("removeFaceMetadata") { Some(true) => { o.insert("removePersonInfo".into(), json!(true)); } Some(false) => unmapped.push("person info (face regions are never written)".into()), - None if lget(v, "removeFaceMetadata").is_some() => { + None if src.get("removeFaceMetadata").is_some() => { o.insert("removePersonInfo".into(), json!(true)); unmapped.push("remove person info (not readable as on or off: person info is removed)".into()); } None => {} } - if lbool(v, "includeVideoFiles") == Some(false) || lstr(v, "export_videoFileHandling").is_some_and(|s| s.eq_ignore_ascii_case("exclude")) { + let no_videos = src.bool("includeVideoFiles") == Some(false); + if src.str("export_videoFileHandling").is_some_and(|s| s.eq_ignore_ascii_case("exclude")) || no_videos { unmapped.push("exclude video files".into()); } + // every setting nothing above looked at is named (FX-222): the person-name privacy settings + // among them say what they were for + let (rest, total) = src.unread(); + unmapped.extend(rest.iter().cloned()); + if total > rest.len() { + unmapped.push(format!("and {} more settings with no counterpart here (not listed)", total - rest.len())); + } let mut params = Value::Object(o); // Lightroom Classic stores `export_bitDepth = 16` in the table even when `format = "JPEG"` ExportOptions::drop_unfit_depth(&mut params, Default::default()); @@ -585,67 +810,95 @@ fn from_lrtemplate(file: &str, text: &str) -> Option Option, String>> { +/// the exporter would refuse is skipped, and said so with its reason (FX-221). +fn from_native(file: &str, text: &str) -> Option> { let v: Value = serde_json::from_str(text).ok()?; if v.get("format").and_then(Value::as_str) != Some(FILE_FORMAT) { return None; } let Some(list) = v.get("presets").and_then(Value::as_array) else { return Some(Err("no `presets` list".into())) }; - let mut out = Vec::new(); - for p in list.iter().take(MAX_PRESETS) { - let Some(name) = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) else { continue }; - let Some(raw) = p.get("params").filter(|x| x.is_object()) else { continue }; + let mut out = Parsed::default(); + // one more than the import's cap is read, enough for [`gather`] to say the rest were left out + for (i, p) in list.iter().enumerate().take(MAX_PRESETS + 1) { + let label = |name: Option<&str>| match name { + Some(n) => format!("preset `{}`", n.chars().take(64).collect::()), + None => format!("preset {} in the file", i + 1), + }; + let Some(name) = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) else { + out.skipped.add(file.to_string(), format!("{}: skipped, it has no name", label(None))); + continue; + }; + let Some(raw) = p.get("params").filter(|x| x.is_object()) else { + out.skipped.add(file.to_string(), format!("{}: skipped, its settings (`params`) are missing or not an object", label(Some(name)))); + continue; + }; let params = ExportOptions::known_keys_only(raw); - let mut unmapped: Vec = raw.as_object().into_iter().flatten().map(|(k, _)| k.clone()).filter(|k| params.get(k).is_none()).collect(); + let unmapped: Vec = raw.as_object().into_iter().flatten().map(|(k, _)| k.clone()).filter(|k| params.get(k).is_none()).collect(); let mut params = params; if let Some(o) = params.as_object_mut() { o.retain(|k, _| !matches!(k.as_str(), "ids" | "id" | "path" | "preset" | "background" | "pluginDestination")); } if let Err(e) = ExportOptions::validate("export.importPresets", ¶ms) { - unmapped.push(format!("preset skipped: {e}")); + out.skipped.add(file.to_string(), format!("{}: skipped, the exporter would refuse it: {e}", label(Some(name)))); continue; } - out.push(Found { + out.found.push(Found { preset: ExportPreset { name: name.chars().take(256).collect(), params, unmapped: unmapped.clone() }, unmapped, file: file.to_string(), }); } + if list.len() > MAX_PRESETS + 1 { + out.skipped.add(file.to_string(), format!("only the first {} presets of this file were read", MAX_PRESETS + 1)); + } + if list.is_empty() { + out.skipped.add(file.to_string(), "the file lists no export presets".into()); + } Some(Ok(out)) } -/// The export presets in file `file` (`bytes`), or `None` when it holds none. Zips are looked -/// into (one level). -pub fn parse_bytes(file: &str, bytes: &[u8]) -> Option, String>> { +/// The export presets in file `file` (`bytes`) and what was left out, or `None` when it holds +/// none of either. Zips are looked into (one level). +pub fn parse_bytes(file: &str, bytes: &[u8]) -> Option> { let text = || String::from_utf8_lossy(bytes).trim_start_matches('\u{feff}').to_string(); match ext_of(file).as_str() { - "lrtemplate" => from_lrtemplate(file, &text()).map(|r| r.map(|f| vec![f])), + "lrtemplate" => from_lrtemplate(file, &text()).map(|r| r.map(|f| Parsed { found: vec![f], skipped: Skipped::default() })), "zip" => { let entries = read_zip(bytes).ok()?; - let mut out = Vec::new(); + let mut out = Parsed::default(); for (inner, data) in entries { // past the import's cap nothing more is added: one more than it is enough for [`gather`] to say so - if out.len() > MAX_PRESETS { + if out.found.len() > MAX_PRESETS { break; } + let at = format!("{file}/{inner}"); if ext_of(&inner) == "zip" { + out.skipped.add(at, "a zip inside a zip: export presets in it are not read".into()); continue; } - if let Some(Ok(list)) = parse_bytes(&format!("{file}/{inner}"), &data) { - out.extend(list); + match parse_bytes(&at, &data) { + Some(Ok(p)) => { + out.found.extend(p.found); + out.skipped.append(p.skipped); + } + Some(Err(e)) => out.skipped.add(at, e), + // not an export preset: a develop preset or another file of the bundle + None => {} } } - (!out.is_empty()).then_some(Ok(out)) + (!out.found.is_empty() || !out.skipped.is_empty()).then_some(Ok(out)) } e if e == EXPORT_PRESET_EXT || e == "json" => from_native(file, &text()), _ => None, } } -/// Add the presets of `list` (found in `file`) to `found`, at most [`MAX_PRESETS`] in all; those -/// past it are left out, with a line in `failed` saying so. -pub(crate) fn gather(found: &mut Vec, list: Vec, file: &str, failed: &mut Vec) { +/// Add the presets of `parsed` (found in `file`) to `found`, at most [`MAX_PRESETS`] in all; those +/// past it are left out, with a line in `failed` saying so. What the file held that was skipped +/// goes to `failed` too, each with its reason (FX-221). +pub(crate) fn gather(found: &mut Vec, parsed: Parsed, file: &str, failed: &mut Vec) { + let Parsed { found: list, skipped } = parsed; + failed.extend(skipped.rows(file)); let room = MAX_PRESETS.saturating_sub(found.len()); if list.len() > room { failed.push(json!([file, format!("one import adds at most {MAX_PRESETS} export presets: the rest of this file's were not imported")])); @@ -698,7 +951,7 @@ fn import(s: &mut Session, p: &Value) -> Result { } }; match parse_bytes(&f, &bytes) { - Some(Ok(list)) => gather(&mut found, list, &f, &mut failed), + Some(Ok(parsed)) => gather(&mut found, parsed, &f, &mut failed), Some(Err(e)) => failed.push(json!([f, e])), None => failed.push(json!([f, "not an export preset"])), } diff --git a/crates/engine/src/cmd/facets.rs b/crates/engine/src/cmd/facets.rs index 0a4af3f4e3..5d86ae03fb 100644 --- a/crates/engine/src/cmd/facets.rs +++ b/crates/engine/src/cmd/facets.rs @@ -58,6 +58,8 @@ fn without(field: &str, f: &Filter) -> Filter { f.date = None; f.date_from = None; f.date_to = None; + f.capture_month_day = None; + f.capture_before_year = None; } // the fields picked through `Filter::facets` only; the search text (`iso:>800`) stays _ => {} diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index e562083b50..364ccc3a71 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -586,7 +586,7 @@ fn step(s: &mut Session, d: isize) -> Result { } /// ↑ / ↓ (`library.up` / `library.down`): a step with no photo active takes the view's last photo for a downward step -/// and its first for an upward one (F-66C0), whatever the row distance. +/// and its first for an upward one, whatever the row distance. fn step_vertical(s: &mut Session, d: isize) -> Result { step_from(s, d, false, d > 0) } @@ -744,6 +744,124 @@ fn flip(s: &mut Session, p: &Value, horizontal: bool) -> Result { Ok(json!({"changed": n})) } +/// A list parameter of `photo.setMeta`: an array of strings, or a comma-separated string (the metadata +/// panel's single text field). +fn meta_strs(p: &Value, k: &str) -> Option> { + p.get(k).and_then(|v| match v { + Value::Array(a) => Some(a.iter().filter_map(Value::as_str).map(str::to_string).collect::>()), + // a comma-separated string (the metadata panel's single text field) + Value::String(t) => Some(t.split(',').map(|s| s.trim().to_string()).collect()), + _ => None, + }) +} + +/// What `photo.setMeta` reads once for every photo: the GPS change and the copyright status. +pub(crate) type MetaEditArgs = (Option>, Option); + +/// Reads the GPS and copyright status of a `photo.setMeta` call, failing before any photo is edited. +pub(crate) fn meta_edit_args(p: &Value) -> Result { + // GPS: "lat, lon" (decimal or 51°30'26"N 0°7'39"W), [lat, lon], or null / "" to clear + let gps: Option> = match p.get("gps") { + None => None, + Some(Value::Null) => Some(None), + Some(Value::String(t)) if t.trim().is_empty() => Some(None), + Some(Value::String(t)) => { + Some(Some(parse_gps(t).ok_or_else(|| bad("photo.setMeta", format!("can't read `{t}` as coordinates (e.g. 51.5072, -0.1276)")))?)) + } + Some(Value::Array(a)) if a.len() == 2 => match (a[0].as_f64(), a[1].as_f64()) { + (Some(la), Some(lo)) if la.abs() <= 90.0 && lo.abs() <= 180.0 => Some(Some((la, lo))), + _ => return Err(bad("photo.setMeta", "gps is [latitude, longitude] in degrees")), + }, + Some(_) => return Err(bad("photo.setMeta", "gps is \"lat, lon\", [lat, lon] or null")), + }; + let status = match str_param(p, "copyrightStatus") { + Some(t) => Some( + CopyrightStatus::parse(t).ok_or_else(|| bad("photo.setMeta", format!("copyrightStatus `{t}`: unknown, copyrighted or publicDomain")))?, + ), + None => None, + }; + Ok((gps, status)) +} + +/// Applies the fields of a `photo.setMeta` call `p` to `m` (what [`meta_edit_args`] read from it passed in). +pub(crate) fn edit_meta(m: &mut lcc_catalog::Meta, p: &Value, (gps, status): MetaEditArgs) { + let strs = |k: &str| meta_strs(p, k); + if let Some(g) = gps { + m.gps = g; + } + if let Some(st) = status { + m.copyright_status = st; + } + for (k, field) in [ + ("title", &mut m.title), + ("headline", &mut m.headline), + ("caption", &mut m.caption), + ("descriptionWriter", &mut m.description_writer), + ("category", &mut m.category), + ("copyright", &mut m.copyright), + ("usageTerms", &mut m.usage_terms), + ("copyrightUrl", &mut m.copyright_url), + ("creator", &mut m.creator), + ("location", &mut m.location), + ("city", &mut m.city), + ("state", &mut m.state), + ("country", &mut m.country), + ("countryCode", &mut m.country_code), + ("altText", &mut m.alt_text), + ("extendedDescription", &mut m.extended_description), + ] { + if let Some(v) = str_param(p, k) { + *field = v.to_string(); + } + } + for k in lcc_meta::CreatorContact::KEYS { + if let (Some(v), Some(field)) = (str_param(p, k), m.contact.get_mut(k)) { + *field = v.to_string(); + } + } + // keywords are stored cleaned (`a | b ` is `a|b`), each once whatever its case + use lcc_catalog::keywords::clean; + // (a set of the lower-cased keywords keeps this linear however many are supplied; upstream #3709) + let mut seen: std::collections::HashSet = m.keywords.iter().map(|x| x.to_lowercase()).collect(); + let add = |m: &mut lcc_catalog::Meta, seen: &mut std::collections::HashSet, k: &str| { + let k = clean(k); + if !k.is_empty() && seen.insert(k.to_lowercase()) { + m.keywords.push(k); + } + }; + if let Some(k) = strs("keywords") { + m.keywords.clear(); + seen.clear(); + for k in k { + add(m, &mut seen, &k); + } + } + for k in strs("addKeywords").unwrap_or_default() { + add(m, &mut seen, &k); + } + let removed: std::collections::HashSet = strs("removeKeywords").unwrap_or_default().iter().map(|k| clean(k).to_lowercase()).collect(); + if !removed.is_empty() { + m.keywords.retain(|x| !removed.contains(&clean(x).to_lowercase())); + } + // supplemental categories and subject codes: a list, each once (the UI edits + // them as one comma-separated text field, so trimming empty entries matters) + let distinct = |v: Vec| { + let mut out: Vec = Vec::new(); + for s in v { + if !s.is_empty() && !out.contains(&s) { + out.push(s); + } + } + out + }; + if let Some(v) = strs("supplementalCategories") { + m.supplemental_categories = distinct(v); + } + if let Some(v) = strs("subjectCode") { + m.subject_code = distinct(v); + } +} + /// The active photo's metadata as `photo.copyMetadata` gives it (and `photo.setMeta` takes it). fn active_meta(s: &Session, c: &str) -> Result { let id = s.active().ok_or_else(|| bad(c, "no active photo"))?; @@ -831,6 +949,21 @@ pub(crate) fn today_month_day(s: &Session) -> String { s.clock.as_ref()().get(5..10).filter(|day| valid_memories_day(day)).unwrap_or("01-01").to_string() } +/// The Memories fields of a filter set by a command (`library.filter`, a smart collection's +/// rules): a day that can't match, or a year without a day, is an error, not an empty view. +pub(crate) fn check_memories_fields(f: &Filter) -> Result<()> { + if f.capture_month_day.as_deref().is_some_and(|day| !valid_memories_day(day)) { + return Err(bad("library.filter", "captureMonthDay must be a valid MM-DD date")); + } + if f.capture_before_year.is_some_and(|year| !(1..=9999).contains(&year)) { + return Err(bad("library.filter", "captureBeforeYear must be a year from 1 to 9999")); + } + if f.capture_before_year.is_some() && f.capture_month_day.is_none() { + return Err(bad("library.filter", "captureBeforeYear needs captureMonthDay")); + } + Ok(()) +} + /// `library.source`: show the source `p` names (the part of it that is not Go Back's bookkeeping). fn show_source(s: &mut Session, p: &Value) -> Result { let kind = str_param(p, "kind").unwrap_or("all"); @@ -847,7 +980,6 @@ fn show_source(s: &mut Session, p: &Value) -> Result { Some(value) => return Err(bad("library.source", format!("`day` must be a valid MM-DD calendar date, not {value}"))), }; s.memories_day = day; - s.sort = Sort { key: SortKey::CaptureDate, ascending: false, group: GroupBy::Year, ..s.sort }; LibrarySource::Memories } "missing" => LibrarySource::Missing, @@ -856,7 +988,7 @@ fn show_source(s: &mut Session, p: &Value) -> Result { "previousExport" => LibrarySource::PreviousExport, "album" => { let a = album_param(p, "id", "library.source")?; - if s.catalog.album(a).is_none_or(|a| a.folder) { + if s.catalog.album(a).is_none() { return Err(bad("library.source", "no such collection")); } // one album at a time: `to_filter` makes the album shown replace the filter's, and the @@ -1068,15 +1200,6 @@ pub fn specs() -> Vec { let mut v = serde_json::to_value(&s.filter).unwrap_or_default(); lcc_develop::presets::deep_merge(&mut v, p); let f: Filter = serde_json::from_value(v).map_err(|e| bad("library.filter", e.to_string()))?; - if f.capture_month_day.as_deref().is_some_and(|day| !valid_memories_day(day)) { - return Err(bad("library.filter", "captureMonthDay must be a valid MM-DD date")); - } - if f.capture_before_year.is_some_and(|year| !(1..=9999).contains(&year)) { - return Err(bad("library.filter", "captureBeforeYear must be a year from 1 to 9999")); - } - if f.capture_before_year.is_some() && f.capture_month_day.is_none() { - return Err(bad("library.filter", "captureBeforeYear needs captureMonthDay")); - } let mut f = f; f.semantic = f.semantic.map(|q| q.trim().to_string()).filter(|q| !q.is_empty()); // a blank folder is no folder: no hidden "filters active" state @@ -1084,6 +1207,7 @@ pub fn specs() -> Vec { if f.library_folder.is_some() && s.source == LibrarySource::LibraryFolder { return Err(bad("library.filter", "a folder is already shown (library.source): show another source first")); } + check_memories_fields(&f)?; // checked like a smart album's rules when this call sets them: an unknown field or a value // that can't match is an error, not an empty grid. Rules that stopped checking since // (their album was deleted) don't block other filter changes. @@ -1559,7 +1683,7 @@ pub fn specs() -> Vec { select_by ), cmd!("library.selectNone", "Deselect All", ["Edit"], Some("Cmd+Shift+A"), "{}", always, |s, _| { - // nothing selected and no active photo: the arrows then start again from the view's ends (F-66C0) + // nothing selected and no active photo: the arrows then start again from the view's ends s.end_interaction()?; s.selection = Selection::default(); s.all_selected = None; @@ -2096,115 +2220,14 @@ pub fn specs() -> Vec { "{ids?, title?, headline?, caption?, descriptionWriter?, category?, supplementalCategories?: [..] | \"a, b\", subjectCode?: [..] | \"c, d\", altText?, extendedDescription?, copyright?, copyrightStatus?: unknown|copyrighted|publicDomain, usageTerms?, copyrightUrl?, creator?, creatorJobTitle?, creatorAddress?, creatorCity?, creatorState?, creatorPostalCode?, creatorCountry?, creatorPhone?, creatorEmail?, creatorWebsite?, location?, city?, state?, country?, countryCode?, gps?: \"lat, lon\" | [lat, lon] | null, keywords?: [..], addKeywords?: [..], removeKeywords?: [..]}", has_selection, |s, p| { - let strs = |k: &str| { - p.get(k).and_then(|v| match v { - Value::Array(a) => Some(a.iter().filter_map(Value::as_str).map(str::to_string).collect::>()), - // a comma-separated string (the metadata panel's single text field) - Value::String(t) => Some(t.split(',').map(|s| s.trim().to_string()).collect()), - _ => None, - }) - }; let targets = s.targets(p)?; - // GPS: "lat, lon" (decimal or 51°30'26"N 0°7'39"W), [lat, lon], or null / "" to clear - let gps: Option> = match p.get("gps") { - None => None, - Some(Value::Null) => Some(None), - Some(Value::String(t)) if t.trim().is_empty() => Some(None), - Some(Value::String(t)) => Some(Some( - parse_gps(t).ok_or_else(|| bad("photo.setMeta", format!("can't read `{t}` as coordinates (e.g. 51.5072, -0.1276)")))?, - )), - Some(Value::Array(a)) if a.len() == 2 => match (a[0].as_f64(), a[1].as_f64()) { - (Some(la), Some(lo)) if la.abs() <= 90.0 && lo.abs() <= 180.0 => Some(Some((la, lo))), - _ => return Err(bad("photo.setMeta", "gps is [latitude, longitude] in degrees")), - }, - Some(_) => return Err(bad("photo.setMeta", "gps is \"lat, lon\", [lat, lon] or null")), - }; - let status = match str_param(p, "copyrightStatus") { - Some(t) => Some( - CopyrightStatus::parse(t) - .ok_or_else(|| bad("photo.setMeta", format!("copyrightStatus `{t}`: unknown, copyrighted or publicDomain")))?, - ), - None => None, - }; + let args = meta_edit_args(p)?; + let strs = |k: &str| meta_strs(p, k); let mut ops = Vec::new(); for id in targets { let Some(ph) = s.catalog.photo(id) else { continue }; let mut m = ph.meta.clone(); - if let Some(g) = gps { - m.gps = g; - } - if let Some(st) = status { - m.copyright_status = st; - } - for (k, field) in [ - ("title", &mut m.title), - ("headline", &mut m.headline), - ("caption", &mut m.caption), - ("descriptionWriter", &mut m.description_writer), - ("category", &mut m.category), - ("copyright", &mut m.copyright), - ("usageTerms", &mut m.usage_terms), - ("copyrightUrl", &mut m.copyright_url), - ("creator", &mut m.creator), - ("location", &mut m.location), - ("city", &mut m.city), - ("state", &mut m.state), - ("country", &mut m.country), - ("countryCode", &mut m.country_code), - ("altText", &mut m.alt_text), - ("extendedDescription", &mut m.extended_description), - ] { - if let Some(v) = str_param(p, k) { - *field = v.to_string(); - } - } - for k in lcc_meta::CreatorContact::KEYS { - if let (Some(v), Some(field)) = (str_param(p, k), m.contact.get_mut(k)) { - *field = v.to_string(); - } - } - // keywords are stored cleaned (`a | b ` is `a|b`), each once whatever its case - use lcc_catalog::keywords::clean; - // (a set of the lower-cased keywords keeps this linear however many are supplied; upstream #3709) - let mut seen: std::collections::HashSet = m.keywords.iter().map(|x| x.to_lowercase()).collect(); - let add = |m: &mut lcc_catalog::Meta, seen: &mut std::collections::HashSet, k: &str| { - let k = clean(k); - if !k.is_empty() && seen.insert(k.to_lowercase()) { - m.keywords.push(k); - } - }; - if let Some(k) = strs("keywords") { - m.keywords.clear(); - seen.clear(); - for k in k { - add(&mut m, &mut seen, &k); - } - } - for k in strs("addKeywords").unwrap_or_default() { - add(&mut m, &mut seen, &k); - } - let removed: std::collections::HashSet = - strs("removeKeywords").unwrap_or_default().iter().map(|k| clean(k).to_lowercase()).collect(); - if !removed.is_empty() { - m.keywords.retain(|x| !removed.contains(&clean(x).to_lowercase())); - } - // supplemental categories and subject codes: a list, each once (the UI edits - // them as one comma-separated text field, so trimming empty entries matters) - let distinct = |v: Vec| { - let mut out: Vec = Vec::new(); - for s in v { - if !s.is_empty() && !out.contains(&s) { - out.push(s); - } - } - out - }; - if let Some(v) = strs("supplementalCategories") { - m.supplemental_categories = distinct(v); - } - if let Some(v) = strs("subjectCode") { - m.subject_code = distinct(v); - } + edit_meta(&mut m, p, args); ops.push(Op::SetMeta { id, meta: Box::new(m) }); } let n = ops.len(); @@ -2267,34 +2290,33 @@ pub fn specs() -> Vec { "Duplicate Collection", [], None, - "{id, name?}: a new regular album beside it with the same photos and Custom Order (a second order of the same photos) → {id}", + "{id, name?}: a copy beside the original: a regular collection (same photos and Custom Order), a smart collection (same rules) or a collection set (everything inside it, same order and nesting, as one undo step; saved creations are not copied) → {id, skipped} (skipped: creations left out of a set copy)", always, |s, p| { const C: &str = "album.duplicate"; let id = p.get("id").and_then(Value::as_u64).map(AlbumId).ok_or_else(|| bad(C, "missing `id`"))?; let a = s.catalog.album(id).cloned().ok_or_else(|| bad(C, format!("no collection {}", id.0)))?; - if a.folder || a.smart.is_some() || a.quick { - return Err(bad(C, "only a regular collection can be duplicated")); + if a.quick { + return Err(bad(C, "the Quick Collection can't be duplicated")); + } + if a.creation.is_some() { + return Err(bad(C, "a saved creation can't be duplicated")); } let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| format!("{} copy", a.name)); - let new = s.catalog.alloc_album_id(); - let photo_order = s.catalog.album_photo_order(id); - let album = Album { - id: new, - name, - parent: a.parent, - folder: false, - photos: a.photos.clone(), - cover: a.cover, - smart: None, - quick: false, - order: None, - creation: None, - photo_order, + let mut ops = Vec::new(); + let mut skipped = 0usize; + let first = s.catalog.alloc_album_id(); + let root = copy_album(&s.catalog, first, &a, a.parent, Some(name), 0, &mut ops, &mut skipped)?; + let label = if a.folder { + "Duplicate Collection Set" + } else if a.smart.is_some() { + "Duplicate Smart Collection" + } else { + "Duplicate Collection" }; - s.commit("Duplicate Collection", Op::AddAlbum { album })?; - Ok(json!({"id": new.0})) + s.commit(label, if ops.len() == 1 { ops.remove(0) } else { Op::Batch { ops } })?; + Ok(json!({"id": root.0, "skipped": skipped})) } ), cmd!( @@ -3113,6 +3135,7 @@ fn merge_rules( owner: Option, ) -> Result { let f = merge_filter(base, patch, c)?; + check_memories_fields(&f)?; // only rules this change sets are checked: one that stopped checking since (its album was // deleted) doesn't block editing the album's other settings let sets_rules = patch.get("ruleSet").is_some_and(|r| !r.is_null()); @@ -3173,6 +3196,10 @@ fn view_rules(s: &Session) -> lcc_catalog::Filter { if s.source == LibrarySource::LibraryFolder { f.library_folder = s.library_folder.clone(); } + // the view as it is: On This Day is its calendar day too (as `Session::view_filter` asks it) + if s.source == LibrarySource::Memories { + s.apply_memories(&mut f); + } f } }; @@ -3620,3 +3647,61 @@ pub(crate) fn tried_stamp(path: &str, size: u64) -> u64 { None => size, } } + +/// How deep a collection set may nest and how many collections one copy may hold: a copy past either +/// is refused whole, so nothing half-copied is left behind. +const COPY_MAX_DEPTH: usize = 32; +#[cfg(not(test))] +const COPY_MAX_ALBUMS: usize = 20_000; +/// Small under test, so the cap can be reached. +#[cfg(test)] +const COPY_MAX_ALBUMS: usize = 50; + +/// Pushes the `AddAlbum` ops that copy `src` under `parent` (a set's contents after it, parents first), +/// numbering new ids up from `first`; returns the copy's id. Saved creations inside a set are left out +/// and counted in `skipped`. +fn copy_album( + c: &lcc_catalog::Catalog, + first: AlbumId, + src: &Album, + parent: Option, + name: Option, + depth: usize, + ops: &mut Vec, + skipped: &mut usize, +) -> Result { + if depth >= COPY_MAX_DEPTH { + return Err(bad("album.duplicate", format!("sets nested more than {COPY_MAX_DEPTH} deep can't be duplicated"))); + } + if ops.len() >= COPY_MAX_ALBUMS { + return Err(bad("album.duplicate", format!("more than {COPY_MAX_ALBUMS} collections can't be duplicated at once"))); + } + // the ops are not applied yet, so each new id is one past the last handed out + let new = AlbumId(first.0.checked_add(ops.len() as u64).ok_or_else(|| bad("album.duplicate", "collection id out of range"))?); + let photo_order = if src.folder || src.smart.is_some() { Vec::new() } else { c.album_photo_order(src.id) }; + ops.push(Op::AddAlbum { + album: Album { + id: new, + name: name.unwrap_or_else(|| src.name.clone()), + parent, + folder: src.folder, + photos: src.photos.clone(), + cover: src.cover, + smart: src.smart.clone(), + quick: false, + order: if depth == 0 { None } else { src.order }, + creation: None, + photo_order, + }, + }); + if src.folder { + for kid in c.album_children(Some(src.id)) { + if kid.creation.is_some() { + *skipped += 1; + } else { + copy_album(c, first, kid, Some(new), None, depth + 1, ops, skipped)?; + } + } + } + Ok(new) +} diff --git a/crates/engine/src/cmd/library/tests_source_history.rs b/crates/engine/src/cmd/library/tests_source_history.rs index 9d99990536..f7876445d6 100644 --- a/crates/engine/src/cmd/library/tests_source_history.rs +++ b/crates/engine/src/cmd/library/tests_source_history.rs @@ -38,13 +38,83 @@ fn memories_filter_previous_years_and_restore_the_chosen_day() { assert_eq!(s.source, LibrarySource::Memories); assert_eq!(s.memories_day, "11-30"); assert_eq!(s.visible(), &[PhotoId(2), PhotoId(1)]); - assert_eq!(s.sort.group, lcc_catalog::GroupBy::Year); + // the view's own order and grouping: the sort chosen for other views is not touched + let sort = s.sort; + assert_eq!(sort, lcc_catalog::Sort::default(), "On This Day does not change the sort"); assert!(s.execute("library.memories", &json!({"day": "02-30"})).is_err()); assert_eq!(s.memories_day, "11-30", "invalid dates must not change the source"); s.execute("library.memories", &json!({"day": "11-29"})).unwrap(); s.execute("library.sourceBack", &json!({})).unwrap(); assert_eq!(s.source, LibrarySource::Memories); assert_eq!(s.memories_day, "11-30", "Go Back restores the month/day too"); + assert_eq!(s.undo.last().map(|u| u.label.as_str()), Some("Change Source"), "another day is another view, not a selection"); +} + +/// Another day of On This Day while a filter narrows the view: the count beside the grid is that +/// day's ("5 of 50 photos"), not the day before's, and the sort the person chose for the library +/// is theirs again once they leave. +#[test] +fn memories_keep_their_own_total_and_leave_the_sort_alone() { + let mut s = Session::new(); + for (id, date, rating) in [(1, "2021-10-01T12:00:00", 5), (2, "2022-10-01T12:00:00", 5), (3, "2023-10-02T12:00:00", 1)] { + let mut p = Photo::new(PhotoId(id), Source::File { path: format!("/memories/{id}.jpg") }, "photo.jpg", "JPEG", 40, 30, "2026-11-30"); + p.captured = Some(date.to_string()); + p.rating = rating; + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + s.execute("library.sort", &json!({"key": "fileName", "ascending": true, "group": "month"})).unwrap(); + let chosen = s.sort; + s.execute("library.memories", &json!({"day": "10-01"})).unwrap(); + s.execute("library.filter", &json!({"rating": 3})).unwrap(); + assert_eq!((s.visible().len(), s.source_total()), (2, Some(2))); + s.execute("library.memories", &json!({"day": "10-02"})).unwrap(); + assert_eq!((s.visible().len(), s.source_total()), (0, Some(1)), "the other day's photos, counted for itself"); + // the filter itself shows as a chip and in the filter's description + s.execute("library.filter", &json!({"captureMonthDay": "10-02"})).unwrap(); + let chips = crate::filter_chips(&s.filter, &s.catalog); + assert!(chips.iter().any(|c| c.clear.get("captureMonthDay").is_some() && c.label.contains("10-02")), "{chips:?}"); + assert!(s.filter.describe().contains("captured on 10-02"), "{}", s.filter.describe()); + assert!(s.execute("library.filter", &json!({"captureMonthDay": null, "captureBeforeYear": 2020})).is_err(), "a year needs a day"); + assert!(s.execute("library.filter", &json!({"captureMonthDay": "02-30"})).is_err()); + // a smart collection from the view keeps the day (it is part of what the view shows) + s.execute("library.clearFilter", &json!({})).unwrap(); + let made = s.execute("album.createSmart", &json!({"name": "Then"})).unwrap(); + assert_eq!(made["count"], 1, "{made}"); + s.execute("library.source", &json!({"kind": "all"})).unwrap(); + assert_eq!(s.sort, chosen, "the sort chosen before is back with the other views"); +} + +/// A typed Memories day and an impossible one in a smart collection's rules are refused alike. +#[test] +fn smart_collection_rules_check_the_memories_fields() { + let mut s = Session::new(); + let id = s.execute("album.createSmart", &json!({"name": "Mine"})).unwrap()["id"].as_u64().unwrap(); + let bad = s.execute("album.setRules", &json!({"id": id, "rules": {"captureBeforeYear": 2020}})); + assert!(bad.is_err(), "{bad:?}"); + let ok = s.execute("album.setRules", &json!({"id": id, "rules": {"captureMonthDay": "11-30", "captureBeforeYear": 2026}})); + assert!(ok.is_ok(), "{ok:?}"); +} + +/// Captures that only look like a date (a month alone, a padded or signed year, a non-ASCII +/// digit, February 30) are not a calendar-day match. +#[test] +fn memories_match_only_a_full_calendar_date() { + let mut c = lcc_catalog::Catalog::new(); + let mut ids = Vec::new(); + for (i, date) in ["2021-11-30T08:00:00", "2021-11", "2021", "+2021-11-30", "2021-1-30", "2021-11-30", "2021-02-30", "bad", "é021-11-30"] + .into_iter() + .enumerate() + { + let mut p = Photo::new(PhotoId(i as u64), Source::File { path: format!("/d/{i}.jpg") }, "p.jpg", "JPEG", 40, 30, "2026-11-30"); + p.captured = Some(date.to_string()); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + ids.push(PhotoId(i as u64)); + } + let f = lcc_catalog::Filter { capture_month_day: Some("11-30".into()), capture_before_year: Some(2022), ..Default::default() }; + assert_eq!(c.query(&f, &lcc_catalog::Sort::default()), vec![PhotoId(0)]); + let f = lcc_catalog::Filter { capture_month_day: Some("02-30".into()), ..Default::default() }; + assert!(c.query(&f, &lcc_catalog::Sort::default()).is_empty()); + let _ = ids; } #[test] diff --git a/crates/engine/src/cmd/ml.rs b/crates/engine/src/cmd/ml.rs index 9faac6efda..7e81a378c8 100644 --- a/crates/engine/src/cmd/ml.rs +++ b/crates/engine/src/cmd/ml.rs @@ -155,7 +155,7 @@ pub fn specs() -> Vec { "Orientation Detection Status", [], None, - "{} → {classifier: {available, origin?: fitted | builtIn, embedder?, minConfidence?, source?, report?, reason?}, running: {checked, total} | null, last: (the last finished photo.autoOrient answer) | null}: which classifier AI orientation detection uses and how its last run went", + "{} → {classifier: {available, modelInstalled, origin?: fitted | builtIn, embedder?, minConfidence?, source?, report?, path?, fittedAt?, reason?}, running: {checked, total} | null, fitting: {phase: embedding | fitting, checked, total, failed} | null, last: (the last finished photo.autoOrient answer) | null, lastFit: (the last finished ml.orientation.fit answer) | null, libraryPhotos}: which classifier AI orientation detection uses, whether a fit is running, and how the last runs went", super::always, |s, p| s.ml_orientation_status(p) ), @@ -164,10 +164,19 @@ pub fn specs() -> Vec { "Fit Orientation Classifier", [], None, - "{ids?: [PhotoId], out?: path, steps?: 600, budgetMs?: 21600000} → {path, embedder, photos, failed, notReached, minConfidence, report: {photos, holdoutPhotos, viewAccuracy, photoAccuracy, thresholds: [{minConfidence, coverage, accuracy}]}}: fit AI orientation detection's classifier on the library's photos (or `ids`) as they are shown now, taken to be upright: each is rendered, turned four ways and embedded by the active CLIP model, then a 4-way linear classifier is fitted, measured on one photo in five held out, and saved as `/orientation-.json` (or `out`), where photo.autoOrient uses it. Waits until done (up to `budgetMs`). Only the fitted numbers are kept, never the photos", + "{ids?: [PhotoId], out?: path, steps?: 600, wait?: true, budgetMs?: 21600000} → {done, path, embedder, photos, failed, notReached, minConfidence, report: {photos, holdoutPhotos, viewAccuracy, photoAccuracy, thresholds: [{minConfidence, coverage, accuracy}]}} (or {done: false, queued, checked, total, phase} when `wait: false`): fit AI orientation detection's classifier on the library's photos (or `ids`) as they are shown now, taken to be upright: each is rendered, turned four ways and embedded by the active CLIP model, then a 4-way linear classifier is fitted, measured on one photo in five held out, and saved as `/orientation-.json` (or `out`), where photo.autoOrient uses it. With `wait: false` it runs in the background with a `mlOrient` activity row (its ✕ cancels it) and finishes via `ml.pump`. Only the fitted numbers are kept, never the photos", super::always, |s, p| s.ml_orientation_fit(p) ), + cmd!( + query "ml.orientation.clear", + "Clear Orientation Classifier", + [], + None, + "{} → {removed, path?}: delete the fitted orientation classifier file for the active CLIP model so a new one can be fitted", + super::always, + |s, p| s.ml_orientation_clear(p) + ), cmd!( query "search.semantic", "Semantic Photo Search", diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index b4f3b909bb..a2bbcdae10 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -79,8 +79,9 @@ pub mod marketplace; pub(crate) mod plugin_develop; pub(crate) mod plugin_filters; #[cfg(not(target_arch = "wasm32"))] -pub mod plugin_jobs; +pub(crate) mod plugin_held; #[cfg(not(target_arch = "wasm32"))] +pub mod plugin_jobs; pub(crate) mod plugin_library; #[cfg(not(target_arch = "wasm32"))] pub mod plugin_programs; diff --git a/crates/engine/src/cmd/plugin_held.rs b/crates/engine/src/cmd/plugin_held.rs new file mode 100644 index 0000000000..c1566c8d55 --- /dev/null +++ b/crates/engine/src/cmd/plugin_held.rs @@ -0,0 +1,268 @@ +//! Catalog writes a plug-in job holds: `metadata.setStandard` and `library.add` made inside a job +//! are kept in a [`Held`] list instead of reaching the catalog, and applied when the job ends, as +//! one undo step named after the command and the plug-in. A job that is cancelled or fails drops +//! them. +//! +//! The job's later calls still see what it holds: a `photo.inspect` (and the `title` and `keywords` +//! of a `catalog.query` row) shows a photo's metadata with the held edits made. A photo is held +//! with the metadata it had when the job first wrote it; at the end, a photo whose metadata is no +//! longer that (the user edited it meanwhile, or it left the library) is skipped and named. +//! Nothing a job holds is checked against the catalog until then, beyond the call's own shape. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError}; + +use lcc_catalog::{Meta, PhotoId}; +use lcc_plugins::HostApi; +use serde_json::{Value, json}; + +use super::library::{edit_meta, meta_edit_args}; +use super::plugin_library::{id_of, steps_since}; +use crate::Session; + +/// Most photo edits and added files one job may hold: a call that would pass it fails. +pub(super) const MAX_HELD_WRITES: usize = 10_000; +/// Most bytes of call parameters one job may hold. +pub(super) const MAX_HELD_BYTES: usize = 8 << 20; + +#[derive(Clone, Debug)] +enum Op { + /// `metadata.setStandard`, as `photo.setMeta` takes it (`ids` are numbers). + Meta { ids: Vec, params: Value }, + /// `library.add`, as `plugin_library::add` takes it. + Add(Value), +} + +/// A job's held writes, in the order they were made. +#[derive(Clone, Debug, Default)] +pub(super) struct Held { + ops: Vec, + /// Photo edits and added files held ([`MAX_HELD_WRITES`]). + writes: usize, + bytes: usize, + /// Each edited photo's metadata when the job first wrote it. + base: HashMap, + /// Each edited photo's metadata with every held edit made: what the job's reads show. + now: HashMap, +} + +impl Held { + /// How many writes are held. + pub(super) fn len(&self) -> usize { + self.writes + } + + fn room(&self, writes: usize, params: &Value) -> Result { + let bytes = self.bytes.saturating_add(params.to_string().len()); + if self.writes.saturating_add(writes) > MAX_HELD_WRITES { + return Err(format!("a job can hold at most {MAX_HELD_WRITES} catalog writes; nothing was applied")); + } + if bytes > MAX_HELD_BYTES { + return Err(format!("a job can hold at most {} MB of catalog writes; nothing was applied", MAX_HELD_BYTES >> 20)); + } + Ok(bytes) + } + + /// The metadata of photo `id` with the held edits made, if the job has edited it. + fn current(&self, id: u64) -> Option<&Meta> { + self.now.get(&id) + } + + /// Shows the held edits in `reply`, the answer to a catalog read. + fn overlay(&self, method: &str, reply: &mut Value) { + if self.base.is_empty() { + return; + } + match method { + "photo.inspect" => { + if let Some(m) = reply.get("id").and_then(Value::as_u64).and_then(|id| self.current(id)) + && let Ok(v) = serde_json::to_value(m) + { + reply["meta"] = v; + } + } + "catalog.query" => { + for row in reply.get_mut("photos").and_then(Value::as_array_mut).into_iter().flatten() { + if let Some(m) = row.get("id").and_then(Value::as_u64).and_then(|id| self.current(id)) { + row["title"] = json!(m.title); + row["keywords"] = json!(m.keywords); + } + } + } + _ => {} + } + } +} + +/// A host that holds its job's catalog writes, over the host `H` the job's calls otherwise go to. +pub(super) struct Holding { + pub(super) inner: H, + pub(super) held: Held, +} + +impl Holding { + pub(super) fn new(inner: H) -> Self { + Holding { inner, held: Held::default() } + } +} + +impl HostApi for Holding { + fn catalog(&mut self, method: &str, params: &Value) -> Result { + let mut reply = self.inner.catalog(method, params)?; + self.held.overlay(method, &mut reply); + Ok(reply) + } + + fn set_metadata(&mut self, params: &Value) -> Result { + let params = super::plugins::standard_params(params)?; + let args = meta_edit_args(¶ms).map_err(|e| e.to_string())?; + let ids: Vec = params.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect(); + let bytes = self.held.room(ids.len(), ¶ms)?; + // a photo is held as it is now: the end checks the user hasn't changed it since + let mut base: Vec<(u64, Meta)> = Vec::new(); + let mut seen_now = std::collections::HashSet::new(); + for id in &ids { + if self.held.base.contains_key(id) || !seen_now.insert(*id) { + continue; + } + let seen = self.inner.catalog("photo.inspect", &json!({"id": id}))?; + let meta = serde_json::from_value::(seen.get("meta").cloned().unwrap_or_default()) + .map_err(|e| format!("metadata.setStandard: photo {id}'s metadata can't be read ({e})"))?; + base.push((*id, meta)); + } + for (id, meta) in base { + self.held.now.insert(id, meta.clone()); + self.held.base.insert(id, meta); + } + for id in &ids { + if let Some(m) = self.held.now.get_mut(id) { + edit_meta(m, ¶ms, args); + } + } + self.held.writes += ids.len(); + self.held.bytes = bytes; + self.held.ops.push(Op::Meta { ids: ids.clone(), params }); + Ok(json!({"changed": ids.len(), "held": true})) + } + + fn library_add(&mut self, params: &Value) -> Result { + params.get("path").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or("library.add: missing `path`")?; + id_of(params.get("from"), "from").map_err(|e| format!("library.add: {e}"))?; + let bytes = self.held.room(1, params)?; + self.held.writes += 1; + self.held.bytes = bytes; + self.held.ops.push(Op::Add(params.clone())); + Ok(json!({"held": true})) + } + + fn library_remove(&mut self, params: &Value) -> Result { + self.inner.library_remove(params) + } + + fn photo_pixels(&mut self, photo: &str, long_edge: u32) -> Result { + self.inner.photo_pixels(photo, long_edge) + } + + fn set_crop(&mut self, photo: &str, rect: [f64; 4], angle: Option) -> Result { + self.inner.set_crop(photo, rect, angle) + } + + fn virtual_copy(&mut self, photo: &str, name: Option<&str>) -> Result { + self.inner.virtual_copy(photo, name) + } + + fn find_program(&mut self, program: &lcc_plugins::ProgramDecl) -> Vec { + self.inner.find_program(program) + } + + fn start_program(&mut self, run: lcc_plugins::StartRequest) -> Result<(), String> { + self.inner.start_program(run) + } +} + +/// Held writes on their way to the session's thread ([`super::plugins::Relayed::ApplyHeld`]). +pub(super) type Handoff = Arc>>; + +pub(super) fn handoff(held: Held, label: String) -> Handoff { + Arc::new(Mutex::new(Some((held, label)))) +} + +/// Applies the writes in `slot` to `s`, as [`apply`] does. +pub(super) fn apply_handoff(s: &mut Session, slot: &Handoff) -> Result { + let taken = slot.lock().unwrap_or_else(PoisonError::into_inner).take(); + let (held, label) = taken.ok_or("the held writes were already applied")?; + Ok(apply(s, held, &label)) +} + +/// Applies `held` to `s` as one undo step named `label`. A photo changed since the job first wrote +/// it is skipped, and a write that fails doesn't stop the others. → `{applied, skipped: [{photo, +/// why}], failed: [text], note}` +pub(super) fn apply(s: &mut Session, held: Held, label: &str) -> Value { + let changed: Vec = held + .base + .iter() + .filter(|(id, seen)| s.catalog.photo(PhotoId(**id)).is_none_or(|ph| !ph.in_library() || ph.meta != **seen)) + .map(|(id, _)| *id) + .collect(); + let mark = s.undo_mark(); + let (mut applied, mut skipped, mut failed) = (0usize, Vec::::new(), Vec::::new()); + let skip = |id: u64, skipped: &mut Vec| { + if !skipped.iter().any(|v| v["photo"] == id) { + skipped.push(json!({"photo": id.to_string(), "why": "it changed after the job first wrote it"})); + } + }; + for op in held.ops { + match op { + Op::Meta { ids, params, .. } => { + let (keep, left): (Vec, Vec) = ids.into_iter().partition(|id| !changed.contains(id)); + for id in left { + skip(id, &mut skipped); + } + if keep.is_empty() { + continue; + } + let mut p = params; + p["ids"] = json!(keep); + match s.execute("photo.setMeta", &p) { + Ok(_) => applied += keep.len(), + Err(e) => failed.push(format!("metadata.setStandard: {e}")), + } + } + Op::Add(p) => { + let from = id_of(p.get("from"), "from").unwrap_or(0); + if changed.contains(&from) { + skip(from, &mut skipped); + continue; + } + match super::plugin_library::add(s, &p) { + Ok(_) => applied += 1, + Err(e) => failed.push(format!("library.add: {e}")), + } + } + } + } + match steps_since(s, mark) { + 0 | 1 => { + if steps_since(s, mark) == 1 + && let Some(e) = s.undo.last_mut() + { + e.label = label.to_string(); + } + } + n => s.merge_undo(n, label), + } + let mut note = format!("{applied} held catalog write{} applied", if applied == 1 { "" } else { "s" }); + if !skipped.is_empty() { + let names: Vec = skipped.iter().filter_map(|v| v["photo"].as_str().map(str::to_string)).collect(); + note.push_str(&format!("; skipped {} changed photo{} ({})", names.len(), if names.len() == 1 { "" } else { "s" }, names.join(", "))); + } + if !failed.is_empty() { + note.push_str(&format!("; {} failed: {}", failed.len(), failed.join("; "))); + } + json!({"applied": applied, "skipped": skipped, "failed": failed, "note": note}) +} + +/// What a job that ends without applying says about the writes it held (`n` of them). +pub(super) fn discarded(n: usize) -> Value { + json!({"applied": 0, "discarded": n, "note": format!("{n} held catalog write{} not applied", if n == 1 { " was" } else { "s were" })}) +} diff --git a/crates/engine/src/cmd/plugin_jobs.rs b/crates/engine/src/cmd/plugin_jobs.rs index cd08219fa0..df358acc82 100644 --- a/crates/engine/src/cmd/plugin_jobs.rs +++ b/crates/engine/src/cmd/plugin_jobs.rs @@ -5,7 +5,8 @@ //! `job.cancelled` says so, every other host call fails with "cancelled", and a reply //! `{continue: state}` is not called again. //! -//! A job may read the catalog, never change it (`lcc_plugins` refuses the writes). Its reads are +//! A job may read the catalog; its `metadata.setStandard` and `library.add` are held and applied +//! when it ends, as one undo step ([`super::plugin_held`]). Its reads are //! relayed to the session's thread like a `program.end` hook's //! ([`super::plugin_programs::answer_requests`]); a session nobody answers for (headless MCP or //! CLI) refuses them at once, so those run a job with `wait: true`, on the caller's thread. @@ -21,6 +22,7 @@ use std::time::Duration; use lcc_plugins::{HostApi, JobReporter, JobUnit, Manager, PendingCall, StartRequest}; use serde_json::{Value, json}; +use super::plugin_held::{self, Held, Holding}; use super::plugin_programs::{answered, relay_sender}; use super::plugins::{RelayHost, Relayed, SessionHost, manager_for}; use crate::Session; @@ -109,8 +111,9 @@ impl Row { } /// What a job on a worker sees: catalog reads relayed to the session's thread when the app answers -/// them (refused at once otherwise), the session's desktop to look programs up. Writes and starts -/// are refused (`lcc_plugins` refuses them first in a job). +/// them (refused at once otherwise), the session's desktop to look programs up. Its writes are +/// held by a [`Holding`] around it; the other writes and starts are refused (`lcc_plugins` refuses +/// them first in a job). struct JobHost(RelayHost); impl JobHost { @@ -119,7 +122,7 @@ impl JobHost { } } -const NO_WRITES: &str = "writes to the catalog aren't available in a job yet"; +const NO_WRITES: &str = "writes to the catalog other than metadata.setStandard and library.add aren't available in a job yet"; impl HostApi for JobHost { fn catalog(&mut self, method: &str, params: &Value) -> Result { @@ -153,9 +156,35 @@ impl HostApi for JobHost { } } -/// How a job ended, for [`take_finished`] and `plugin.run {wait}`. -fn report(id: u64, plugin: &str, plugin_name: &str, command: &str, label: &str, r: &Result) -> Value { +/// The result of a job run with `wait`, with what became of its held writes (`held`, if it held +/// any): in the last reply of a job that succeeded, in the error of one that didn't. +fn with_held(r: Result, held: Option<&Value>) -> Result { + let Some(held) = held else { return r }; + match r { + Ok(Value::Null) => Ok(json!({"held": held})), + Ok(mut v) => { + if let Some(o) = v.as_object_mut() { + o.insert("held".into(), held.clone()); + } + Ok(v) + } + Err(e) => { + let why = match e { + lcc_plugins::Error::Cancelled => "cancelled".to_string(), + lcc_plugins::Error::Failed(m) => m, + e => e.to_string(), + }; + Err(lcc_plugins::Error::Failed(format!("{why} ({})", held["note"].as_str().unwrap_or("held catalog writes not applied")))) + } + } +} + +/// How a job ended, for [`take_finished`] and `plugin.run {wait}`; `held`: what became of its held writes. +fn report(id: u64, plugin: &str, plugin_name: &str, command: &str, label: &str, r: &Result, held: Option) -> Value { let mut v = json!({"job": id, "plugin": plugin, "pluginName": plugin_name, "command": command, "label": label}); + if let Some(h) = held { + v["held"] = h; + } match r { Ok(ok) => v["ok"] = ok.clone(), Err(lcc_plugins::Error::Cancelled) => v["cancelled"] = json!(true), @@ -183,6 +212,27 @@ fn run_guarded(call: &mut PendingCall, host: &mut dyn HostApi, row: &Row) -> lcc }) } +/// What became of the writes a job held when it ended: applied as one undo step by `apply` when +/// it succeeded, dropped when it didn't. `None` when it held none. +fn settle(held: Held, ok: bool, label: &str, apply: impl FnOnce(Held, &str) -> Result) -> Option { + let n = held.len(); + if n == 0 { + return None; + } + if !ok { + return Some(plugin_held::discarded(n)); + } + Some( + apply(held, label) + .unwrap_or_else(|e| json!({"applied": 0, "failed": [e.clone()], "note": format!("{n} held catalog writes were not applied: {e}")})), + ) +} + +/// The undo step's name: the command and the plug-in, as the job's row is named. +fn step_label(call: &PendingCall) -> String { + format!("{} ({})", call.job_label().unwrap_or_default(), call.plugin_name()) +} + /// Runs job `call` of session `s`, begun with [`Manager::begin_command`]. On a worker by default: /// returns `{job: its activity id, running: true, plugin, command}` at once. With `wait`, here, to the end: its /// last reply, or its error. @@ -198,13 +248,18 @@ pub(super) fn run(s: &mut Session, mut call: PendingCall, wait: bool) -> Result< call.job_label().unwrap_or_default().to_string(), ); if wait { - let outcome = run_guarded(&mut call, &mut SessionHost(s), &row); + let label = step_label(&call); + let mut host = Holding::new(SessionHost(s)); + let outcome = run_guarded(&mut call, &mut host, &row); + let held = host.held; + let ok = outcome.value.is_ok(); + let settled = settle(held, ok, &label, |h, l| Ok(plugin_held::apply(s, h, l))); let r = manager_for(&library).get_or_insert_with(Manager::in_memory).end(call, Some(outcome)); row.end(); super::plugins::sync_fields(s); - return r; + return with_held(r, settled.as_ref()); } - let host = JobHost(RelayHost::new(relay_sender(), s)); + let host = Holding::new(JobHost(RelayHost::new(relay_sender(), s))); let started = json!({"job": id, "running": true, "plugin": names.0, "command": names.2}); // the call and its row are moved in; a thread that can't start hands them back let (tx, rx) = std::sync::mpsc::channel::<(PendingCall, Row)>(); @@ -216,9 +271,16 @@ pub(super) fn run(s: &mut Session, mut call: PendingCall, wait: bool) -> Result< let Ok((mut call, row)) = rx.recv() else { return }; let mut host = host; let outcome = run_guarded(&mut call, &mut host, &row); + let ok = outcome.value.is_ok(); + let Holding { inner: job, held } = host; + // the session's thread applies what the job held, as one undo step + let settled = settle(held, ok, &step_label(&call), |h, l| { + job.reachable()?; + job.0.ask_within(Relayed::ApplyHeld(plugin_held::handoff(h, l.to_string())), &Value::Null, ANSWER_WAIT) + }); let r = manager_for(&library).get_or_insert_with(Manager::in_memory).end(call, Some(outcome)); let (plugin, plugin_name, command, label) = &names; - let ended = report(id, plugin, plugin_name, command, label, &r); + let ended = report(id, plugin, plugin_name, command, label, &r, settled); // the row goes before the report, so whoever reads the report sees the row gone row.end(); { @@ -258,7 +320,7 @@ mod tests { /// A job `go` ("Go Far") of plug-in `id` that sends each of `requests`, then replies `reply`. fn job_module(id: &str, requests: &[&str], reply: &str) -> Vec { let manifest = format!( - r#"{{"id":"{id}","name":"Job Test","version":"1.0.0","requires":["jobs"],"permissions":{{"catalog":true}},"commands":[{{"id":"go","label":"Go Far","job":true}}]}}"# + r#"{{"id":"{id}","name":"Job Test","version":"1.0.0","requires":["jobs"],"permissions":{{"catalog":true,"metadataWrite":true,"libraryAdd":true}},"commands":[{{"id":"go","label":"Go Far","job":true}}]}}"# ); let esc = |s: &str| s.replace('"', "\\\""); let data: String = requests.iter().enumerate().map(|(k, r)| format!("(data (i32.const {}) \"{}\")", 8192 + 1024 * k, esc(r))).collect(); @@ -365,8 +427,252 @@ mod tests { let ended = within("the job's end", || take_finished(&mut s).into_iter().find(|v| v["job"] == started["job"])); assert!(ended["error"].as_str().is_some_and(|e| e.contains("the disk is full")), "{ended}"); let log = s.execute("plugin.log", &json!({"id": "test.fail"})).unwrap(); - assert!(log.as_array().unwrap().iter().any(|l| l.as_str().is_some_and(|l| l.contains("the disk is full"))), "{log}"); + assert!(log.as_array().unwrap().iter().any(|l| l["text"].as_str().is_some_and(|l| l.contains("the disk is full"))), "{log}"); + } + } + + /// Installs the job module `bytes` with the catalog and metadata writes granted. + fn install_writing(bytes: &[u8]) { + let grant = lcc_plugins::Permissions { catalog: true, metadata_write: true, library_add: true, ..Default::default() }; + manager().get_or_insert_with(Manager::in_memory).install_bytes_by_user(bytes, Some(grant), false).unwrap(); + } + + /// A `metadata.setStandard` request setting `title` on photo `id`. + fn set_title(id: u64, title: &str) -> String { + format!(r#"{{"method":"metadata.setStandard","params":{{"ids":["{id}"],"title":"{title}"}}}}"#) + } + + fn title_of(s: &mut Session, id: u64) -> String { + s.execute("photo.inspect", &json!({"id": id})).unwrap()["meta"]["title"].as_str().unwrap_or_default().to_string() + } + + /// Runs the session's side of a background job until its report is in. + fn finish(s: &mut Session, job: &Value) -> Value { + within("the job's end", || { + super::super::plugin_programs::answer_requests(s); + take_finished(s).into_iter().find(|v| v["job"] == *job) + }) + } + + #[test] + fn a_jobs_metadata_writes_are_applied_when_it_ends_as_one_undo_step_named_after_the_plugin() { + let _test_plugins = crate::cmd::plugins::TEST_PLUGINS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _turn = turn(); + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().iter().take(3).map(|p| p.0).collect(); + let before: Vec = ids.iter().map(|id| title_of(&mut s, *id)).collect(); + let requests: Vec = ids.iter().map(|id| set_title(*id, &format!("Held {id}"))).collect(); + let requests: Vec<&str> = requests.iter().map(String::as_str).collect(); + install_writing(&job_module("test.hold", &requests, r#"{"ok":{"message":"Done"}}"#)); + // in the background: the session answers, and the job's report says what was applied + let started = s.execute("plugin.run", &json!({"plugin": "test.hold", "command": "go"})).unwrap(); + let mark = s.undo_mark(); + let ended = finish(&mut s, &started["job"]); + assert_eq!(ended["ok"]["message"], "Done", "{ended}"); + assert_eq!(ended["held"]["applied"], 3, "{ended}"); + for id in &ids { + assert_eq!(title_of(&mut s, *id), format!("Held {id}"), "the held writes were applied at the end"); + } + assert_eq!(s.undo_mark() - mark, 1, "three writes, one undo step"); + assert_eq!(s.undo.last().map(|u| u.label.as_str()), Some("Go Far (Job Test)"), "named after the command and the plug-in"); + s.execute("edit.undo", &json!({})).unwrap(); + for (id, old) in ids.iter().zip(&before) { + assert_eq!(&title_of(&mut s, *id), old, "one Undo takes all three back"); + } + // with wait: the same, on the caller's thread, and the reply says what was applied + let r = s.execute("plugin.run", &json!({"plugin": "test.hold", "command": "go", "wait": true})).unwrap(); + assert_eq!(r["held"]["applied"], 3, "{r}"); + assert_eq!(s.undo.last().map(|u| u.label.as_str()), Some("Go Far (Job Test)")); + } + + #[test] + fn a_job_that_fails_or_is_stopped_applies_none_of_its_held_writes_and_says_so() { + let _test_plugins = crate::cmd::plugins::TEST_PLUGINS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _turn = turn(); + let mut s = Session::with_demo(); + let id = s.visible_cloned().first().map(|p| p.0).unwrap(); + let old = title_of(&mut s, id); + // fails after writing + install_writing(&job_module("test.holdfail", &[&set_title(id, "Never")], r#"{"error":"the disk is full"}"#)); + let started = s.execute("plugin.run", &json!({"plugin": "test.holdfail", "command": "go"})).unwrap(); + let ended = finish(&mut s, &started["job"]); + assert!(ended["error"].as_str().is_some_and(|e| e.contains("the disk is full")), "{ended}"); + assert_eq!(ended["held"]["discarded"], 1, "{ended}"); + assert!(ended["held"]["note"].as_str().is_some_and(|n| n.contains("not applied")), "{ended}"); + assert_eq!(title_of(&mut s, id), old, "a failed job changes nothing"); + let e = s.execute("plugin.run", &json!({"plugin": "test.holdfail", "command": "go", "wait": true})).unwrap_err().to_string(); + assert!(e.contains("the disk is full") && e.contains("not applied"), "wait: the error says so too: {e}"); + // stopped while it goes on + // the progress report after the write tells the test the write was made + install_writing(&job_module( + "test.holdstop", + &[&set_title(id, "Never"), r#"{"method":"job.progress","params":{"done":1,"total":3}}"#], + r#"{"ok":{"continue":1}}"#, + )); + let started = s.execute("plugin.run", &json!({"plugin": "test.holdstop", "command": "go"})).unwrap(); + within("the job's write", || { + super::super::plugin_programs::answer_requests(&mut s); + s.activity.list().iter().find(|t| t.id == started["job"] && t.done == 1).map(|_| ()) + }); + s.execute("activity.cancel", &json!({"id": started["job"]})).unwrap(); + let ended = finish(&mut s, &started["job"]); + assert_eq!(ended["cancelled"], true, "{ended}"); + assert!(ended["held"]["discarded"].as_u64().is_some_and(|n| n >= 1), "{ended}"); + assert_eq!(title_of(&mut s, id), old, "a stopped job changes nothing"); + } + + /// A host over `s` that holds, as a job's does. + fn holding(s: &mut Session) -> Holding> { + Holding::new(SessionHost(s)) + } + + #[test] + fn held_writes_stay_out_of_the_catalog_but_the_jobs_later_reads_see_them() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + let old = title_of(&mut s, ids[0]); + let mut h = holding(&mut s); + h.set_metadata(&json!({"ids": [ids[0].to_string()], "title": "Held title", "addKeywords": ["held-one"]})).unwrap(); + // what the job reads shows the write + let seen = h.catalog("photo.inspect", &json!({"id": ids[0].to_string()})).unwrap(); + assert_eq!(seen["meta"]["title"], "Held title", "{seen}"); + assert!(seen["meta"]["keywords"].as_array().unwrap().iter().any(|k| k == "held-one"), "{seen}"); + let rows = h.catalog("catalog.query", &json!({"limit": 5})).unwrap(); + let row = rows["photos"].as_array().unwrap().iter().find(|r| r["id"] == ids[0]).expect("the photo's row"); + assert_eq!(row["title"], "Held title", "{row}"); + let other = rows["photos"].as_array().unwrap().iter().find(|r| r["id"] == ids[1]).expect("another row"); + assert_ne!(other["title"], "Held title", "a photo the job didn't write shows as it is"); + // a second write builds on the first + h.set_metadata(&json!({"ids": [ids[0].to_string()], "removeKeywords": ["held-one"]})).unwrap(); + let seen = h.catalog("photo.inspect", &json!({"id": ids[0]})).unwrap(); + assert!(!seen["meta"]["keywords"].as_array().unwrap().iter().any(|k| k == "held-one"), "{seen}"); + assert_eq!(seen["meta"]["title"], "Held title"); + assert_eq!(h.held.len(), 2); + drop(h); + // nothing reached the catalog + assert_eq!(title_of(&mut s, ids[0]), old, "nothing is written until the job ends"); + } + + #[test] + fn a_photo_the_user_changed_after_the_job_first_wrote_it_is_skipped_and_named() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + let mut h = holding(&mut s); + h.set_metadata(&json!({"ids": [ids[0].to_string(), ids[1].to_string()], "title": "From the job"})).unwrap(); + let held = h.held; + // the user edits the first photo meanwhile + s.execute("photo.setMeta", &json!({"ids": [ids[0]], "caption": "The user's own"})).unwrap(); + let r = plugin_held::apply(&mut s, held, "Go Far (Job Test)"); + assert_eq!(r["applied"], 1, "{r}"); + assert_eq!(r["skipped"][0]["photo"], ids[0].to_string(), "{r}"); + assert!(r["note"].as_str().is_some_and(|n| n.contains(&ids[0].to_string())), "the summary names it: {r}"); + assert_ne!(title_of(&mut s, ids[0]), "From the job", "the user's photo is left alone"); + assert_eq!(title_of(&mut s, ids[1]), "From the job", "the others are applied"); + } + + #[test] + fn held_writes_have_a_cap_and_a_call_that_passes_it_fails_with_nothing_held() { + let mut s = Session::with_demo(); + let id = s.visible_cloned().first().map(|p| p.0).unwrap(); + let mut h = holding(&mut s); + // too many photos in one call + let many: Vec = (0..=plugin_held::MAX_HELD_WRITES as u64).map(|n| n.to_string()).collect(); + let e = h.set_metadata(&json!({"ids": many, "title": "x"})).unwrap_err(); + assert!(e.contains("at most") && e.contains("nothing was applied"), "{e}"); + // too much text + let big = "x".repeat(plugin_held::MAX_HELD_BYTES + 1); + let e = h.set_metadata(&json!({"ids": [id.to_string()], "caption": big})).unwrap_err(); + assert!(e.contains("at most") && e.contains("MB"), "{e}"); + assert_eq!(h.held.len(), 0, "a refused call holds nothing"); + // the count is of writes, across calls + h.set_metadata(&json!({"ids": [id.to_string()], "title": "one"})).unwrap(); + let rest: Vec = (0..plugin_held::MAX_HELD_WRITES as u64).map(|_| id.to_string()).collect(); + assert!(h.set_metadata(&json!({"ids": rest, "title": "two"})).is_err()); + assert_eq!(h.held.len(), 1); + } + + #[test] + fn hostile_held_write_params_are_errors_not_panics() { + let mut s = Session::with_demo(); + let mut h = holding(&mut s); + for p in [ + json!({}), + json!({"ids": []}), + json!({"ids": "7", "title": "x"}), + json!({"ids": ["x"], "title": "x"}), + json!({"ids": [u64::MAX.to_string()], "title": "x"}), + json!({"ids": [-1], "title": "x"}), + json!({"ids": ["1"], "notAField": "x"}), + json!({"ids": ["1"], "gps": "nowhere"}), + Value::Null, + json!([1, 2]), + ] { + assert!(h.set_metadata(&p).is_err(), "{p}"); } + for p in [json!({}), json!({"path": "", "from": "1"}), json!({"path": "/a", "from": "x"}), json!({"path": 5, "from": "1"}), Value::Null] { + assert!(h.library_add(&p).is_err(), "{p}"); + } + assert_eq!(h.held.len(), 0); + } + + #[test] + fn a_held_library_add_adds_its_file_at_the_end_in_one_undo_step_with_the_metadata_writes() { + let dir = std::env::temp_dir().join(format!("held-add-ok-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let png = |name: &str, seed: u8| { + let data: Vec<[u8; 4]> = (0..32 * 20).map(|i| [(i % 32 * 6) as u8, (i / 32 * 9) as u8, seed, 255]).collect(); + let img = lcc_raster::Rgba8 { width: 32, height: 20, data }; + let bytes = lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(&img), &lcc_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join(name), bytes).unwrap(); + dir.join(name) + }; + let beach = png("beach.png", 9); + let made = png("beach-edit.png", 40); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [beach.to_string_lossy()]})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + let before = s.catalog.photos().count(); + let mut h = holding(&mut s); + let r = h.library_add(&json!({"path": made.to_string_lossy(), "from": id.to_string()})).unwrap(); + assert_eq!(r["held"], true, "{r}"); + h.set_metadata(&json!({"ids": [id.to_string()], "title": "Edited beach"})).unwrap(); + let held = h.held; + assert_eq!(s.catalog.photos().count(), before, "held: the file isn't in the catalog yet"); + let mark = s.undo_mark(); + let r = plugin_held::apply(&mut s, held, "Go Far (Job Test)"); + assert_eq!(r["applied"], 2, "the add and the title: {r}"); + assert_eq!(r["failed"].as_array().map(Vec::len), Some(0), "{r}"); + assert_eq!(s.catalog.photos().count(), before + 1, "the file was added"); + assert_eq!(title_of(&mut s, id), "Edited beach"); + assert_eq!(s.undo_mark() - mark, 1, "one undo step for both"); + assert_eq!(s.undo.last().map(|u| u.label.as_str()), Some("Go Far (Job Test)")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), before, "one Undo takes the add back"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_held_library_add_that_fails_at_the_end_is_named_and_the_other_writes_still_apply() { + let dir = std::env::temp_dir().join(format!("held-add-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let mut s = Session::with_demo(); + let made = dir.join("a-edit.jpg"); + std::fs::write(&made, b"not an image").unwrap(); + let id = s.visible_cloned().first().map(|p| p.0).unwrap(); + let mut h = holding(&mut s); + // held with only its shape checked; a demo photo has no file, so the add fails at the end and says so + h.library_add(&json!({"path": made.to_string_lossy(), "from": id.to_string()})).unwrap(); + h.set_metadata(&json!({"ids": [id.to_string()], "title": "With an add"})).unwrap(); + let held = h.held; + let before = s.catalog.photos().count(); + let mark = s.undo_mark(); + let r = plugin_held::apply(&mut s, held, "Go Far (Job Test)"); + assert_eq!(r["applied"], 1, "the title: {r}"); + assert_eq!(r["failed"].as_array().map(Vec::len), Some(1), "the add fails and is named: {r}"); + assert_eq!(s.catalog.photos().count(), before); + assert_eq!(s.undo_mark() - mark, 1, "{r}"); + let _ = std::fs::remove_dir_all(&dir); } /// A host that breaks on a catalog read. diff --git a/crates/engine/src/cmd/plugin_library.rs b/crates/engine/src/cmd/plugin_library.rs index 62cb0b91a5..0f190142e4 100644 --- a/crates/engine/src/cmd/plugin_library.rs +++ b/crates/engine/src/cmd/plugin_library.rs @@ -70,7 +70,7 @@ pub(super) fn checked_source(v: &Value) -> std::result::Result { } /// One photo id: a number, or the decimal string the SDK hands out. -fn id_of(v: Option<&Value>, key: &str) -> std::result::Result { +pub(super) fn id_of(v: Option<&Value>, key: &str) -> std::result::Result { let v = v.ok_or_else(|| format!("missing `{key}`"))?; v.as_u64().or_else(|| v.as_str().and_then(|t| t.trim().parse().ok())).ok_or_else(|| format!("`{key}`: {v} is not an id")) } @@ -184,7 +184,7 @@ pub(super) fn remove(s: &mut Session, p: &Value) -> std::result::Result usize { +pub(super) fn steps_since(s: &Session, mark: u64) -> usize { usize::try_from(s.undo_mark().wrapping_sub(mark)).unwrap_or(usize::MAX).min(s.undo.len()) } diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index ac8939cd97..c8a56d6e44 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -135,6 +135,22 @@ fn engine_ids(params: &Value) -> std::result::Result { Ok(p) } +/// `metadata.setStandard`'s params as `photo.setMeta` takes them: ids as numbers, only the standard fields. +pub(super) fn standard_params(params: &Value) -> std::result::Result { + let params = &engine_ids(params)?; + let ids = params.get("ids").and_then(Value::as_array).filter(|a| !a.is_empty()).ok_or("metadata.setStandard needs `ids`")?; + let mut p = serde_json::Map::new(); + p.insert("ids".into(), Value::Array(ids.clone())); + for (k, v) in params.as_object().into_iter().flatten() { + if STANDARD_FIELDS.contains(&k.as_str()) { + p.insert(k.clone(), v.clone()); + } else if k != "ids" { + return Err(format!("metadata.setStandard: `{k}` is not a standard field")); + } + } + Ok(Value::Object(p)) +} + impl HostApi for SessionHost<'_> { fn catalog(&mut self, method: &str, params: &Value) -> std::result::Result { // lcc-plugins only forwards the read-only methods; check again: this is the boundary @@ -146,18 +162,8 @@ impl HostApi for SessionHost<'_> { } fn set_metadata(&mut self, params: &Value) -> std::result::Result { - let params = &engine_ids(params)?; - let ids = params.get("ids").and_then(Value::as_array).filter(|a| !a.is_empty()).ok_or("metadata.setStandard needs `ids`")?; - let mut p = serde_json::Map::new(); - p.insert("ids".into(), Value::Array(ids.clone())); - for (k, v) in params.as_object().into_iter().flatten() { - if STANDARD_FIELDS.contains(&k.as_str()) { - p.insert(k.clone(), v.clone()); - } else if k != "ids" { - return Err(format!("metadata.setStandard: `{k}` is not a standard field")); - } - } - self.0.execute("photo.setMeta", &Value::Object(p)).map_err(|e| e.to_string()) + let p = standard_params(params)?; + self.0.execute("photo.setMeta", &p).map_err(|e| e.to_string()) } fn library_add(&mut self, params: &Value) -> std::result::Result { @@ -422,7 +428,7 @@ pub(crate) fn install_module( let lib = s.plugin_library.clone(); let r = with_library(&lib, |m| { let plugin = m.load(bytes).map_err(|e| plugin_err(cmd, e))?; - if let Some(e) = filter_has_id(plugin.id()) { + if let Some(e) = filter_has_id(m, plugin.id()) { return Err(bad(cmd, e)); } check(Loaded::Plugin(m, &plugin)).map_err(|e| bad(cmd, e))?; @@ -556,10 +562,20 @@ fn plugin_has_id(m: &Manager, id: &str) -> Option { Some(format!("{id:?} is the id of the installed plug-in \"{name}\"; a pixel filter can't share it (remove the plug-in first)")) } -/// [`plugin_has_id`] the other way round: why a plug-in with `id` can't be installed. -fn filter_has_id(id: &str) -> Option { - let f = crate::filter_plugins::registry().get(id)?; - Some(format!("{id:?} is the id of the installed pixel filter \"{}\"; a plug-in can't share it (remove the filter first)", f.manifest().name)) +/// [`plugin_has_id`] the other way round: why a plug-in with `id` can't be installed. A filter +/// with its id is installed, or a filter module (one the registry refused too) is the file the +/// plug-in would be written to, `.wasm`. A refused module with the id elsewhere in the folder +/// stays: it holds no id and nothing is written over it. +fn filter_has_id(m: &Manager, id: &str) -> Option { + if let Some(f) = crate::filter_plugins::registry().get(id) { + return Some(format!( + "{id:?} is the id of the installed pixel filter \"{}\"; a plug-in can't share it (remove the filter first)", + f.manifest().name + )); + } + let file = m.dir()?.join(format!("{id}.wasm")); + (crate::filter_plugins::filter_file_cached(&file) != crate::filter_plugins::FilterFile::No) + .then(|| format!("{} is a pixel filter module; installing the plug-in {id:?} would replace it (remove the filter first)", file.display())) } /// Filter `f` is older than the installed filter with its id: the error installing it without @@ -625,7 +641,7 @@ fn inspect_file(_: &mut Session, p: &Value) -> Result { }) .or_else(|| m.unloaded(id).map(|(version, grant)| json!({"version": version, "granted": grant, "loaded": false}))); let (missing, version_error, downgrade) = m.install_check(&plugin_manifest); - let conflict = filter_has_id(id); + let conflict = filter_has_id(m, id); let (unknown, dropped) = (&plugin_manifest.unknown_fields, &plugin_manifest.dropped); // who signed it, and whether that's the key pinned for the installed plug-in let pin = m.pin(id); @@ -658,10 +674,23 @@ fn uninstall(s: &mut Session, p: &Value) -> Result { return uninstall_file(s, file, keep_data); } let id = id_param(p, C)?; + let lib = s.plugin_library.clone(); + // a filter and a plug-in with one id (copied into the folder): by id, which would it be? neither + if let Some(filter) = crate::filter_plugins::registry().get(id) { + let plugin_file = with_library(&lib, |m| Ok(plugin_has_id(m, id).map(|_| plugin_file(m, id))))?; + if let Some(plugin_file) = plugin_file { + let filter_file = filter.source().map_or_else(|| "(no file)".to_string(), str::to_string); + return Err(bad( + C, + format!( + "{id:?} is the id of both the pixel filter {filter_file} and the plug-in {plugin_file}; nothing was removed. Remove one by its file: plugin.uninstall {{file}}" + ), + )); + } + } if crate::filter_plugins::uninstall(id).map_err(|e| bad(C, e))? { return Ok(Value::Null); } - let lib = s.plugin_library.clone(); let filter_files = crate::filter_plugins::sources(); with_library(&lib, |m| { // a pixel filter's module fails to load here too: it's only removed through the filter registry @@ -682,12 +711,22 @@ fn uninstall(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// `plugin.uninstall {file}`: a module that didn't load. Another module with its id loaded (or -/// stands in for it): only this file goes. Otherwise it is the plug-in's only module, and the -/// plug-in is removed as by its id, data and all. +/// The module file of plug-in `id`, as a message names it. +fn plugin_file(m: &Manager, id: &str) -> String { + let loaded = m.get(id).and_then(|i| i.path().map(|p| p.display().to_string())); + loaded.or_else(|| m.failed.iter().find(|f| f.id == id).map(|f| f.file.clone())).unwrap_or_else(|| format!("{id}.wasm")) +} + +/// `plugin.uninstall {file}`: a pixel filter's file removes that filter. Otherwise a module that +/// didn't load: another module with its id loaded (or stands in for it): only this file goes. +/// Otherwise it is the plug-in's only module, and the plug-in is removed as by its id, data and all. fn uninstall_file(s: &mut Session, file: &str, keep_data: bool) -> Result { const C: &str = "plugin.uninstall"; let lib = s.plugin_library.clone(); + if let Some(f) = crate::filter_plugins::registry().list().iter().find(|f| f.source() == Some(file)) { + crate::filter_plugins::uninstall(f.id()).map_err(|e| bad(C, e))?; + return Ok(Value::Null); + } with_library(&lib, |m| { let Some(row) = m.failed.iter().find(|f| f.file == file).cloned() else { return Err(bad(C, format!("{file}: no module that didn't load is listed with this file"))); @@ -758,7 +797,9 @@ fn set_grant(_: &mut Session, p: &Value) -> Result { fn log(_: &mut Session, p: &Value) -> Result { const C: &str = "plugin.log"; let id = id_param(p, C)?; - with_manager(|m| m.get(id).map(|i| json!(i.log)).ok_or_else(|| bad(C, format!("no plug-in {id:?} is installed")))) + with_manager(|m| { + m.get(id).map(|i| json!(i.log.iter().map(|l| l.json()).collect::>())).ok_or_else(|| bad(C, format!("no plug-in {id:?} is installed"))) + }) } fn picture(_: &mut Session, p: &Value) -> Result { @@ -1469,6 +1510,8 @@ pub(super) enum Relayed { LibraryAdd, /// `library.remove`. LibraryRemove, + /// A job's held writes, to apply as one undo step ([`super::plugin_held`]). + ApplyHeld(super::plugin_held::Handoff), /// `photo.pixels`: `{photo, longEdge}`, already checked. The session's thread only finds the /// source and leaves it here; the caller decodes it on its own thread. Pixels(std::sync::Arc>>), @@ -1545,6 +1588,7 @@ impl HostRequest { Relayed::SetMetadata => host.set_metadata(&self.params), Relayed::LibraryAdd => host.library_add(&self.params), Relayed::LibraryRemove => host.library_remove(&self.params), + Relayed::ApplyHeld(slot) => super::plugin_held::apply_handoff(host.0, slot), Relayed::Pixels(slot) => relayed_pixels(host.0, &self.params, slot), Relayed::SetCrop => relayed_crop(&mut host, &self.params), Relayed::VirtualCopy => relayed_copy(&mut host, &self.params), @@ -1943,7 +1987,7 @@ pub fn specs() -> Vec { cmd!(query "plugin.grant", "Set Plug-in Permissions", [], None, "{id, grant}: replaces the grant with one that may repeat or leave out what is granted (revoking what it leaves out), never add to it: a permission, host, folder (or its write), program or wider program entry the plug-in doesn't have is an error and changes nothing. Only the user allows, when the plug-in asks or in the Plug-in Manager → granted", always, set_grant), cmd!(query "plugin.revoke", "Revoke Plug-in Permission", [], None, "{id, group: catalog|metadataWrite|libraryAdd|pixels|crop|virtualCopy|network|fs|programs, value?: the host, folder or program id (none: all of the group)}: takes back one permission; the plug-in may ask for it again → granted", always, revoke), cmd!(query "plugin.picture", "Plug-in Picture", [], None, "{id, picture?: header|icon (header), theme?: dark|light (dark)}: a plug-in's or pixel filter's own picture: its header for that interface theme, or its icon (the manifest's `header` and `icon`) → {svg: SVG text | null}", always, picture), - cmd!(query "plugin.log", "Plug-in Log", [], None, "{id} → [lines]", always, log), + cmd!(query "plugin.log", "Plug-in Log", [], None, "{id} → [{source, text}]", always, log), cmd!(query "plugin.commands", "Plug-in Commands", [], None, "{} → [{plugin, pluginName, command, label, menu, dialog, prepare, quickAction, values: what the dialog opens with (the last-run values of fields that remember, else defaults)}] of enabled plug-ins", always, commands), cmd!(query "plugin.prepare", "Prepare Plug-in Command", [], None, "{plugin, command, ids?, source?: {kind: album|smartAlbum|folder|allPhotos|other, id?, name?, path?} (default: the Library source shown)}: asks a command with `prepare` how to run on ids / the selection (others: their dialog as declared) → {dialog: [field + value], error: why the plug-in's own options are missing | null} | {run: args} | {message}; runs nothing", always, prepare), cmd!(query "plugin.run", "Run Plug-in Command", [], None, "{plugin, command, args?: dialog values, ids?, source?: as plugin.prepare, wait?: a job runs to its end}: runs a plug-in menu command on ids / the selection, telling it the Library source it was started from (`source`, default: the one shown) → its result; args given are remembered for its dialog. A command with `prepare` is asked first: a message → {message, ran: false} and nothing runs; its own args are used when `args` is missing; args are checked against its dialog as prepared. A job (a command with `job`) runs on a worker with a row in the activity stack and returns at once → {job: its activity id (activity.list, activity.cancel), running: true, plugin, command}; with `wait: true` it runs here to its end → its result (a cancelled job is an error). Headless sessions answer a job's catalog reads only with `wait`", always, run), @@ -2037,7 +2081,7 @@ pub(crate) mod tests { } /// An export hook plug-in `id` that answers `{seen: true}` (no catalog access). - fn hook_module(id: &str) -> Vec { + pub(crate) fn hook_module(id: &str) -> Vec { let manifest = format!(r#"{{"id":"{id}","name":"Hook","version":"1.0.0","hooks":{{"export":true}},"exportDestinations":[{{"id":"d","name":"D"}}]}}"#); let reply = r#"{"ok":{"seen":true}}"#; @@ -2378,7 +2422,7 @@ pub(crate) mod tests { let r = s.execute("plugin.install", &json!({"path": v11.path(), "allowDowngrade": true})).unwrap(); assert_eq!(r["version"], "1.1.0"); let log = s.execute("plugin.log", &json!({"id": "test.ver"})).unwrap(); - assert!(log.as_array().unwrap().iter().any(|l| l == "downgraded from 1.2.0 to 1.1.0"), "{log}"); + assert!(log.as_array().unwrap().iter().any(|l| l["text"] == "downgraded from 1.2.0 to 1.1.0" && l["source"] == "host"), "{log}"); s.execute("plugin.uninstall", &json!({"id": "test.ver"})).unwrap(); } // The install dialog learns whether a file is exactly what is installed (`installed.same`): @@ -2481,6 +2525,70 @@ pub(crate) mod tests { } } + #[test] + fn a_filter_and_a_plugin_sharing_an_id_are_removed_only_by_their_files() { + let _turn = turn(); + let mut s = Session::with_demo(); + let dir = lcc_testkit::TempDir::new("lcc-engine-id-clash"); + let (filter_file, plugin_file) = (dir.join("a.wasm"), dir.join("b.wasm")); + let bytes = crate::tests_plugin_filters::invert_module("test.clash"); + std::fs::write(&filter_file, &bytes).unwrap(); + std::fs::write(&plugin_file, b"a plug-in that didn't load").unwrap(); + let filter = lcc_filters::Filter::load(&bytes, lcc_filters::Limits::default()).unwrap().with_source(filter_file.display().to_string()); + crate::filter_plugins::registry().install(filter); + let row = lcc_plugins::Failed { + file: plugin_file.display().to_string(), + error: "didn't load".into(), + missing: vec![], + id: "test.clash".into(), + path: Some(plugin_file.clone()), + }; + manager().get_or_insert_with(Manager::in_memory).failed.push(row); + + // by id: which one? neither goes, and the error names both files and `file` + let e = s.execute("plugin.uninstall", &json!({"id": "test.clash"})).unwrap_err().to_string(); + let (still_filter, still_row) = + (crate::filter_plugins::registry().get("test.clash").is_some(), manager().as_ref().unwrap().failed.iter().any(|f| f.id == "test.clash")); + let (a, b) = (filter_file.display().to_string(), plugin_file.display().to_string()); + let kept = (filter_file.exists(), plugin_file.exists()); + // each by its file + let by_plugin = s.execute("plugin.uninstall", &json!({"file": b})); + let after_plugin = (crate::filter_plugins::registry().get("test.clash").is_some(), filter_file.exists(), plugin_file.exists()); + let by_filter = s.execute("plugin.uninstall", &json!({"file": a})); + let after_filter = (crate::filter_plugins::registry().get("test.clash").is_some(), filter_file.exists()); + manager().as_mut().unwrap().failed.retain(|f| f.id != "test.clash"); + crate::filter_plugins::registry().remove("test.clash"); + + assert!(e.contains(&a) && e.contains(&b) && e.contains("file"), "{e}"); + assert!(still_filter && still_row && kept == (true, true), "nothing was removed"); + by_plugin.unwrap(); + assert_eq!(after_plugin, (true, true, false), "the plug-in's file went, the filter stayed"); + by_filter.unwrap(); + assert_eq!(after_filter, (false, false), "then the filter by its file"); + } + + #[test] + fn a_plugin_is_not_installed_over_a_filter_module_in_its_file() { + let _turn = turn(); + let mut s = Session::with_demo(); + let dir = lcc_testkit::TempDir::new("lcc-engine-id-clash-file"); + // a pixel filter copied in under the file name the plug-in would be written to; the manager + // opened on the folder (the filter registry has none of it: it wasn't loaded from there) + let filter_bytes = crate::tests_plugin_filters::invert_module("test.clashfile.filter"); + std::fs::write(dir.join("test.clashfile.plugin.wasm"), &filter_bytes).unwrap(); + let before = manager().replace(Manager::open(&dir).unwrap()); + let manifest = json!({"id": "test.clashfile.plugin", "name": "P", "version": "1.0.0"}); + let module = module_file("clashfile", &manifest); + let r = s.execute("plugin.install", &json!({"path": module.path()})); + let info = s.execute("plugin.inspectFile", &json!({"path": module.path()})); + let left = std::fs::read(dir.join("test.clashfile.plugin.wasm")).unwrap(); + *manager() = before; + let e = r.unwrap_err().to_string(); + assert!(e.contains("test.clashfile.plugin.wasm") && e.contains("pixel filter"), "{e}"); + assert_eq!(left, filter_bytes, "the filter module is left as it was"); + assert!(info.unwrap()["conflict"].is_string(), "the install dialog says so before"); + } + /// A plug-in with `manifest` that answers every call with `reply`, written to `.wasm` in a /// Temp folder of its own, removed when the returned guard is dropped. fn replying_module_file(name: &str, manifest: &Value, reply: &str) -> lcc_testkit::TempFile { @@ -2630,7 +2738,7 @@ pub(crate) mod tests { manager() .get_or_insert_with(Manager::in_memory) .get("test.prog") - .map_or(0, |p| p.log.iter().filter(|l| l.starts_with("program.end failed")).count()) + .map_or(0, |p| p.log.iter().filter(|l| l.text.starts_with("program.end failed")).count()) } /// A run: recorded start with its folder, a row in the activity stack, ✕ ends it without @@ -2742,7 +2850,8 @@ pub(crate) mod tests { } let mut g = manager(); let m = g.get_or_insert_with(Manager::in_memory); - let failed: Vec = m.get("test.prog").unwrap().log.iter().filter(|l| l.starts_with("program.start failed")).cloned().collect(); + let failed: Vec = + m.get("test.prog").unwrap().log.iter().filter(|l| l.text.starts_with("program.start failed")).map(|l| l.text.clone()).collect(); assert_eq!(failed.len(), 2, "each start fails, and the second isn't refused as already running: {failed:?}"); assert!(failed[0].contains("exited at once"), "{failed:?}"); assert!(s.activity.list().iter().all(|t| t.kind != "pluginProgram"), "no row"); @@ -2861,7 +2970,7 @@ pub(crate) mod tests { .unwrap() .log .iter() - .filter(|l| l.starts_with("program.start failed") && l.contains("start the program from a command")) + .filter(|l| l.text.starts_with("program.start failed") && l.text.contains("start the program from a command")) .count(); assert_eq!(refused, 5, "each hook's start is refused: {:?}", m.get("test.prog").unwrap().log); m.uninstall("test.prog").unwrap(); diff --git a/crates/engine/src/cmd/prefs.rs b/crates/engine/src/cmd/prefs.rs index 12a2ef7cf7..e773d2403d 100644 --- a/crates/engine/src/cmd/prefs.rs +++ b/crates/engine/src/cmd/prefs.rs @@ -18,6 +18,7 @@ fn current(s: &Session) -> Value { "cameraDefaults": s.camera_profile_defaults, "rawDecoders": s.raw_decoders, "libraw": crate::raw_decoder::libraw_name(), + "dnglab": crate::raw_decoder::dnglab_name(), "cacheMb": if s.cache_mb == 0 { s.cache_bytes() >> 20 } else { u64::from(s.cache_mb) }, "forgetLocalDays": s.forget_local_days, "persistent": s.library.is_some(), @@ -80,8 +81,8 @@ fn camera_default(s: &mut Session, v: &Value) -> Result<()> { Ok(()) } -/// The raw decoder for a camera: `{camera: "Make Model", decoder: "auto" | "lcc" | "libraw"}`; `auto` (or null) -/// removes the entry. LibRaw may be chosen where it isn't built in (the choice travels with the library); such a +/// The raw decoder for a camera: `{camera: "Make Model", decoder: "auto" | "lcc" | "libraw" | "dnglab"}`; `auto` (or null) +/// removes the entry. LibRaw or dnglab may be chosen where it isn't built in (the choice travels with the library); such a /// camera is read by lcc-raw there ([`crate::raw_decoder`]). fn raw_decoder_choice(s: &mut Session, v: &Value) -> Result<()> { let camera = v.get("camera").and_then(Value::as_str).map(str::trim).unwrap_or_default().to_string(); @@ -91,9 +92,9 @@ fn raw_decoder_choice(s: &mut Session, v: &Value) -> Result<()> { let decoder = match v.get("decoder") { None | Some(Value::Null) => crate::raw_decoder::Decoder::Auto, Some(Value::String(x)) => { - crate::raw_decoder::Decoder::parse(x).ok_or_else(|| bad(ID, format!("decoder must be `auto`, `lcc` or `libraw`, not `{x}`")))? + crate::raw_decoder::Decoder::parse(x).ok_or_else(|| bad(ID, format!("decoder must be `auto`, `lcc`, `libraw` or `dnglab`, not `{x}`")))? } - Some(other) => return Err(bad(ID, format!("decoder must be `auto`, `lcc` or `libraw`, not {other}"))), + Some(other) => return Err(bad(ID, format!("decoder must be `auto`, `lcc`, `libraw` or `dnglab`, not {other}"))), }; let key = crate::raw_decoder::camera_key(&camera); s.raw_decoders.retain(|k, _| crate::raw_decoder::camera_key(k) != key); @@ -305,7 +306,7 @@ pub fn specs() -> Vec { "Catalog Preferences", [], None, - "{import?: {rawPreset?: presetId|\"default\", otherPreset?: presetId|\"default\", perCamera?: bool, cameras?: [{camera: \"Make Model\", preset: presetId|null}], copyright?: text, creator?: text (given to imported photos without one), showOnCard?: bool (open the import review when a camera or card is connected), constrainCrop?: bool (new photos start with Constrain Crop on; default true), denoiseAboveIso?: ISO | 0 | null (AI Denoise on for new raw photos shot at this ISO or above, their pictures made in the background; 0 / null = off), importDuplicates?: bool (Synchronize Folder brings in files whose content a photo already has, as photos of their own: \"Don't import files already in the library\" unticked, as the dialog last left it; off by default; `folder.synchronize` takes it unless given `importDuplicates`)}, camera?: {camera, preset?, remove?: bool}, cameraDefault?: {camera: \"Make Model\"|\"*\" (the default camera profile photos of that camera start from when they choose none, ahead of the camera's active imported profile and its calibration's default look; \"*\" = every camera), profile?: \"lc\" (the app's own colour) | dcpId (camera.listDcp) | calId | null (remove the entry)}, rawDecoder?: {camera: \"Make Model\", decoder: \"auto\" (lcc-raw, LibRaw for the variants it can't read) | \"lcc\" (lcc-raw only) | \"libraw\" (LibRaw, lcc-raw when it fails or isn't built in) | null (= auto)}, cacheMb?: n (0 = default), forgetLocalDays?: n (forget untouched Local photos of folders not browsed for n days; 0 = never)}: develop defaults applied on import (raws / other images / per camera), the default camera profile per camera model and the thumbnail cache size, saved with the library → {xmp, import, cameraDefaults, rawDecoders, libraw (the LibRaw build in this app, null when it has none), cacheMb, forgetLocalDays, persistent}", + "{import?: {rawPreset?: presetId|\"default\", otherPreset?: presetId|\"default\", perCamera?: bool, cameras?: [{camera: \"Make Model\", preset: presetId|null}], copyright?: text, creator?: text (given to imported photos without one), showOnCard?: bool (open the import review when a camera or card is connected), constrainCrop?: bool (new photos start with Constrain Crop on; default true), denoiseAboveIso?: ISO | 0 | null (AI Denoise on for new raw photos shot at this ISO or above, their pictures made in the background; 0 / null = off), importDuplicates?: bool (Synchronize Folder brings in files whose content a photo already has, as photos of their own: \"Don't import files already in the library\" unticked, as the dialog last left it; off by default; `folder.synchronize` takes it unless given `importDuplicates`)}, camera?: {camera, preset?, remove?: bool}, cameraDefault?: {camera: \"Make Model\"|\"*\" (the default camera profile photos of that camera start from when they choose none, ahead of the camera's active imported profile and its calibration's default look; \"*\" = every camera), profile?: \"lc\" (the app's own colour) | dcpId (camera.listDcp) | calId | null (remove the entry)}, rawDecoder?: {camera: \"Make Model\", decoder: \"auto\" (lcc-raw, then LibRaw and dnglab for the variants it can't read) | \"lcc\" (lcc-raw only) | \"libraw\" (LibRaw, lcc-raw when it fails or isn't built in) | \"dnglab\" (dnglab's rawler, lcc-raw when it fails or isn't built in) | null (= auto)}, cacheMb?: n (0 = default), forgetLocalDays?: n (forget untouched Local photos of folders not browsed for n days; 0 = never)}: develop defaults applied on import (raws / other images / per camera), the default camera profile per camera model and the thumbnail cache size, saved with the library → {xmp, import, cameraDefaults, rawDecoders, libraw / dnglab (the LibRaw / dnglab build in this app, null when it has none), cacheMb, forgetLocalDays, persistent}", always, prefs ), diff --git a/crates/engine/src/cmd/preset_files.rs b/crates/engine/src/cmd/preset_files.rs index 3d4d606554..9172cc3912 100644 --- a/crates/engine/src/cmd/preset_files.rs +++ b/crates/engine/src/cmd/preset_files.rs @@ -63,8 +63,8 @@ fn import(s: &mut Session, p: &Value) -> Result { None => {} } match super::export_preset_files::parse_bytes(&f, &bytes) { - Some(Ok(list)) => { - super::export_preset_files::gather(&mut export_found, list, &f, &mut failed); + Some(Ok(parsed)) => { + super::export_preset_files::gather(&mut export_found, parsed, &f, &mut failed); other_kind = true; } Some(Err(e)) => { diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 096b4edfc7..cefea0166f 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -1015,6 +1015,7 @@ fn smart(s: &mut Session, p: &Value) -> Result { let what = if discard { "discarding smart previews" } else { "smart previews" }; let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() }); s.preview_build = Some(state.clone()); + s.smart_scan.after = Some(state.clone()); let task = task_for(s, &state); let st = state.clone(); std::thread::Builder::new() @@ -1030,6 +1031,7 @@ fn smart(s: &mut Session, p: &Value) -> Result { return Ok(state.json()); } let r = smart_run(&dir, custom, discard, jobs, None).map_err(|e| bad(C, e))?; + s.scan_smart_previews(); Ok( json!({"built": r.built, "repaired": r.repaired, "refreshed": r.refreshed, "staleKept": r.stale_kept, "removed": r.removed, "failed": r.failed}), ) @@ -1142,6 +1144,7 @@ fn smart_location(s: &mut Session, p: &Value) -> Result { let (moved, failed) = crate::smart::migrate(¤t, &new_dir, existing); s.smart_previews_dir = custom; s.media.smart_dir = Some(new_dir); + s.scan_smart_previews(); s.save_prefs()?; let mut r = location_json(s); r["handled"] = json!(moved); @@ -1149,6 +1152,83 @@ fn smart_location(s: &mut Session, p: &Value) -> Result { Ok(r) } +/// What decides when the catalog's smart preview set ([`lcc_catalog::Catalog::set_smart_previews`]) is made again: the +/// folder listing on its worker thread, and the background build whose end asks for a new one. +#[derive(Default)] +pub struct SmartScan { + listing: Option>>, + /// Another listing was asked for while one ran: that one's answer is out of date (another folder, or built since). + again: bool, + pub(crate) after: Option>, +} + +impl Session { + /// Tell the catalog which photos have a smart preview file now, listing the folder here (a command's own answer + /// has to be right when it returns). A photo's proxy is named by its content ([`crate::smart::file_name`]), so a + /// name in the folder is enough: the header isn't read. + pub fn scan_smart_previews(&mut self) { + // a listing still running answers an older question + self.smart_scan.listing = None; + self.smart_scan.again = false; + let names = self.media.smart_dir.as_deref().map(crate::smart::names).unwrap_or_default(); + self.apply_smart_names(&names); + } + + /// The same on a worker thread (the library's open, the end of a background build): a smart previews folder on a + /// drive that answers slowly never holds the screen. [`Session::poll_smart_scan`] applies the result. + pub fn start_smart_scan(&mut self) { + // no folder (a library off disk), or no threads (the web build): list here + #[cfg(target_arch = "wasm32")] + { + self.scan_smart_previews(); + } + #[cfg(not(target_arch = "wasm32"))] + { + let Some(dir) = self.media.smart_dir.clone() else { + self.scan_smart_previews(); + return; + }; + if self.smart_scan.listing.is_some() { + self.smart_scan.again = true; + return; + } + match std::thread::Builder::new().name("lc-smart-scan".into()).spawn(move || crate::smart::names(&dir)) { + Ok(h) => self.smart_scan.listing = Some(h), + Err(e) => { + log::warn!("smart preview listing could not start: {e}"); + self.scan_smart_previews(); + } + } + } + } + + /// Apply a finished listing, and start the next one when the background build that asked for it has ended + /// (cheap; every frame, from [`Session::finishing_tick`]). + pub fn poll_smart_scan(&mut self) { + if self.smart_scan.listing.as_ref().is_some_and(|h| h.is_finished()) + && let Some(h) = self.smart_scan.listing.take() + { + match h.join() { + Ok(_) if std::mem::take(&mut self.smart_scan.again) => self.start_smart_scan(), + Ok(names) => self.apply_smart_names(&names), + Err(_) => { + log::warn!("smart preview listing failed"); + self.scan_smart_previews(); + } + } + } + if self.smart_scan.after.as_ref().is_some_and(|b| b.finished.load(Ordering::Relaxed)) { + self.smart_scan.after = None; + self.start_smart_scan(); + } + } + + fn apply_smart_names(&mut self, names: &std::collections::HashSet) { + let ids = self.catalog.photos().filter(|p| !names.is_empty() && names.contains(&crate::smart::file_name(p))).map(|p| p.id).collect(); + self.catalog.set_smart_previews(ids); + } +} + /// Whether photo `id` has a smart preview. pub fn has_smart_preview(s: &Session, id: lcc_catalog::PhotoId) -> bool { match (&s.media.smart_dir, s.catalog.photo(id)) { diff --git a/crates/engine/src/cmd/publish.rs b/crates/engine/src/cmd/publish.rs index 18cdeb7680..f91cc25a4f 100644 --- a/crates/engine/src/cmd/publish.rs +++ b/crates/engine/src/cmd/publish.rs @@ -28,8 +28,23 @@ fn load(s: &Session, c: &str) -> Result<(PathBuf, PublishConfig)> { Ok((dir, cfg)) } -fn save(dir: &std::path::Path, cfg: &PublishConfig, c: &str) -> Result<()> { - cfg.save(dir).map_err(|e| bad(c, e.to_string())) +/// Write `publish.json`, and tell the catalog the services' names (the Published Via rule matches on them). +fn save(s: &mut Session, dir: &std::path::Path, cfg: &PublishConfig, c: &str) -> Result<()> { + cfg.save(dir).map_err(|e| bad(c, e.to_string()))?; + s.catalog.set_publish_services(service_names(cfg)); + Ok(()) +} + +fn service_names(cfg: &PublishConfig) -> std::collections::BTreeMap { + cfg.services.iter().map(|x| (x.id.clone(), x.name.clone())).collect() +} + +/// Tell the catalog the names of the library's publish services, from its `publish.json` (none when the library +/// isn't on disk or the file can't be read: Published Via then matches nothing). +pub(crate) fn refresh_service_names(s: &mut Session) { + let names = + s.library.as_ref().filter(|l| l.on_disk).and_then(|l| PublishConfig::load(&l.dir).ok()).map(|c| service_names(&c)).unwrap_or_default(); + s.catalog.set_publish_services(names); } /// `service`: a service id, or its name. @@ -153,7 +168,7 @@ fn create_service(s: &mut Session, p: &Value) -> Result { s.commit("New Publish Service", Op::AddAlbum { album })?; let id = cfg.alloc_id(); cfg.services.push(ServiceConfig { id: id.clone(), kind, name, settings, export, set: Some(set), collections: Vec::new() }); - save(&dir, &cfg, C)?; + save(s, &dir, &cfg, C)?; Ok(cfg.service(&id).map(|x| service_json(&s.catalog, x)).unwrap_or(Value::Null)) } @@ -184,7 +199,7 @@ fn update_service(s: &mut Session, p: &Value) -> Result { if let Some(x) = cfg.service_mut(&id) { *x = next; } - save(&dir, &cfg, C)?; + save(s, &dir, &cfg, C)?; Ok(cfg.service(&id).map(|x| service_json(&s.catalog, x)).unwrap_or(Value::Null)) } @@ -205,7 +220,7 @@ fn delete_service(s: &mut Session, p: &Value) -> Result { s.commit("Delete Publish Service", Op::Batch { ops })?; } cfg.services.retain(|x| x.id != id); - save(&dir, &cfg, C)?; + save(s, &dir, &cfg, C)?; services(s) } @@ -252,7 +267,7 @@ fn create_collection(s: &mut Session, p: &Value) -> Result { if let Some(x) = cfg.service_mut(&id) { x.collections.push(CollectionConfig { album, folder, sidecars: Default::default() }); } - save(&dir, &cfg, C)?; + save(s, &dir, &cfg, C)?; status_json(s, &cfg, album) } @@ -281,7 +296,7 @@ fn delete_collection(s: &mut Session, p: &Value) -> Result { if let Some(x) = cfg.service_mut(&svc.id) { x.collections.retain(|c| c.album != coll.album); } - save(&dir, &cfg, C)?; + save(s, &dir, &cfg, C)?; services(s) } diff --git a/crates/engine/src/cmd/publish_tests.rs b/crates/engine/src/cmd/publish_tests.rs index e0246e289d..b129dc7365 100644 --- a/crates/engine/src/cmd/publish_tests.rs +++ b/crates/engine/src/cmd/publish_tests.rs @@ -453,7 +453,7 @@ fn plugin_publish_service_gets_account_collection_and_metadata_and_answers_comme assert_eq!(r["runs"][0]["published"].as_array().unwrap().len(), 1, "{r}"); let log = s.execute("plugin.log", &json!({"id": "test.flickrish"})).unwrap(); - let upload = log.as_array().unwrap().iter().filter_map(Value::as_str).find(|l| l.contains("publish.upload")).unwrap().to_string(); + let upload = log.as_array().unwrap().iter().filter_map(|l| l["text"].as_str()).find(|l| l.contains("publish.upload")).unwrap().to_string(); for want in ["\"user\":\"ann\"", "\"name\":\"My Site\"", "\"name\":\"Harbours\"", "Harbour at dusk", "\"caption\":\"Boats\"", "\"sea\""] { assert!(upload.contains(want), "{want} missing from {upload}"); } @@ -462,14 +462,20 @@ fn plugin_publish_service_gets_account_collection_and_metadata_and_answers_comme assert_eq!(c["comments"][0]["author"], "Ann", "{c}"); assert_eq!(c["comments"][0]["text"], "Lovely light"); let log = s.execute("plugin.log", &json!({"id": "test.flickrish"})).unwrap(); - assert!(log.as_array().unwrap().iter().filter_map(Value::as_str).any(|l| l.contains("publish.comments") && l.contains("remote-1")), "{log}"); + assert!( + log.as_array().unwrap().iter().filter_map(|l| l["text"].as_str()).any(|l| l.contains("publish.comments") && l.contains("remote-1")), + "{log}" + ); // taking the photo out removes it through the plug-in, with the same remote id s.execute("album.removePhotos", &json!({"id": coll, "ids": [ids[0]]})).unwrap(); let r = s.execute("publish.run", &json!({"collection": coll})).unwrap(); assert_eq!(r["runs"][0]["removed"].as_array().map(Vec::len), Some(1), "{r}"); let log = s.execute("plugin.log", &json!({"id": "test.flickrish"})).unwrap(); - assert!(log.as_array().unwrap().iter().filter_map(Value::as_str).any(|l| l.contains("publish.delete") && l.contains("remote-1")), "{log}"); + assert!( + log.as_array().unwrap().iter().filter_map(|l| l["text"].as_str()).any(|l| l.contains("publish.delete") && l.contains("remote-1")), + "{log}" + ); } #[cfg(not(target_arch = "wasm32"))] @@ -477,3 +483,86 @@ fn s_install(bytes: &[u8]) { let mut g = crate::cmd::plugins::manager(); g.get_or_insert_with(lcc_plugins::Manager::in_memory).install_bytes(bytes, None, false).unwrap(); } + +/// The photos a smart collection holds, sorted. +fn held(s: &Session, smart: u64) -> Vec { + let mut v: Vec = s.catalog.photos().filter(|p| s.catalog.album_contains(lcc_catalog::AlbumId(smart), p)).map(|p| p.id.0).collect(); + v.sort(); + v +} + +fn smart(s: &mut Session, name: &str, field: &str, op: &str, value: &str) -> u64 { + let rules = json!({"ruleSet": {"match": "all", "rules": [{"field": field, "op": op, "value": value}]}}); + s.execute("album.createSmart", &json!({"name": name, "rules": rules})).unwrap()["id"].as_u64().unwrap() +} + +/// The Published Via and Publish Collection criteria follow the publish links, two services apart; a +/// renamed service matches under its new name, and a photo taken out of its collection or a service that is +/// deleted stops matching. +#[test] +fn smart_collections_match_publish_services_and_collections() { + let (root, mut s) = library("smart"); + let ids = import(&mut s, &root, 3); + let export = json!({"format": "jpeg", "longEdge": 20, "naming": "{name}"}); + for (name, dir) in [("Disk A", "a"), ("Disk B", "b")] { + let dir = root.join(dir); + s.execute("publish.createService", &json!({"name": name, "dir": dir.to_string_lossy(), "export": export})).unwrap(); + } + let collection = |s: &mut Session, service: &str, name: &str, photos: &[u64]| { + s.execute("library.select", &json!({"ids": photos})).unwrap(); + let c = s.execute("publish.createCollection", &json!({"service": service, "name": name, "addSelected": true})).unwrap(); + c["collection"].as_u64().unwrap() + }; + let web = collection(&mut s, "Disk A", "Web", &[ids[0], ids[1]]); + collection(&mut s, "Disk B", "Print", &[ids[1]]); + + let via_a = smart(&mut s, "via A", "publishedVia", "is", "Disk A"); + let via_b = smart(&mut s, "via B", "publishedVia", "contains", "disk b"); + let in_web = smart(&mut s, "in Web", "publishCollection", "is", "Web"); + let in_print = smart(&mut s, "in Print", "publishCollection", "contains", "print"); + let not_a = smart(&mut s, "not via A", "publishedVia", "isNot", "Disk A"); + let nowhere = smart(&mut s, "unknown", "publishedVia", "is", "Nowhere"); + // nothing is published yet: the links appear with the first run + assert_eq!(held(&s, via_a), Vec::::new()); + for service in ["Disk A", "Disk B"] { + s.execute("publish.run", &json!({"service": service})).unwrap(); + } + assert_eq!(held(&s, via_a), vec![ids[0], ids[1]]); + assert_eq!(held(&s, via_b), vec![ids[1]]); + assert_eq!(held(&s, in_web), vec![ids[0], ids[1]]); + assert_eq!(held(&s, in_print), vec![ids[1]]); + assert_eq!(held(&s, not_a), vec![ids[2]], "a photo in two services isn't 'not via' one of them"); + assert_eq!(held(&s, nowhere), Vec::::new(), "an unknown name matches nothing"); + + // a rename follows: the new name matches, the old one no longer does + s.execute("publish.updateService", &json!({"service": "Disk A", "name": "Archive"})).unwrap(); + assert_eq!(held(&s, via_a), Vec::::new()); + let via_archive = smart(&mut s, "via Archive", "publishedVia", "is", "Archive"); + assert_eq!(held(&s, via_archive), vec![ids[0], ids[1]]); + + // the link decides, not the collection: taken out, a photo matches until the run removes its link + s.execute("album.removePhotos", &json!({"id": web, "ids": [ids[1]]})).unwrap(); + assert_eq!(held(&s, in_web), vec![ids[0], ids[1]]); + s.execute("publish.run", &json!({"collection": web})).unwrap(); + assert_eq!(held(&s, in_web), vec![ids[0]]); + assert_eq!(held(&s, via_archive), vec![ids[0]]); + assert_eq!(held(&s, via_b), vec![ids[1]], "the other service's link is kept"); + + // a renamed collection matches under its new name + s.execute("album.rename", &json!({"id": web, "name": "Gallery"})).unwrap(); + assert_eq!(held(&s, in_web), Vec::::new()); + let in_gallery = smart(&mut s, "in Gallery", "publishCollection", "is", "Gallery"); + assert_eq!(held(&s, in_gallery), vec![ids[0]]); + + // a deleted service takes its links, and names, with it + s.execute("publish.deleteService", &json!({"service": "Disk B"})).unwrap(); + assert_eq!(held(&s, via_b), Vec::::new()); + assert_eq!(held(&s, in_print), Vec::::new()); + + // names survive a reopen (they are read from publish.json, not remembered) + s.close_library().unwrap(); + drop(s); + let mut s = Session::new().with_fs(); + s.open_library(root.join("lib"), false).unwrap(); + assert_eq!(held(&s, via_archive), vec![ids[0]]); +} diff --git a/crates/engine/src/cmd/web.rs b/crates/engine/src/cmd/web.rs index 5671da13e4..b74360863b 100644 --- a/crates/engine/src/cmd/web.rs +++ b/crates/engine/src/cmd/web.rs @@ -698,6 +698,34 @@ mod tests { } } + /// A gallery's images carry the metadata export's own policy gives their setting (FX-241): thumbnails none, large + /// images everything under "All", and under "Copyright only" the copyright alone with the location removed. + #[test] + fn gallery_images_follow_the_export_metadata_policy() { + use lcc_webgallery::{GallerySettings, MetadataMode}; + let (_dir, mut s) = session("metadata-policy"); + let id = s.visible()[0]; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.copyright = "GalleryCopyright".into(); + meta.title = "GalleryTitle".into(); + meta.gps = Some((48.8566, 2.3522)); + meta.city = "GalleryCity".into(); + s.catalog.apply(lcc_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let photo = s.catalog.photo(id).unwrap().clone(); + for mode in [MetadataMode::All, MetadataMode::CopyrightOnly] { + let mut g = GallerySettings::default(); + g.output.metadata = mode; + let all = mode == MetadataMode::All; + // thumbnails carry none, whatever the setting + let thumb = crate::export::export_metadata(&photo, &s.catalog, &super::image_options(&g, 100, false)); + assert!(thumb.is_none(), "{mode:?}: a thumbnail carries metadata"); + let large = crate::export::export_metadata(&photo, &s.catalog, &super::image_options(&g, 400, true)).expect("the large image's metadata"); + assert_eq!(large.copyright.as_deref(), Some("GalleryCopyright"), "{mode:?}"); + assert_eq!(large.title.is_some(), all, "{mode:?}: the title"); + assert_eq!((large.gps.is_some(), large.city.is_some()), (all, all), "{mode:?}: the position and place"); + } + } + #[test] fn a_server_that_cannot_be_reached_fails_before_anything_renders() { let (_dir, mut s) = session("upload-first"); diff --git a/crates/engine/src/colour_export.rs b/crates/engine/src/colour_export.rs index 7fe4839f09..c0435dd747 100644 --- a/crates/engine/src/colour_export.rs +++ b/crates/engine/src/colour_export.rs @@ -83,7 +83,8 @@ pub fn look_cube(settings: &DevelopSettings, title: &str) -> Result Result { + self.run_with_row_and(activity, &mut |_| {}) + } + + /// [`Prepared::run_with_row`], calling `after_photo(done)` once the row shows `done` photos finished. + fn run_with_row_and(self, activity: &crate::activity::Activity, after_photo: &mut dyn FnMut(usize)) -> Result { + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let row = activity.start("export", "Exporting contact sheet", crate::activity::Cancel::Flag(cancel.clone())); + let total = self.items.len() as u64; + row.progress(0, total); + self.run(&mut |done, name| { + row.progress(done as u64, total); + row.detail(name); + after_photo(done); + !cancel.load(std::sync::atomic::Ordering::Relaxed) + }) + } + /// Cancellation produces no partial document; callers write only after this succeeds. pub fn run(self, progress: &mut dyn FnMut(usize, &str) -> bool) -> Result { let l = self.options.layout()?; @@ -303,6 +323,46 @@ mod tests { assert!(prepare(&mut s, &p).unwrap().run(&mut |_, _| false).is_err()); } + /// FX-217: the command's run holds one row of kind `export` with a real cancel: it shows the photos done, its + /// ✕ (`activity.cancel`) stops the run before the next photo with no document, and it ends with the run. + #[test] + fn a_run_with_a_row_shows_progress_and_a_cancel_stops_it() { + let mut s = Session::with_demo(); + let ids: Vec<_> = s.catalog.photos().take(10).map(|p| p.id.0).collect(); + let p = json!({"ids": ids, "columns": 3, "rows": 3, "captions": false}); + let activity = s.activity.clone(); + // uncancelled: the row is there, cancellable, counting the photos; and gone afterwards + let mut seen = Vec::new(); + let doc = prepare(&mut s, &p) + .unwrap() + .run_with_row_and(&activity, &mut |done| { + let rows = activity.list(); + assert_eq!(rows.len(), 1, "one row while it runs"); + assert!(rows[0].kind == "export" && rows[0].label == "Exporting contact sheet" && rows[0].cancellable, "{:?}", rows[0]); + seen.push((done, rows[0].done, rows[0].total)); + }) + .unwrap(); + assert_eq!(doc.photos, 10); + assert_eq!(seen, (0..=10).map(|i| (i, i as u64, 10)).collect::>()); + assert!(activity.list().is_empty(), "the row ends with the run"); + // cancelled from the row after the third photo: the run stops before the fourth, with no document + let mut photos_started = 0; + let err = prepare(&mut s, &p) + .unwrap() + .run_with_row_and(&activity, &mut |done| { + photos_started = done; + if done == 3 { + let id = activity.list()[0].id; + activity.cancel(id).unwrap(); + } + }) + .err() + .expect("a cancelled sheet is an error"); + assert!(err.contains("cancelled"), "{err}"); + assert_eq!(photos_started, 3, "no photo is rendered after the cancel"); + assert!(activity.list().is_empty(), "a cancelled run ends its row too"); + } + fn first_page(bytes: &[u8]) -> Rgba8 { let start = bytes.windows(2).position(|v| v == [0xff, 0xd8]).unwrap(); let end = bytes[start..].windows(2).position(|v| v == [0xff, 0xd9]).unwrap() + start + 2; diff --git a/crates/engine/src/device_sync/tests.rs b/crates/engine/src/device_sync/tests.rs index 55babf1b07..986a95121c 100644 --- a/crates/engine/src/device_sync/tests.rs +++ b/crates/engine/src/device_sync/tests.rs @@ -70,13 +70,23 @@ fn pair_up(a: &mut Session, b: &mut Session) { b.execute("sync.clearPairing", &json!({})).unwrap(); } -fn lan_skipped() -> bool { - // LAN discovery times out on the macOS CI runner; checked in person on real Macs instead - if cfg!(target_os = "macos") && std::env::var_os("CI").is_some() { - lcc_testkit::skip!(System, "LAN discovery on the macOS CI runner (tested in person)"); - return true; - } - false +/// A test that starts a sync session opens sockets on every interface, which macOS asks about for each +/// rebuilt test binary: it must open with `lcc_testkit::lan_tests`, so one setting skips all of them. +#[test] +fn every_test_that_starts_the_service_checks_the_lan_opt_out() { + const STARTS: [&str; 7] = ["session(", "pair_up(", "\"sync.find\"", "\"sync.pair\"", "\"sync.setup\"", "\"sync.rename\"", "\"sync.answer\""]; + let source = include_str!("tests.rs"); + // each test: from its attribute to the closing brace at the start of a line, whatever sits between (doc + // comments, more attributes, `pub`/`async`) + let unchecked: Vec<&str> = source + .split(concat!("#[", "test]")) + .skip(1) + .map(|t| t.split("\n}\n").next().unwrap_or(t)) + .filter(|t| !t.contains("fn every_test_that_starts_the_service_checks_the_lan_opt_out")) + .filter(|t| STARTS.iter().any(|s| t.contains(s)) && !t.contains("lan_tests(")) + .filter_map(|t| t.split("fn ").nth(1)?.split('(').next()) + .collect(); + assert!(unchecked.is_empty(), "these tests start the service without `if !lcc_testkit::lan_tests(..) {{ return; }}`: {unchecked:?}"); } fn collection<'a>(v: &'a Value, name: &str) -> Option<&'a Value> { @@ -88,7 +98,7 @@ fn collection<'a>(v: &'a Value, name: &str) -> Option<&'a Value> { /// added there reaches the owner with its file; what the owner doesn't allow stays home. #[test] fn a_shared_collection_brings_photos_files_and_edits_both_ways() { - if lan_skipped() { + if !lcc_testkit::lan_tests(true) { return; } let dir = lcc_testkit::TempDir::new("lcc-engine-device-sync"); @@ -190,6 +200,10 @@ fn a_shared_collection_brings_photos_files_and_edits_both_ways() { /// Cancelling with no pairing under way (or no service at all) is harmless and answers the status. #[test] fn cancel_pairing_without_a_pairing_is_harmless() { + // `sync.find` starts the service + if !lcc_testkit::lan_tests(false) { + return; + } let dir = lcc_testkit::TempDir::new("lcc-engine-sync-cancel"); let mut a = session(&dir, "a", 31000 + (std::process::id() % 2000) as u16); let v = a.execute("sync.cancelPairing", &json!({})).unwrap(); diff --git a/crates/engine/src/errors.rs b/crates/engine/src/errors.rs index fb0fd0f926..24f2dcc99a 100644 --- a/crates/engine/src/errors.rs +++ b/crates/engine/src/errors.rs @@ -27,6 +27,10 @@ pub enum AiModel { Scene, /// Depth Anything V2 Small, behind Depth Range masks (`ai.models.download {"id": "depth"}`). Depth, + /// The CLIP image-text embedding model (`ml.models.download`, used by semantic search and AI Auto Orient). + Clip, + /// The 4-way orientation classifier head fitted on top of CLIP (`ml.orientation.fit`, used by AI Auto Orient). + OrientationClassifier, } /// The kind of an [`EngineError`] (or of an error a frontend raised itself: [`ErrorKind::Other`]). diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index fd807cd4c7..cfad974ec0 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -166,8 +166,101 @@ impl ExportFormat { /// Formats whose exports keep a transparent source's alpha (straight in PNG and WebP, /// associated in TIFF); the others composite it onto white (issue #2976). pub fn keeps_alpha(self) -> bool { - matches!(self, Self::Png | Self::Tiff | Self::Webp) + self.caps().keeps_alpha } + + /// What the format does with bit depth, alpha and HDR: the one table every question about it is answered from + /// ([`ExportOptions::effective_depth`], [`ExportOptions::bit_depths`], [`ExportOptions::hdr_output`], + /// [`ExportOptions::gain_map`], [`ExportOptions::effective_space`], [`ExportFormat::keeps_alpha`], the stored + /// `bitDepth` a format lacks, the encoders' alpha) (FX-236). + fn caps(self) -> FormatCaps { + use OutputDepth::{F32Linear, U8, U16}; + const D8: &[(u8, &str)] = &[(8, "8-bit")]; + match self { + Self::Jpeg => FormatCaps { depths: D8, samples: |_| U8, keeps_alpha: false, hdr: HdrKind::GainMap, hdr_rec2020: false }, + Self::Webp => FormatCaps { depths: D8, samples: |_| U8, keeps_alpha: true, hdr: HdrKind::None, hdr_rec2020: false }, + Self::Original | Self::Dng => FormatCaps { depths: D8, samples: |_| U8, keeps_alpha: false, hdr: HdrKind::None, hdr_rec2020: false }, + Self::Png => FormatCaps { + depths: &[(8, "8-bit"), (16, "16-bit")], + samples: |d| if matches!(d, Some(16 | 32)) { U16 } else { U8 }, + keeps_alpha: true, + hdr: HdrKind::Float, + hdr_rec2020: true, + }, + Self::Tiff => FormatCaps { + depths: &[(16, "16-bit"), (8, "8-bit"), (32, "32-bit float")], + samples: |d| match d { + Some(8) => U8, + Some(32) => F32Linear, + _ => U16, + }, + keeps_alpha: true, + hdr: HdrKind::FloatAt32, + hdr_rec2020: false, + }, + Self::Psd => FormatCaps { + depths: &[(16, "16-bit"), (8, "8-bit")], + samples: |d| if d == Some(8) { U8 } else { U16 }, + keeps_alpha: false, + hdr: HdrKind::None, + hdr_rec2020: false, + }, + Self::RenderedDng => { + FormatCaps { depths: &[(16, "16-bit float")], samples: |_| F32Linear, keeps_alpha: false, hdr: HdrKind::Float, hdr_rec2020: false } + } + Self::Exr => FormatCaps { + depths: &[(16, "16-bit half float"), (32, "32-bit float")], + samples: |_| F32Linear, + keeps_alpha: false, + hdr: HdrKind::Float, + hdr_rec2020: false, + }, + Self::Avif => FormatCaps { + depths: &[(8, "8-bit"), (10, "10-bit")], + samples: |d| if matches!(d, Some(10 | 16 | 32)) { U16 } else { U8 }, + keeps_alpha: false, + hdr: HdrKind::GainMapOrFloat, + hdr_rec2020: true, + }, + Self::Jxl => FormatCaps { + depths: &[(8, "8-bit"), (16, "16-bit")], + samples: |d| if matches!(d, Some(10 | 16 | 32)) { U16 } else { U8 }, + keeps_alpha: false, + hdr: HdrKind::GainMapOrFloat, + hdr_rec2020: true, + }, + } + } +} + +/// One row of [`ExportFormat::caps`]. +struct FormatCaps { + /// The bit depths the format offers (value, label); the first is its default. + depths: &'static [(u8, &'static str)], + /// The sample format a bit depth request is written with when the file is not HDR (a request the format doesn't + /// offer falls back to the closest it writes). + samples: fn(Option) -> OutputDepth, + /// Whether the export keeps a transparent source's alpha. + keeps_alpha: bool, + /// How the format writes HDR, when asked. + hdr: HdrKind, + /// Whether an HDR file is written in Rec. 2020 (single layer; a gain map's base image stays in the ordinary space). + hdr_rec2020: bool, +} + +/// How a format writes HDR ([`FormatCaps::hdr`]). +#[derive(Clone, Copy, PartialEq, Eq)] +enum HdrKind { + /// No HDR output: `hdr` is ignored. + None, + /// An SDR base image with a gain map, always (JPEG). + GainMap, + /// A float HDR render (PNG as PQ, OpenEXR, Render to DNG). + Float, + /// A float HDR render at 32 bits only (TIFF). + FloatAt32, + /// A gain map or a single HDR image, as [`ExportOptions::hdr_mode`] says (AVIF, JPEG XL). + GainMapOrFloat, } /// How the output size is chosen (see [`Resize`]). @@ -278,8 +371,10 @@ pub enum Conflict { /// Add `-2`, `-3`, … to the name. #[default] Unique, + /// Replace a file from before the export; a name the export itself wrote gets a number. Overwrite, - /// Leave the existing file and skip the photo. + /// Leave the existing file and skip the photo; a name the export itself wrote gets a number (and is skipped + /// when a file from before has that one). Skip, } @@ -346,6 +441,9 @@ pub fn subfolder_problem(name: &str) -> Option<&'static str> { if t.chars().all(|c| c == '.') { return Some("the subfolder can't be `.` or `..`"); } + if t.len() > crate::rename::MAX_NAME_BYTES { + return Some("the subfolder name is longer than a file system takes (255 bytes)"); + } // a name every file system takes: no character Windows refuses (`* ? " < > |`), no leading or trailing dot or space, and no // device name Windows reserves (`CON`, `NUL`, `COM1`…, also before a dot), as for a file name if portable_stem(t) != t { @@ -1025,10 +1123,29 @@ impl Default for ExportOptions { } } +/// The refusal of a command that runs a whole export on the calling thread while another export is in flight: the +/// desktop app's own exports run on workers and hold a row of kind `export`, and a second job writing to the same +/// folders at once would only race the first (the same rule as the front end's `an export is already running`). +pub fn ensure_none_running(activity: &crate::activity::Activity) -> Result<(), String> { + if activity.is_running("export") { + Err("an export is already running: wait for it to finish, or stop it (activity.cancel)".into()) + } else { + Ok(()) + } +} + /// The `app.export` params that are not export options: which photos, where to, a preset to start /// from, and the desktop app's background flag. pub const TARGET_PARAMS: &[&str] = &["id", "ids", "path", "dir", "preset", "background", "pluginDestination"]; +/// Whether `v` is a well-formed `pluginDestination`: `{plugin, destination, args?: object}`, a plug-in export +/// destination run after the files are written (by `app.export` and `export.runPresets`). +pub fn is_plugin_destination(v: &serde_json::Value) -> bool { + v.get("plugin").is_some_and(serde_json::Value::is_string) + && v.get("destination").is_some_and(serde_json::Value::is_string) + && v.get("args").is_none_or(|a| a.is_object() || a.is_null()) +} + /// The export option params [`ExportOptions::from_json`] reads (and [`ExportOptions::to_json`] writes). pub const OPTION_PARAMS: &[&str] = &[ "format", @@ -1094,6 +1211,19 @@ pub const WATERMARK_INSET_RANGE: (f32, f32) = (0.0, 0.4); /// A graphic's width as a fraction of the photo's width. pub const WATERMARK_IMAGE_WIDTH_RANGE: (f32, f32) = (0.01, 1.0); +/// First `{seq}` value ([`ExportOptions::start_number`]): `0` is accepted (the Lightroom importer passes it) and names +/// from 1 like `1` does. The accepted ranges of the numeric options are one set for [`ExportOptions::validate`], +/// [`ExportOptions::from_json`], the Lightroom preset importer and the Export dialog (whose sliders stay inside them; +/// a test checks), as the watermark's are (FX-238). +pub const START_NUMBER_RANGE: (u32, u32) = (0, 999_999); +/// Resolution written into the file (pixels per inch); the file's own field is 16 bits. +pub const PPI_RANGE: (u32, u32) = (1, u16::MAX as u32); +/// JPEG file-size limit in KB; `0` is no limit. +pub const LIMIT_KB_RANGE: (u32, u32) = (0, u32::MAX); +/// An output size value (`longEdge`, `shortEdge`, `width`, `height`, `megapixels`, `percent`): the size an export +/// actually gets is bounded by [`Resize::scale`] (65,535 px an edge, 512 megapixels). +pub const RESIZE_VALUE_RANGE: (f64, f64) = (0.0, 1.0e9); + /// Levenshtein distance, for "did you mean" on a misspelled key (both inputs are short). fn edit_distance(a: &str, b: &str) -> usize { let (a, b): (Vec, Vec) = (a.chars().collect(), b.chars().collect()); @@ -1127,8 +1257,6 @@ fn whole(v: &serde_json::Value) -> Option { v.as_i64() } -/// A `watermark` object as a [`Watermark`]; a legacy `inset` fills whichever of `insetX` and -/// `insetY` is missing. /// A privacy switch read leniently: absent or null is `default`, a boolean is itself, anything else is on (FX-184). fn fail_closed_bool(v: Option<&serde_json::Value>, default: bool) -> bool { match v { @@ -1137,6 +1265,8 @@ fn fail_closed_bool(v: Option<&serde_json::Value>, default: bool) -> bool { } } +/// A `watermark` object as a [`Watermark`]; a legacy `inset` fills whichever of `insetX` and +/// `insetY` is missing. fn watermark_from_json(v: &serde_json::Value) -> serde_json::Result { let mut v = v.clone(); if let Some(o) = v.as_object_mut() @@ -1170,6 +1300,19 @@ impl ExportOptions { p } + /// Stored export settings of a Choose folder later export, replayed (Export with Previous) or + /// saved as a preset: without the folder that export was given. The folder is the answer to one + /// question; with it kept, `app.export` found a `dir` and never asked again (FX-192), so the + /// mode stays and the folder goes. Any other mode keeps its `dir`, a setting as in Lightroom's + /// presets. + pub fn without_chosen_folder(mut p: serde_json::Value) -> serde_json::Value { + let choose_later = Self::from_json(&p).destination_mode == DestinationMode::ChooseLater; + if let Some(o) = p.as_object_mut().filter(|_| choose_later) { + o.remove("dir"); + } + p + } + /// [`ExportOptions::known_keys_only`] keeping `bitDepth`, for a preset whose format may only be /// known once the call's own params (`path`) are merged in. pub(crate) fn known_keys(p: &serde_json::Value) -> serde_json::Value { @@ -1214,6 +1357,18 @@ impl ExportOptions { Ok(o) } + /// The extension of `path` when it names a format other than `format` (FX-191): a file with + /// that name would hold the bytes of one format under the name of another. `None` for a path + /// naming no format (or none: `output`), the same format under another spelling (`jpg`, + /// `jpeg`; `dng` for either DNG), and for `Original`, which takes the source's own extension + /// that a path can't know. + pub(crate) fn extension_naming_another_format(path: &str, format: ExportFormat) -> Option { + let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str())?; + let named = ExportFormat::parse(ext)?; + let same = matches!(named, ExportFormat::Original) || matches!(format, ExportFormat::Original) || named.extension() == format.extension(); + (!same).then(|| ext.to_string()) + } + /// The format `app.export` writes: `format` (`null`: the default), else the one the extension of /// `path` names, else `fallback` for a path that names none (the desktop app writes JPEG there, /// the headless backend PNG), else the default. @@ -1276,13 +1431,13 @@ impl ExportOptions { } } "ppi" => { - int(k, v, 1, u16::MAX as i64)?; + int(k, v, i64::from(PPI_RANGE.0), i64::from(PPI_RANGE.1))?; } "limitKb" => { - int(k, v, 0, u32::MAX as i64)?; + int(k, v, i64::from(LIMIT_KB_RANGE.0), i64::from(LIMIT_KB_RANGE.1))?; } "startNumber" => { - int(k, v, 0, 999_999)?; + int(k, v, i64::from(START_NUMBER_RANGE.0), i64::from(START_NUMBER_RANGE.1))?; } "bitDepth" => { if !matches!(whole(v), Some(8 | 10 | 16 | 32)) { @@ -1290,7 +1445,7 @@ impl ExportOptions { } } "longEdge" | "shortEdge" | "width" | "height" | "megapixels" | "percent" => { - num(k, v, 0.0, 1.0e9)?; + num(k, v, RESIZE_VALUE_RANGE.0, RESIZE_VALUE_RANGE.1)?; } "fit" => parses(k, v, |s| fit_bounds_each_edge(s).is_some(), &["dimensions", "widthHeight"])?, "resize" => { @@ -1353,10 +1508,7 @@ impl ExportOptions { "watermark" => Self::validate_watermark(cmd, v)?, "pluginDestination" => { // {plugin, destination, args?}: a plug-in export destination run after the files are written - let ok = v.get("plugin").is_some_and(Value::is_string) - && v.get("destination").is_some_and(Value::is_string) - && v.get("args").is_none_or(|a| a.is_object() || a.is_null()); - if !ok { + if !is_plugin_destination(v) { return Err(bad(format!("`{k}` must be {{plugin, destination, args?: object}}"))); } } @@ -1485,12 +1637,12 @@ impl ExportOptions { format: s("format").and_then(ExportFormat::parse).unwrap_or(d.format), quality: u("quality").map_or(d.quality, |q| q.clamp(1, 100) as u8), resize: Self::resize_from_json(p), - ppi: u("ppi").filter(|v| *v > 0).map_or(d.ppi, |v| v.min(u16::MAX as u64) as u16), - limit_kb: u("limitKb").filter(|v| *v > 0).map(|v| v.min(u32::MAX as u64) as u32), + ppi: u("ppi").filter(|v| *v > 0).map_or(d.ppi, |v| v.min(u64::from(PPI_RANGE.1)) as u16), + limit_kb: u("limitKb").filter(|v| *v > 0).map(|v| v.min(u64::from(LIMIT_KB_RANGE.1)) as u32), sharpen: s("sharpen").and_then(SharpenFor::parse).unwrap_or(d.sharpen), sharpen_amount: s("sharpenAmount").and_then(SharpenAmount::parse).unwrap_or(d.sharpen_amount), naming: s("naming").map_or(d.naming, str::to_string), - start_number: u("startNumber").map_or(d.start_number, |v| v.min(999_999) as u32), + start_number: u("startNumber").map_or(d.start_number, |v| v.min(u64::from(START_NUMBER_RANGE.1)) as u32), custom_text: s("customText").map_or(d.custom_text, str::to_string), texts: p .get("texts") @@ -1605,55 +1757,29 @@ impl ExportOptions { /// The sample format the file is written with (unsupported requests fall back to the closest). pub fn effective_depth(&self) -> OutputDepth { - match (self.format, self.bit_depth) { - (ExportFormat::Jpeg | ExportFormat::Webp | ExportFormat::Original | ExportFormat::Dng, _) => OutputDepth::U8, - (ExportFormat::Png, _) if self.hdr => OutputDepth::F32Hdr, - (ExportFormat::Png, Some(16 | 32)) => OutputDepth::U16, - (ExportFormat::Png, _) => OutputDepth::U8, - (ExportFormat::Tiff, Some(8)) => OutputDepth::U8, - (ExportFormat::Tiff, Some(32)) if self.hdr => OutputDepth::F32Hdr, - (ExportFormat::Tiff, Some(32)) => OutputDepth::F32Linear, - (ExportFormat::Tiff, _) => OutputDepth::U16, - (ExportFormat::RenderedDng, _) if self.hdr => OutputDepth::F32Hdr, - (ExportFormat::RenderedDng, _) => OutputDepth::F32Linear, - (ExportFormat::Exr, _) if self.hdr => OutputDepth::F32Hdr, - (ExportFormat::Exr, _) => OutputDepth::F32Linear, - (ExportFormat::Psd, Some(8)) => OutputDepth::U8, - (ExportFormat::Psd, _) => OutputDepth::U16, - (ExportFormat::Avif, _) if self.gain_map() => OutputDepth::U8, - (ExportFormat::Avif, _) if self.hdr => OutputDepth::F32Hdr, - (ExportFormat::Avif, Some(10 | 16 | 32)) => OutputDepth::U16, - (ExportFormat::Avif, _) => OutputDepth::U8, - (ExportFormat::Jxl, _) if self.gain_map() => OutputDepth::U8, - (ExportFormat::Jxl, _) if self.hdr => OutputDepth::F32Hdr, - (ExportFormat::Jxl, Some(10 | 16 | 32)) => OutputDepth::U16, - (ExportFormat::Jxl, _) => OutputDepth::U8, + if self.gain_map() { + OutputDepth::U8 + } else if self.hdr_output() { + OutputDepth::F32Hdr + } else { + (self.format.caps().samples)(self.bit_depth) } } /// The bit depths `format` offers (value, label); the first is its default. pub fn bit_depths(format: ExportFormat) -> &'static [(u8, &'static str)] { - match format { - ExportFormat::Jpeg | ExportFormat::Webp | ExportFormat::Original | ExportFormat::Dng => &[(8, "8-bit")], - ExportFormat::Png => &[(8, "8-bit"), (16, "16-bit")], - ExportFormat::Tiff => &[(16, "16-bit"), (8, "8-bit"), (32, "32-bit float")], - ExportFormat::Psd => &[(16, "16-bit"), (8, "8-bit")], - ExportFormat::RenderedDng => &[(16, "16-bit float")], - ExportFormat::Exr => &[(16, "16-bit half float"), (32, "32-bit float")], - ExportFormat::Avif => &[(8, "8-bit"), (10, "10-bit")], - ExportFormat::Jxl => &[(8, "8-bit"), (16, "16-bit")], - } + format.caps().depths } /// Whether these options write HDR files (for photos edited in HDR): JPEG (gain map), AVIF, - /// PNG or JPEG XL (PQ) or 32-bit float TIFF with [`ExportOptions::hdr`]. + /// PNG or JPEG XL (PQ), OpenEXR, Render to DNG, or 32-bit float TIFF with [`ExportOptions::hdr`]. pub fn hdr_output(&self) -> bool { self.hdr - && matches!( - (self.format, self.bit_depth), - (ExportFormat::Jpeg | ExportFormat::Avif | ExportFormat::Png | ExportFormat::Jxl | ExportFormat::Exr, _) - | (ExportFormat::Tiff, Some(32)) - ) + && match self.format.caps().hdr { + HdrKind::None => false, + HdrKind::FloatAt32 => self.bit_depth == Some(32), + HdrKind::GainMap | HdrKind::Float | HdrKind::GainMapOrFloat => true, + } } /// Whether these options write an SDR base image with an ISO 21496-1 gain map: JPEG with @@ -1661,10 +1787,10 @@ impl ExportOptions { /// [`ExportOptions::hdr`], as every HDR output does). pub fn gain_map(&self) -> bool { self.hdr - && match self.format { - ExportFormat::Jpeg => true, - ExportFormat::Avif | ExportFormat::Jxl => self.hdr_mode == HdrMode::GainMap, - _ => false, + && match self.format.caps().hdr { + HdrKind::GainMap => true, + HdrKind::GainMapOrFloat => self.hdr_mode == HdrMode::GainMap, + HdrKind::None | HdrKind::Float | HdrKind::FloatAt32 => false, } } @@ -1674,7 +1800,7 @@ impl ExportOptions { /// format's ordinary space. pub fn effective_space(&self) -> OutputSpace { match self.format { - ExportFormat::Avif | ExportFormat::Png | ExportFormat::Jxl if self.hdr && !self.gain_map() => OutputSpace::Rec2020, + f if f.caps().hdr_rec2020 && self.hdr && !self.gain_map() => OutputSpace::Rec2020, // rendered in the working primaries; ACEScg is converted to when the file is written ExportFormat::Exr => OutputSpace::Rec2020, ExportFormat::Avif => OutputSpace::Srgb, @@ -1700,14 +1826,19 @@ impl ExportOptions { /// Output file name for photo `p` at 1-based position `seq` in a batch (the original's /// extension is kept for [`ExportFormat::Original`]). pub fn file_name_for(&self, p: &lcc_catalog::Photo, seq: usize) -> String { + self.file_name_and_cut(p, seq).0 + } + + /// [`Self::file_name_for`], and whether the name had to be cut to fit a file system's name length + /// ([`crate::rename::MAX_NAME_BYTES`], less what is added after naming): a long `{title}`, `{creator}` + /// or `{folder}` would otherwise fail at write time with a bare "File name too long" (FX-224). + pub fn file_name_and_cut(&self, p: &lcc_catalog::Photo, seq: usize) -> (String, bool) { let base = if self.naming.trim().is_empty() { "{name}" } else { self.naming.as_str() }; let n = seq + self.start_number.max(1) as usize - 1; let base = crate::rename::fill_texts(base, &|l| self.texts.get(l).cloned()); // `{custom}` is one of the expansion's tokens, so its text counts toward the expansion's cap // however often the template repeats it; like a `{text:…}` text, it is at most `MAX_TEXT` characters - let custom: String = self.custom_text.trim().chars().take(crate::rename::MAX_TEXT).collect(); - let custom_token = |token: &str, _: Option<&str>, _: &str| (token == "custom").then(|| custom.clone()); - let name = crate::rename::expand_tokens_with(&base, p, n, 3, &custom_token); + let name = crate::rename::expand_tokens_with(&base, p, n, 3, &crate::rename::custom_token(&self.custom_text)); let mut name = portable_stem(&name); let (stem, ext) = p.file_name.rsplit_once('.').unwrap_or((&p.file_name, "")); // the catalog's own file name is cleaned like the expansion: a supplied catalog may hold separators @@ -1717,11 +1848,13 @@ impl ExportOptions { // every token came out empty (no title, no capture time…): keep the original name name = portable_stem(stem); } + let out_ext = if self.format == ExportFormat::Original { ext } else { self.format.extension() }; + let (name, cut) = crate::rename::cap_stem_bytes(name, out_ext.len()); if self.format == ExportFormat::Original { let base = name.trim_end_matches('.'); - if ext.is_empty() { base.to_string() } else { format!("{base}.{ext}") } + (if ext.is_empty() { base.to_string() } else { format!("{base}.{ext}") }, cut) } else { - format!("{name}.{}", self.format.extension()) + (format!("{name}.{}", self.format.extension()), cut) } } } @@ -1870,15 +2003,12 @@ fn encode_8bit(img: &Rgba8, o: &ExportOptions, meta: Option<&Metadata>) -> Resul note_encode(); let img = finish_8bit(img, o); let space = o.effective_space(); - let profile = icc::write_named(named_space(space)); - let exif = meta.map(lcc_meta::write_exif); - let xmp = meta.map(|m| lcc_meta::write_xmp(m, None)); - let meta = EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: Some(o.ppi) }; + let embedded = Embedded::of_metadata(space, None, meta, o.ppi)?; + let meta = embedded.encode_meta(); // Opaque photo exports need no alpha channel (#1670). Keep real transparency for // callers of this encoder, and leave unrelated formats on their existing path. - let rgb: Option> = (matches!(o.format, ExportFormat::Png | ExportFormat::Tiff | ExportFormat::Webp) - && img.data.iter().all(|p| p.last() == Some(&255))) - .then(|| img.data.iter().flat_map(|p| p.iter().take(3).copied()).collect()); + let rgb: Option> = (o.format.keeps_alpha() && img.data.iter().all(|p| p.last() == Some(&255))) + .then(|| img.data.iter().flat_map(|p| p.iter().take(3).copied()).collect()); let e = match &rgb { Some(data) => EncodeImage::new(img.width as u32, img.height as u32, 3, Samples::U8(data)), None => EncodeImage::rgba8(&img), @@ -1887,7 +2017,7 @@ fn encode_8bit(img: &Rgba8, o: &ExportOptions, meta: Option<&Metadata>) -> Resul ExportFormat::Jpeg => { // 4:4:4 normally; 4:2:0 when targeting a file size (much smaller at equal visual quality). let sub = if o.limit_kb.is_some() { ChromaSubsampling::S420 } else { ChromaSubsampling::S444 }; - let fixed = profile.len() + exif.as_ref().map_or(0, Vec::len) + xmp.as_ref().map_or(0, String::len); + let fixed = embedded.len(); return encode_jpeg_with_limit(o, &img, sub, fixed, &mut |q| encode::encode_jpeg(&e, q, sub, &meta).map_err(|e| e.to_string())); } ExportFormat::Png => encode::encode_png(&e, &meta), @@ -1904,20 +2034,66 @@ fn encode_8bit(img: &Rgba8, o: &ExportOptions, meta: Option<&Metadata>) -> Resul r.map(|bytes| (bytes, None)).map_err(|e| e.to_string()) } -/// The warning for an AVIF file `name` written without metadata the policy included (`meta`): the AVIF writer embeds -/// Exif only, so what only XMP holds ([`lcc_meta::exif_leaves_out`]) is not in the file. `None` for other formats, or -/// when nothing was left out. -fn avif_leaves_out(o: &ExportOptions, meta: Option<&Metadata>, name: &str) -> Option { - if o.format != ExportFormat::Avif { - return None; +/// The Exif block of `meta` for an encoder, or the export's error when it can't be serialised: a file is never written +/// with an empty block in its place (FX-189). +pub(crate) fn exif_block(meta: Option<&Metadata>) -> Result>, String> { + meta.map(lcc_meta::write_exif) + .transpose() + .map_err(|e| format!("the photo's Exif metadata could not be written ({e}); export with Metadata set to None to leave it out")) +} + +/// What a file embeds beside its pixels: the colour profile, the Exif block and the XMP packet, and the print +/// resolution. The one place the three are put together for every encoder of the export and of Edit In, so a rule on +/// what goes into a file (a strip, a size limit) is written once (FX-237). Owned: [`Embedded::encode_meta`] borrows it +/// for an encoder, [`Embedded::len`] measures it for a file-size limit. +pub(crate) struct Embedded { + profile: Vec, + exif: Option>, + xmp: Option, + ppi: Option, +} + +impl Embedded { + /// The profile `icc` when the render has one of its own, else the named profile of `space`, with the Exif block + /// and XMP packet already built. + pub(crate) fn new(space: OutputSpace, icc: Option>, exif: Option>, xmp: Option, ppi: Option) -> Self { + Self { profile: icc.unwrap_or_else(|| icc::write_named(named_space(space))), exif, xmp, ppi } + } + + /// [`Embedded::new`] with the Exif block and XMP packet of `meta` (none of either when `meta` is none); the + /// export's error when the Exif block can't be serialised ([`exif_block`]). + pub(crate) fn of_metadata(space: OutputSpace, icc: Option>, meta: Option<&Metadata>, ppi: u16) -> Result { + let exif = exif_block(meta)?; + let xmp = meta.map(|m| lcc_meta::write_xmp(m, None)); + Ok(Self::new(space, icc, exif, xmp, Some(ppi))) + } + + /// The embedded parts as the codecs take them. + pub(crate) fn encode_meta(&self) -> EncodeMeta<'_> { + EncodeMeta { icc: Some(&self.profile), exif: self.exif.as_deref(), xmp: self.xmp.as_deref(), ppi: self.ppi } + } + + pub(crate) fn xmp(&self) -> Option<&str> { + self.xmp.as_deref() + } + + /// The bytes of the profile, Exif block and XMP packet: what a file-size limit can't shrink. + pub(crate) fn len(&self) -> usize { + self.profile.len() + self.exif.as_ref().map_or(0, Vec::len) + self.xmp.as_ref().map_or(0, String::len) } - let left = lcc_meta::exif_leaves_out(meta?); - (!left.is_empty()).then(|| { - format!( - "{name}: AVIF files hold no XMP metadata, so it was written without its {}; export as JPEG, TIFF, PNG, WebP or JPEG XL to keep them", - left.join(", ") - ) - }) +} + +/// The warning for a file `name` written without metadata the policy included (`meta`), for the formats that can't hold +/// all of it: AVIF embeds Exif only, so what only XMP holds ([`lcc_meta::exif_leaves_out`]) is not in the file; +/// OpenEXR holds none ([`lcc_meta::metadata_fields`], FX-188). `None` for other formats, or when nothing was left out. +fn metadata_left_out(o: &ExportOptions, meta: Option<&Metadata>, name: &str) -> Option { + let meta = meta?; + let (left, format, keep) = match o.format { + ExportFormat::Avif => (lcc_meta::exif_leaves_out(meta), "AVIF files hold no XMP metadata", "JPEG, TIFF, PNG, WebP or JPEG XL"), + ExportFormat::Exr => (lcc_meta::metadata_fields(meta), "OpenEXR files hold no metadata", "a 32-bit float TIFF (which keeps the HDR values)"), + _ => return None, + }; + (!left.is_empty()).then(|| format!("{name}: {format}, so it was written without its {}; export as {keep} to keep them", left.join(", "))) } /// Apply the same file-size policy to ordinary JPEGs and complete HDR gain map JPEGs: `encode(q)` @@ -2106,10 +2282,8 @@ fn encode_gain_map_file(sdr: &Rgba8, hdr: &DeepImage, o: &ExportOptions, meta: O gainmap::compute(&sdr_lin, hdr_lin, w, h, space.luma(), &gainmap::GainMapOptions::default()).map_err(|e| e.to_string())?; drop(sdr_lin); lap("gain map: compute", &mut t); - let profile = icc::write_named(named_space(space)); - let exif = meta.map(lcc_meta::write_exif); - let xmp = meta.map(|m| lcc_meta::write_xmp(m, None)); - let em = EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: Some(o.ppi) }; + let embedded = Embedded::of_metadata(space, None, meta, o.ppi)?; + let em = embedded.encode_meta(); let e = EncodeImage::rgba8(&base); // AVIF is always sRGB (`effective_space`), so the map measured in the output space fits let bytes = match o.format { @@ -2153,15 +2327,13 @@ fn encode_gain_map_with_quality(sdr: &Rgba8, hdr: &DeepImage, o: &ExportOptions, let (map, gm) = gainmap::compute(&sdr_lin, hdr_lin, w, h, space.luma(), &gainmap::GainMapOptions::default()).map_err(|e| e.to_string())?; drop(sdr_lin); lap("gain map: compute", &mut t); - let profile = icc::write_named(named_space(space)); - let exif = meta.map(lcc_meta::write_exif); - let xmp = meta.map(|m| lcc_meta::write_xmp(m, None)); - let em = EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: Some(o.ppi) }; + let embedded = Embedded::of_metadata(space, None, meta, o.ppi)?; + let em = embedded.encode_meta(); let sub = if o.limit_kb.is_some() { ChromaSubsampling::S420 } else { ChromaSubsampling::S444 }; // the gain map is encoded once; a file size limit only encodes the primary image again let gain_jpeg = gainmap::encode_gain(&map, &gm, o.quality).map_err(|e| e.to_string())?; let e = EncodeImage::rgba8(&base); - let fixed = gain_jpeg.len() + profile.len() + exif.as_ref().map_or(0, Vec::len) + xmp.as_ref().map_or(0, String::len); + let fixed = gain_jpeg.len() + embedded.len(); let r = encode_jpeg_with_limit(o, &base, sub, fixed, &mut |q| gainmap::encode_with_gain(&e, &gain_jpeg, q, sub, &em).map_err(|e| e.to_string())); lap("gain map: JPEG encode", &mut t); r @@ -2259,13 +2431,13 @@ fn encode_deep_with_alpha(img: &DeepImage, alpha: Option<&Plane>, o: &ExportOpti DeepSamples::U16(_) => a.data.iter().any(|&v| (v.clamp(0.0, 1.0) * 65535.0).round() < 65535.0), DeepSamples::F32(_) => a.data.iter().any(|&v| v < 1.0), }); - let profile = match img.samples { - DeepSamples::F32(_) => icc::write_matrix_trc(&img.space.rgb_space(), &lcc_codecs::Trc::Linear), - DeepSamples::U16(_) => icc::write_named(named_space(img.space)), + // float samples are linear light: the matrix profile of the render's primaries; 16-bit ones the named profile + let linear = match img.samples { + DeepSamples::F32(_) => Some(icc::write_matrix_trc(&img.space.rgb_space(), &lcc_codecs::Trc::Linear)), + DeepSamples::U16(_) => None, }; - let exif = meta.map(lcc_meta::write_exif); - let xmp = meta.map(|m| lcc_meta::write_xmp(m, None)); - let meta = EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: Some(o.ppi) }; + let embedded = Embedded::of_metadata(img.space, linear, meta, o.ppi)?; + let meta = embedded.encode_meta(); let (w, h) = (img.width as u32, img.height as u32); // RGB plus the alpha as a fourth sample fn rgba(v: &[T], a: &Plane, alpha: impl Fn(f32) -> T) -> Vec { @@ -2277,7 +2449,7 @@ fn encode_deep_with_alpha(img: &DeepImage, alpha: Option<&Plane>, o: &ExportOpti .collect() } let (rgba16, rgba32); - let e = match (&img.samples, alpha.as_ref().filter(|_| matches!(o.format, ExportFormat::Png | ExportFormat::Tiff))) { + let e = match (&img.samples, alpha.as_ref().filter(|_| o.format.keeps_alpha())) { (DeepSamples::U16(v), Some(a)) => { rgba16 = rgba(v, a, |av| (av * 65535.0).round() as u16); EncodeImage::new(w, h, 4, Samples::U16(&rgba16)) @@ -2296,7 +2468,8 @@ fn encode_deep_with_alpha(img: &DeepImage, alpha: Option<&Plane>, o: &ExportOpti (ExportFormat::Psd, _) => encode::encode_psd(&e, &meta), (ExportFormat::RenderedDng, DeepSamples::F32(v)) => { let m = meta_src.cloned().unwrap_or_default(); - return lcc_raw::write_rendered_dng(img.width, img.height, v, &img.space.rgb_space(), &m, xmp.clone()).map_err(|e| e.to_string()); + return lcc_raw::write_rendered_dng(img.width, img.height, v, &img.space.rgb_space(), &m, embedded.xmp().map(str::to_string)) + .map_err(|e| e.to_string()); } (ExportFormat::Exr, DeepSamples::F32(v)) => { let primaries = o.exr_primaries.rgb_space(); @@ -2464,12 +2637,15 @@ pub struct Exported { } impl Exported { - /// Write the export to `path` (the movie moved there, else the bytes; sidecars not included). - pub fn save(&self, path: &str) -> Result<(), String> { - match &self.video_file { - Some(f) => f.move_to(path), - None => write_file(path, &self.bytes), - } + /// Write the export to `path` with its sidecars (named like the Placer names them, [`sidecar_path`]), replacing + /// earlier files of those names: the one writer for an export to a single path outside a batch (the CLI's + /// `render`). `guard` is asked about every file first, so nothing is written over a catalogued original or its + /// sidecar, however it is spelled, and a failure writes nothing the caller didn't see ([`write_group_replacing`]). + /// Returns the sidecars written. + pub fn save(&self, path: &str, guard: &crate::originals::OriginalGuard) -> Result, String> { + let files = group_files(self, path); + check_not_originals(guard, &files, &|_| false)?; + write_group_replacing(&mut write_file, self, &files, true).map_err(|f| f.error) } /// The exported file's size in bytes. @@ -2541,6 +2717,8 @@ pub struct PreparedExport { gpu: bool, /// [`Self::preview_until`] also renders an HDR file's HDR rendition ([`Self::keep_hdr`]). want_hdr: bool, + /// Said in the result's warnings when the file name was cut to fit a file system (FX-224). + name_cut: Option, } struct RenderWork { @@ -2631,7 +2809,8 @@ fn prepare_as( movie: bool, ) -> Result { let p = session.catalog.photo(id).ok_or("no such photo")?; - let mut file_name = o.file_name_for(p, seq); + let (mut file_name, cut) = o.file_name_and_cut(p, seq); + let name_cut = cut.then(|| name_cut_warning(&p.file_name, &file_name)); let source_dir = original_folder(&p.source); if let Some(v) = p.video.as_ref().filter(|_| movie && o.format.is_rendered()) { let lcc_catalog::Source::File { path } = &p.source else { @@ -2662,6 +2841,7 @@ fn prepare_as( mix: false, gpu: export_gpu(), want_hdr: true, + name_cut, }); } // HDR output only for photos edited in HDR; the rest of the batch exports as usual @@ -2679,6 +2859,10 @@ fn prepare_as( let (nw, nh) = lcc_pipeline::native_output_size(p.width.max(1) as usize, p.height.max(1) as usize, &p.develop); let native_px = (nw.round().max(1.0) * nh.round().max(1.0)) as usize; let label = p.file_name.clone(); + // a WebP side past the format's limit fails after the whole render: refuse before it (FX-226) + if let Some(why) = webp_size_refusal(o, (w, h)) { + return Err(format!("{label}: {why}")); + } let meta = export_metadata(p, &session.catalog, o); let gain_map = o.gain_map(); // (HDR files are written without alpha: their transparent areas stay on white) @@ -2737,7 +2921,7 @@ fn prepare_as( }; (work, weight) }; - Ok(PreparedExport { photo: id, file_name, source_dir, work, guard, weight, mix: export_mix(), gpu: export_gpu(), want_hdr: true }) + Ok(PreparedExport { photo: id, file_name, source_dir, work, guard, weight, mix: export_mix(), gpu: export_gpu(), want_hdr: true, name_cut }) } /// Why video clip `p`'s original file can't be copied under `o`: a movie's location can sit in places no reader here @@ -2752,6 +2936,14 @@ fn video_location_refusal(p: &lcc_catalog::Photo, catalog: &lcc_catalog::Catalog }) } +/// The warning for a file name cut to fit the file system's name length (FX-224). +fn name_cut_warning(original: &str, written: &str) -> String { + format!( + "{original}: the file name from the naming template was longer than a file system takes ({} bytes), so it was cut to {written}; shorten the template or the title, creator or folder it uses", + crate::rename::MAX_NAME_BYTES + ) +} + /// The folder a photo's original is in, for [`DestinationMode::SameAsOriginal`]. None for a demo /// photo, and on the web, where an original lives in the browser's storage, not in a folder. fn original_folder(source: &lcc_catalog::Source) -> Option { @@ -2763,6 +2955,21 @@ fn original_folder(source: &lcc_catalog::Source) -> Option { (!dir.is_empty()).then_some(dir) } +/// Why a WebP export (`o`) of `out` pixels can't be written, if it can't: a side past the format's limit +/// (16,383 px for lossy WebP, 16,384 for lossless). Other formats have none here. +fn webp_size_refusal(o: &ExportOptions, out: (usize, usize)) -> Option { + if o.format != ExportFormat::Webp { + return None; + } + let max = lcc_codecs::webp_max_side(o.webp_lossy()); + (out.0.max(out.1) > max as usize).then(|| { + format!( + "WebP files are at most {max} pixels a side and this export would be {} × {}; choose a smaller size (Resize to) or another format", + out.0, out.1 + ) + }) +} + /// Why an export of `out` pixels (`w`, `h`), from a photo of `native_px` pixels at its own size, /// can't be made on a computer with `ram` bytes, given its working memory `weight`: an export /// enlarged past the photo's size that needs more memory than the computer has would fail to @@ -3054,12 +3261,17 @@ impl PreparedExport { /// of the items that reads the same pixels: several presets then cost one decode of the photo, /// not one each. A source that fails to decode is left alone (each export reports the error /// itself); stops with [`CANCELLED`] once `stop()` says so. Returns how many decodes it made. + /// + /// Each decode holds its export's working memory from [`crate::memory::export_gate`] and runs under the panic + /// guard, as the export itself does ([`run_gated`]): a decoder that panics leaves that source undecoded, so + /// each export of the photo that reads it fails with the panic as its own error, and the run goes on (FX-220). pub fn share_decodes(items: &mut [PreparedExport], stop: &dyn Fn() -> bool) -> Result { use crate::media::{DecodedSource, SourceLevel, SourceRef}; let mut done: Vec<(SourceLevel, Option, Option)> = Vec::new(); let mut decodes = 0; for it in items.iter_mut() { let Work::Render(w) = &mut it.work else { continue }; + let (weight, what) = (it.weight, format!("decoding {}", it.file_name)); let RenderWork { job, hdr_job, .. } = &mut **w; for job in std::iter::once(job).chain(hdr_job.as_mut()) { if matches!(job.source, SourceRef::Loaded(_)) { @@ -3071,7 +3283,12 @@ impl PreparedExport { if stop() { return Err(CANCELLED.to_string()); } - let d = job.source.load_source_of(job.source_key).ok(); + // (a cancel ends the wait for memory too) + let Some(held) = crate::memory::export_gate().acquire_until(weight, stop) else { + return Err(CANCELLED.to_string()); + }; + let d = crate::guard::catch(&what, || job.source.load_source_of(job.source_key)).and_then(|r| r).ok(); + drop(held); decodes += usize::from(d.is_some()); done.push((job.level, job.source_key, d.clone())); d @@ -3096,7 +3313,14 @@ impl PreparedExport { /// [`Self::run`], giving up ([`CANCELLED`]) between its steps (decode, renders, encode) once /// `stop()` says so: a cancelled export stops within a step, not after the photo. - pub fn run_until(self, stop: &dyn Fn() -> bool) -> Result { + pub fn run_until(mut self, stop: &dyn Fn() -> bool) -> Result { + let name_cut = self.name_cut.take(); + let mut done = self.run_named(stop)?; + done.warnings.extend(name_cut); + Ok(done) + } + + fn run_named(self, stop: &dyn Fn() -> bool) -> Result { let check = || if stop() { Err(CANCELLED.to_string()) } else { Ok(()) }; let file_name = self.file_name; let mix = self.mix; @@ -3123,13 +3347,18 @@ impl PreparedExport { let (r, hdr, gpu_fallback) = render_pair(job, hdr_job, src_px, mix, gpu, &check, &mut t)?; // 3. The encode, on this lane's thread after its turn (the next photo renders meanwhile) check()?; + // a JPEG holds one Exif and one XMP segment: text too long for them is left out and named, not a + // failed export (FX-215); a gain map JPEG's packet also takes its container description + let xmp_reserve = if hdr.is_some() { lcc_codecs::gainmap::XMP_RESERVE } else { 0 }; + let (meta, too_long) = crate::export_jpeg_meta::fit_for_export(meta, &opts, xmp_reserve, &file_name); let (bytes, limit_quality) = match &hdr { Some(hdr) => encode_gain_map_file(&r.image, hdr, &opts, meta.as_ref())?, None => encode_rendered_with_quality(&r, &opts, meta.as_ref())?, }; lap("encode", &mut t); let mut warnings = r.warnings.clone(); - warnings.extend(avif_leaves_out(&opts, meta.as_ref(), &file_name)); + warnings.extend(too_long); + warnings.extend(metadata_left_out(&opts, meta.as_ref(), &file_name)); Ok(Exported { file_name, bytes, @@ -3213,7 +3442,8 @@ impl PreparedExport { if lcc_raw::probe(&bytes).is_none() { return Err(format!("{label}: DNG export needs a raw photo")); } - let mut raw = lcc_raw::decode(&bytes).map_err(|e| format!("{label}: {e}"))?; + // read by the camera's chosen decoder, as every other raw read is, so the DNG holds the mosaic the photo shows (FX-194) + let mut raw = crate::raw_decoder::decode(&bytes).map_err(|e| format!("{label}: {e}"))?; // the colour the photo renders with: its chosen .dcp or calibration look, else the starting colour crate::colour_export::with_photo_colour(&mut raw, &bytes, &camera); drop(bytes); @@ -3427,7 +3657,8 @@ impl crate::Session { } } -/// Export `ids` in order ([`prepare_batch`] + [`run_batch`]), stopping at the first error. +/// Export `ids` in order ([`prepare_batch`] + [`run_batch`]), stopping at the first error. The error drops the +/// results of the photos written before it: a caller that reports what was written uses [`export_batch_outcome`]. pub fn export_batch( session: &mut crate::Session, ids: &[lcc_catalog::PhotoId], @@ -3436,8 +3667,67 @@ pub fn export_batch( write: &mut dyn FnMut(&str, &[u8]) -> Result<(), String>, exists: &dyn Fn(&str) -> bool, ) -> Result, String> { + export_batch_outcome(session, ids, o, to, write, exists)?.into_result() +} + +/// [`export_batch`], telling what it did however it ended: the results of the photos it got to and, when it +/// stopped at a failed photo, [`BatchStop::Failed`] (FX-187). `Err` only when the batch couldn't be set up, before +/// anything was written. +pub fn export_batch_outcome( + session: &mut crate::Session, + ids: &[lcc_catalog::PhotoId], + o: &ExportOptions, + to: &Destination, + write: &mut dyn FnMut(&str, &[u8]) -> Result<(), String>, + exists: &dyn Fn(&str) -> bool, +) -> Result { let items = prepare_batch(session, ids, o)?; - run_batch(items, o, to, write, exists, true, &mut |_, _| true) + Ok(run_batch_outcome(items, o, to, write, exists, true, &mut |_, _| true)) +} + +/// Why an export batch ended before its last photo ([`BatchOutcome::stopped`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum BatchStop { + /// Cancelled (`progress` said stop, or the cancel flag was set): the photos it hadn't got to were not exported. + Cancelled, + /// A photo failed in a batch that stops at the first failure (`stop_on_error`): its error, which its + /// `{photo, file, error}` entry holds too; the photos after it were not exported. + Failed(String), +} + +impl BatchStop { + /// Its name in an export's JSON result (`stopped`): `cancelled` or `failed`. + pub fn name(&self) -> &'static str { + match self { + Self::Cancelled => "cancelled", + Self::Failed(_) => "failed", + } + } +} + +/// What an export batch did, however it ended: one result per photo it got to, in batch order (as [`run_batch`] +/// describes them; the files they name are on disk whether or not the batch ran to the end), and why it ended +/// early, if it did. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BatchOutcome { + pub files: Vec, + pub stopped: Option, +} + +impl BatchOutcome { + /// The results as a `Result`: the error that stopped the batch at a failed photo (the results before it are + /// dropped), else the results (a cancelled batch: the ones until then). + pub fn into_result(self) -> Result, String> { + match self.stopped { + Some(BatchStop::Failed(e)) => Err(e), + Some(BatchStop::Cancelled) | None => Ok(self.files), + } + } + + /// Whether the batch wrote any photo's file. + pub fn wrote_any(&self) -> bool { + self.files.iter().any(|f| FileOutcome::written_path(f).is_some()) + } } /// What one entry of an export's per-photo results (`files`) says happened to its photo: the one @@ -3526,14 +3816,16 @@ pub(crate) fn export_batch_tuned( let lanes = lanes.clamp(1, MAX_EXPORT_LANES).min(items.len().max(1)); let to = Destination::default(); let mut sink = |_: &str, _: &[u8]| Ok(()); - run_batch_with(items, &mut Placer::new(o, &to, &mut sink, &|_| false, true), &mut |_, _| true, lanes, None) + run_batch_with(items, &mut Placer::new(o, &to, &mut sink, &|_| false, true), &mut |_, _| true, lanes, None).into_result() } /// Write an exported or rendered file on disk: its folder is created if needed, and the file is /// replaced atomically ([`lcc_catalog::safe_file::write_atomic_nosync`]: a temp file /// renamed into place), so a failure part-way leaves any previous file intact and no truncated /// one. Not synced to disk (issue #134): an export can always be made again from the original. -/// The native writer behind exports, renders and screenshots (app, CLI, MCP). +/// The native writer behind exports, renders and screenshots (app, CLI, MCP). It writes the path it is given and asks +/// nothing about it: an export's files go through the Placer or [`Exported::save`], which refuse a catalogued original +/// and name the sidecars (FX-216). pub fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { write_with(path, bytes, false) } @@ -3593,10 +3885,8 @@ fn sidecar_path(main: &str, ext: &str) -> String { /// hidden file's) starts no extension (upstream #1415). fn split_file_name(path: &str) -> (&str, &str, Option<&str>) { let (folder, name) = path.split_at(path.rfind(['/', '\\']).map_or(0, |i| i + 1)); - match name.rfind('.').filter(|&i| i > 0) { - Some(i) => (folder, name.get(..i).unwrap_or(name), name.get(i + 1..)), - None => (folder, name, None), - } + let (stem, ext) = lcc_catalog::safe_file::split_extension(name); + (folder, stem, ext) } #[cfg(test)] @@ -3622,10 +3912,12 @@ fn exact_target_refusal(requested: &str, guard: &crate::originals::OriginalGuard /// Run prepared exports in order: pick each one's path, and hand the bytes (and sidecars) to /// `write`. `exists` tells whether a path is taken. The conflict policy applies to a file and its /// sidecars as one: with Unique both get the same free name, with Skip the photo is skipped when -/// either is taken. A path that is a catalogued original (or its sidecar) is refused whatever the +/// either is taken by a file from before the export (a name the batch itself wrote is numbered, as +/// under Overwrite). A path that is a catalogued original (or its sidecar) is refused whatever the /// policy. `progress(done, next file)` is called before each photo; returning false cancels the /// rest. Returns one JSON object per photo: `{path, width, height, bytes, sidecars}`, -/// `{skipped: path}` or (unless `stop_on_error`) `{photo, file, error}`. +/// `{skipped: path}` or `{photo, file, error}`; with `stop_on_error` the first failure ends the batch and is +/// returned as its error instead ([`run_batch_outcome`] keeps the results before it). /// /// Several photos render side by side ([`export_parallelism`], within the memory of /// [`crate::memory::export_gate`]), so one photo's decode, encode or GPU wait overlaps another's @@ -3640,7 +3932,21 @@ pub fn run_batch( stop_on_error: bool, progress: &mut dyn FnMut(usize, &str) -> bool, ) -> Result, String> { - run_batch_cancellable(items, o, to, write, exists, stop_on_error, progress, None) + run_batch_outcome(items, o, to, write, exists, stop_on_error, progress).into_result() +} + +/// [`run_batch`], telling what it did however it ended ([`BatchOutcome`]): a batch stopped at a failed photo +/// still lists the photos written before it, and the failed photo's entry (FX-187). +pub fn run_batch_outcome( + items: Vec, + o: &ExportOptions, + to: &Destination, + write: &mut dyn FnMut(&str, &[u8]) -> Result<(), String>, + exists: &dyn Fn(&str) -> bool, + stop_on_error: bool, + progress: &mut dyn FnMut(usize, &str) -> bool, +) -> BatchOutcome { + run_batch_sharing(items, o, to, write, exists, stop_on_error, progress, None, &mut TakenNames::default()) } /// [`run_batch`] that also stops within about a second once `cancel` is set (a cancelled export @@ -3658,12 +3964,12 @@ pub fn run_batch_cancellable( progress: &mut dyn FnMut(usize, &str) -> bool, cancel: Option>, ) -> Result, String> { - run_batch_sharing(items, o, to, write, exists, stop_on_error, progress, cancel, &mut TakenNames::default()) + run_batch_sharing(items, o, to, write, exists, stop_on_error, progress, cancel, &mut TakenNames::default()).into_result() } /// [`run_batch_cancellable`] as one part of a larger run whose files are `taken` (an export with several presets runs /// photo by photo and preset by preset): the files written are added to it, and a file the run already wrote is never -/// replaced, as within one batch. +/// replaced, as within one batch. Tells what it did however it ended ([`BatchOutcome`]). #[allow(clippy::too_many_arguments)] pub fn run_batch_sharing( items: Vec, @@ -3675,7 +3981,7 @@ pub fn run_batch_sharing( progress: &mut dyn FnMut(usize, &str) -> bool, cancel: Option>, taken: &mut TakenNames, -) -> Result, String> { +) -> BatchOutcome { let lanes = export_parallelism(items.len()); let mut placer = Placer::new(o, to, write, exists, stop_on_error); placer.taken = std::mem::take(taken); @@ -3700,7 +4006,7 @@ pub(crate) fn export_batch_lanes( let to = Destination::default(); let mut write = |_: &str, _: &[u8]| Ok(()); let lanes = lanes.clamp(1, MAX_EXPORT_LANES).min(items.len().max(1)); - run_batch_with(items, &mut Placer::new(o, &to, &mut write, &|_| false, true), &mut |_, _| true, lanes, None) + run_batch_with(items, &mut Placer::new(o, &to, &mut write, &|_| false, true), &mut |_, _| true, lanes, None).into_result() } /// How many photos of a batch of `n` render side by side. Each render already spreads its rows @@ -3945,34 +4251,50 @@ fn run_batch_with( progress: &mut dyn FnMut(usize, &str) -> bool, lanes: usize, cancel: Option>, -) -> Result, String> { +) -> BatchOutcome { // the lanes keep the memory each photo frees for the next one and give it back once at the end (#1416) crate::memory::holding_freed_memory(|| run_batch_holding(items, placer, progress, lanes, cancel)) } -/// [`run_batch_with`] with this thread holding its freed memory. +/// [`run_batch_with`] with this thread holding its freed memory: the results placed and why it ended early, on +/// every way out (FX-187). fn run_batch_holding( items: Vec, placer: &mut Placer<'_>, progress: &mut dyn FnMut(usize, &str) -> bool, lanes: usize, cancel: Option>, -) -> Result, String> { +) -> BatchOutcome { + let stopped = run_batch_placing(items, placer, progress, lanes, cancel); + BatchOutcome { files: std::mem::take(&mut placer.out), stopped } +} + +/// [`run_batch_holding`]'s work: place the photos with `placer`, which keeps their results. Why the batch ended +/// before its last photo, if it did. +fn run_batch_placing( + items: Vec, + placer: &mut Placer<'_>, + progress: &mut dyn FnMut(usize, &str) -> bool, + lanes: usize, + cancel: Option>, +) -> Option { placer.single = items.len() == 1; let cancelled = || cancel.as_ref().is_some_and(|c| c.load(std::sync::atomic::Ordering::Relaxed)); if cfg!(target_arch = "wasm32") || (cancel.is_none() && (lanes <= 1 || items.len() <= 1)) { for (i, item) in items.into_iter().enumerate() { if !progress(i, &item.file_name) || cancelled() { - break; + return Some(BatchStop::Cancelled); } let (photo, name, guard, source_dir) = (item.photo, item.file_name.clone(), item.guard.clone(), item.source_dir.clone()); let r = run_gated(item, &cancelled); if cancelled() { - break; + return Some(BatchStop::Cancelled); + } + if let Err(e) = placer.place(photo, name, source_dir.as_deref(), &guard, r) { + return Some(BatchStop::Failed(e)); } - placer.place(photo, name, source_dir.as_deref(), &guard, r)?; } - return Ok(std::mem::take(&mut placer.out)); + return None; } let heads: Vec<_> = items.iter().map(|i| (i.photo, i.file_name.clone(), i.guard.clone(), i.source_dir.clone())).collect(); let lanes = lanes.max(1); @@ -4008,12 +4330,14 @@ fn run_batch_holding( } for (i, (photo, name, guard, source_dir)) in heads.into_iter().enumerate() { if !progress(i, &name) || queue.cancelled() { - break; + return Some(BatchStop::Cancelled); + } + let Some(e) = queue.result(i) else { return Some(BatchStop::Cancelled) }; + if let Err(e) = placer.place(photo, name, source_dir.as_deref(), &guard, e) { + return Some(BatchStop::Failed(e)); } - let Some(e) = queue.result(i) else { break }; - placer.place(photo, name, source_dir.as_deref(), &guard, e)?; } - Ok(std::mem::take(&mut placer.out)) + None } /// Stops a [`Queue`] when dropped, also while unwinding from a panic. @@ -4330,6 +4654,77 @@ fn remove_own(main: &str, sidecars: &[String]) { } } +/// The files of one exported photo named `main`: it first, then its sidecars, named like it ([`sidecar_path`]). The one +/// place an export's file names are made, for a batch and for [`Exported::save`]. +fn group_files(e: &Exported, main: &str) -> Vec { + std::iter::once(main.to_string()).chain(e.sidecars.iter().map(|(x, _)| sidecar_path(main, x))).collect() +} + +/// Never over an original: `guard` refuses a catalogued original or its sidecar among `files`, however it is +/// spelled. `restored` names the files let through (a missing original an export puts back on purpose, +/// [`Destination::restores`]). +fn check_not_originals(guard: &crate::originals::OriginalGuard, files: &[String], restored: &dyn Fn(&str) -> bool) -> Result<(), String> { + for f in files { + if !restored(f) { + guard.check(std::path::Path::new(f))?; + } + } + Ok(()) +} + +/// A photo's files that could not all be written: why, and which of them are on disk anyway. +struct GroupFailed { + error: String, + kept: Vec, +} + +/// Write `e`'s file and sidecars as `files` (main first), replacing files of those names. The main file is written +/// first, each file atomically, so a failing write leaves the file it was to replace as it was. When a later file +/// fails, a photo is still not left half written where it can be helped: files this call created (`remove_new`, a +/// folder on disk: the ones that were not there before) are removed again, so the photo has all its files or none. +/// Files this call *replaced* can't be put back, so they stay: the error names the file that failed and says which +/// ones stay ([`GroupFailed::kept`]), never reporting a photo that has a new main file beside an old sidecar as +/// written (FX-214). Returns the sidecars written. +fn write_group_replacing( + write: &mut dyn FnMut(&str, &[u8]) -> Result<(), String>, + e: &Exported, + files: &[String], + remove_new: bool, +) -> Result, GroupFailed> { + let Some(main) = files.first() else { return Err(GroupFailed { error: "no file name to write".into(), kept: Vec::new() }) }; + // (a name that is a link counts as there: it is replaced through, not created) + let was_there: Vec = files.iter().map(|f| std::fs::symlink_metadata(f).is_ok()).collect(); + let first = match &e.video_file { + Some(f) => f.move_to(main), + None => write(main, &e.bytes), + }; + first.map_err(|error| GroupFailed { error, kept: Vec::new() })?; + let mut written = vec![main.clone()]; + for ((_, bytes), sc) in e.sidecars.iter().zip(files.iter().skip(1)) { + if let Err(err) = write(sc, bytes) { + let (mut kept, mut removed) = (Vec::new(), Vec::new()); + // (`written[i]` is `files[i]`) + for (i, f) in written.into_iter().enumerate() { + let new = was_there.get(i).is_some_and(|there| !there); + if remove_new && new && std::fs::remove_file(&f).is_ok() { + removed.push(f); + } else { + kept.push(f); + } + } + let list = |v: &[String]| v.join(", "); + let error = match (kept.is_empty(), removed.is_empty()) { + (_, true) => format!("{err} (written and kept: {})", list(&kept)), + (true, false) => format!("{err} ({} removed again: a photo is written with its sidecars or not at all)", list(&removed)), + (false, false) => format!("{err} (written and kept: {}; removed again: {})", list(&kept), list(&removed)), + }; + return Err(GroupFailed { error, kept }); + } + written.push(sc.clone()); + } + Ok(written.split_off(1)) +} + fn join_path(a: &str, b: &str) -> String { if a.is_empty() { b.to_string() } else { format!("{}/{b}", a.trim_end_matches('/')) } } @@ -4372,7 +4767,7 @@ impl<'a> Placer<'a> { } /// Place photo `photo`'s export result (file `name`, its original in `source_dir`): write it - /// and record the outcome. `Err` only when it failed and `stop_on_error` is set. + /// and record the outcome, a failure too. `Err` (its error) only when it failed and `stop_on_error` is set. fn place( &mut self, photo: lcc_catalog::PhotoId, @@ -4388,15 +4783,14 @@ impl<'a> Placer<'a> { let (o, exists) = (self.o, self.exists); let (dir, e) = match dir.and_then(|dir| e.map(|e| (dir, e))) { Ok(v) => v, - Err(err) if self.stop_on_error => return Err(err), Err(err) => { - self.out.push(json!({"photo": photo.0, "file": name, "error": err})); - return Ok(()); + self.out.push(json!({"photo": photo.0, "file": name, "error": &err})); + return if self.stop_on_error { Err(err) } else { Ok(()) }; } }; let dir = dir.as_str(); // the exported file and its sidecars - let group = |main: &str| std::iter::once(main.to_string()).chain(e.sidecars.iter().map(|(x, _)| sidecar_path(main, x))).collect::>(); + let group = |main: &str| group_files(&e, main); let requested = exact.map_or_else(|| join_path(dir, &e.file_name), str::to_string); // An explicitly requested folder or original is an error, not a candidate for renaming or skipping. let refused = if exact.is_some() { exact_target_refusal(&requested, guard) } else { Ok(()) }; @@ -4409,14 +4803,15 @@ impl<'a> Placer<'a> { let restores = &self.to.restores; let claimed = |p: &str| !restores.iter().any(|r| r == p) && guard.claims(std::path::Path::new(p)); let busy = |main: &str| group(main).iter().any(|p| taken.contains(p) || appeared.borrow().contains(p) || exists(p) || claimed(p)); - // the first of `stem-2`, `stem-3`… that `ok` accepts - let next_name = |ok: &dyn Fn(&str) -> bool| { - // keep the requested folder and basename, split as the sidecars' names are - let (folder, stem, ext) = split_file_name(&requested); - let name = |n: usize| ext.map_or_else(|| format!("{folder}{stem}-{n}"), |x| format!("{folder}{stem}-{n}.{x}")); - (2..1_000_000).map(name).find(|p| ok(p)).ok_or_else(|| format!("{requested}: no free file name")) - }; + // the requested name numbered `-2`, `-3`, …, keeping its folder and basename, split as the sidecars' names are + let (folder, stem, ext) = split_file_name(&requested); + let folder_and_stem = format!("{folder}{stem}"); + // the first numbered name that `ok` accepts (one rule and one limit with every other place that numbers a clash) + let first_numbered = |ok: &dyn Fn(&str) -> bool| lcc_catalog::safe_file::first_free_numbered(&folder_and_stem, ext, 2, ok); + let next_name = |ok: &dyn Fn(&str) -> bool| first_numbered(ok).ok_or_else(|| format!("{requested}: no free file name")); let unique = || next_name(&|p| !busy(p)); + // a file this run wrote has the name (or a sidecar's) + let ours = |main: &str| group(main).iter().any(|p| taken.contains(p)); // Overwrite replaces an earlier export: a sidecar name that is there while the file it goes with isn't, beside // another file of that stem (another program's `IMG_1.NEF` and its `IMG_1.xmp`), is that file's sidecar, which // an earlier export of this one would not have left, so it is not Overwrite's to replace (FX-183). A sidecar @@ -4433,11 +4828,22 @@ impl<'a> Placer<'a> { match o.conflict { // Overwrite replaces files from earlier runs, never another photo of this // same batch: a name already written by this batch gets the next free one - Conflict::Overwrite if group(&requested).iter().any(|p| taken.contains(p)) => unique(), + Conflict::Overwrite if ours(&requested) => unique(), Conflict::Overwrite if !replaceable(&requested) && !group(&requested).iter().any(|p| guard.claims(std::path::Path::new(p))) => { next_name(&replaceable) } Conflict::Overwrite => Ok(requested.clone()), + // Skip skips for a file from before the export, never for one this run wrote: the photo takes + // the first number the run hasn't written either, and is skipped only when a file from before + // has that name, so running the export again skips it there (FX-190) + Conflict::Skip if ours(&requested) => match first_numbered(&|p| !ours(p)) { + Some(p) if busy(&p) => { + self.out.push(json!({"photo": photo.0, "skipped": p})); + return Ok(()); + } + Some(p) => Ok(p), + None => Err(format!("{requested}: no free file name")), + }, Conflict::Skip => { self.out.push(json!({"photo": photo.0, "skipped": requested})); return Ok(()); @@ -4447,6 +4853,10 @@ impl<'a> Placer<'a> { }; let file = path.clone().unwrap_or_else(|_| exact.map_or_else(|| name.clone(), str::to_string)); let write = &mut *self.write; + // files an Overwrite wrote that stay although the photo failed (a sidecar that could not be written) + let kept = std::cell::RefCell::new(Vec::::new()); + // a folder on this computer's disk: files this export created may be removed again + let on_disk = self.to.write_new.is_some(); // Unique and Skip promise never to replace a file: `busy` looked a moment ago, so on disk // the file and its sidecars are written as new ones, and a name taken meanwhile (another // export into the folder, a sync client) is the next free name (Unique) or a skip (FX-143) @@ -4456,22 +4866,17 @@ impl<'a> Placer<'a> { let files = group(&path); // never over an original, whatever the conflict policy or the exact path said // (rechecked for the selected main file too: collision probes can outlive its early validation) - for f in &files { - if !(restores.contains(f) && !exists(f)) { - guard.check(std::path::Path::new(f))?; - } - } + check_not_originals(guard, &files, &|f| restores.iter().any(|r| r == f) && !exists(f))?; let Some(write_new) = write_new else { - match &e.video_file { - Some(f) => f.move_to(&path)?, - None => write(&path, &e.bytes)?, - } - let mut sidecars = Vec::new(); - for ((_, bytes), sc) in e.sidecars.iter().zip(files.iter().skip(1)) { - write(sc, bytes)?; - sidecars.push(sc.clone()); - } - return Ok(Placed::Written(path, files, sidecars)); + // Overwrite, and a sink with no folder of its own: the files replace earlier ones, all or none of + // what this call created (FX-214) + return match write_group_replacing(&mut *write, &e, &files, on_disk) { + Ok(sidecars) => Ok(Placed::Written(path, files, sidecars)), + Err(failed) => { + *kept.borrow_mut() = failed.kept; + Err(failed.error) + } + }; }; if let Some(sidecars) = write_group_new(write_new, &e, &files)? { return Ok(Placed::Written(path, files, sidecars)); @@ -4503,8 +4908,19 @@ impl<'a> Placer<'a> { } self.out.push(entry); } - Err(err) if self.stop_on_error => return Err(err), - Err(err) => self.out.push(json!({"photo": photo.0, "file": file, "error": err})), + Err(err) => { + let kept = kept.into_inner(); + let mut entry = json!({"photo": photo.0, "file": file, "error": &err}); + if !kept.is_empty() { + // (the photo failed, but these files are on disk: a later photo of this batch never takes their names) + entry["kept"] = json!(kept); + self.taken.extend(kept); + } + self.out.push(entry); + if self.stop_on_error { + return Err(err); + } + } } Ok(()) } @@ -5026,7 +5442,7 @@ mod tests { 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(lcc_geom::Orientation::from_exif(orientation)), ..Default::default() }; - let exif = lcc_meta::write_exif(&meta); + let exif = lcc_meta::write_exif(&meta).unwrap(); let bytes = lcc_codecs::encode_jpeg( &EncodeImage::rgba8(&logo), 100, @@ -5259,7 +5675,7 @@ mod tests { let props = lcc_meta::parse_xmp(&xmp).unwrap().properties; assert_eq!(props.get("photoshop:DateCreated"), Some(&vec![captured.to_string()]), "{xmp}"); assert_eq!(props.contains_key("exif:DateTimeOriginal"), full, "{xmp}"); - let exif = lcc_meta::read_exif(&lcc_meta::write_exif(&m)); + let exif = lcc_meta::read_exif(&lcc_meta::write_exif(&m).unwrap()); assert_eq!(exif.capture_time.is_some(), full, "{captured}: Exif dates"); let jpg = encode_with_metadata(&test_image(), &ExportOptions::default(), Some(&m)).unwrap(); assert_eq!(lcc_meta::extract(&jpg).capture_time.map(|d| d.to_iso()).as_deref(), Some(captured), "the exported file reads back as stated"); @@ -5776,6 +6192,132 @@ mod tests { } } + /// A name built from a long `{title}` is cut at a character boundary so that the file fits the + /// 255 bytes a file system takes, with room left for a collision number and a sidecar; the cut is + /// reported (FX-224). Boundary: the longest stem that fits, one byte less, one byte more, and a + /// multi-byte character straddling the cut. + #[test] + fn a_long_title_is_cut_to_the_file_system_name_length() { + use crate::rename::{MAX_NAME_BYTES, NAME_SPARE_BYTES}; + let mut p = named("a.jpg"); + let o = ExportOptions { naming: "{title}".into(), ..Default::default() }; + let room = MAX_NAME_BYTES - NAME_SPARE_BYTES - ".jpg".len(); + let mut at = |title: String| { + p.meta.title = title; + o.file_name_and_cut(&p, 1) + }; + let (name, cut) = at("x".repeat(room)); + assert_eq!((name.len(), cut), (room + 4, false), "exactly the room: kept whole"); + let (name, cut) = at("x".repeat(room - 1)); + assert_eq!((name.len(), cut), (room + 3, false), "one byte below: kept whole"); + let (name, cut) = at("x".repeat(room + 1)); + assert_eq!((name, cut), (format!("{}.jpg", "x".repeat(room)), true), "one byte above: cut to the room"); + // a two-byte character that starts at the last byte of the room goes whole or not at all + let (name, cut) = at(format!("{}é", "x".repeat(room - 1))); + assert_eq!((name, cut), (format!("{}.jpg", "x".repeat(room - 1)), true), "é straddles the cut: dropped"); + let (name, cut) = at(format!("{}é", "x".repeat(room - 2))); + assert_eq!((name.len(), cut), (room + 4, false), "é ends at the cut: kept"); + // a cut that leaves a dot or space at the end drops it (a name can't end in one) + let (name, cut) = at(format!("{}. . y", "x".repeat(room - 1))); + assert_eq!((name, cut), (format!("{}.jpg", "x".repeat(room - 1)), true), "trailing dot dropped"); + // every format: the whole name, extension included, fits with the spare + for format in [ExportFormat::Jpeg, ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Original] { + let o = ExportOptions { naming: "{title}{creator}{folder}".into(), format, ..Default::default() }; + let mut p = named("DSC_1.NEF"); + p.meta.title = "t".repeat(1 << 20); + p.meta.creator = "ü".repeat(1 << 19); + let (name, cut) = o.file_name_and_cut(&p, 1); + assert!(cut && name.len() <= MAX_NAME_BYTES - NAME_SPARE_BYTES, "{format:?}: {} bytes", name.len()); + assert_eq!(o.file_name_for(&p, 1), name); + } + // a name that never reaches the limit is not reported + assert!(!ExportOptions::default().file_name_and_cut(&named("a.jpg"), 1).1); + } + + /// A subfolder name is refused past the 255 bytes a file system takes (FX-224): at, below and above the limit, and a + /// multi-byte character straddling it. + #[test] + fn a_subfolder_name_is_at_most_the_file_system_length() { + let max = crate::rename::MAX_NAME_BYTES; + assert_eq!(subfolder_problem(&"a".repeat(max)), None, "exactly 255 bytes"); + assert_eq!(subfolder_problem(&"a".repeat(max - 1)), None); + assert!(subfolder_problem(&"a".repeat(max + 1)).is_some_and(|w| w.contains("255")), "one byte over"); + assert!(subfolder_problem(&format!("{}é", "a".repeat(max - 1))).is_some(), "é straddles the limit: 256 bytes"); + assert_eq!(subfolder_problem(&format!("{}é", "a".repeat(max - 2))), None, "é ends at the limit"); + } + + /// A WebP export past the format's side limit is refused before anything is rendered (FX-226): at the limit, + /// one pixel below, one above, on either side, for lossy (16,383) and lossless (16,384) files, and never for + /// another format. + #[test] + fn a_webp_past_its_side_limit_is_refused_before_rendering() { + let o = |format, webp_lossless| ExportOptions { format, webp_lossless, ..Default::default() }; + for (lossless, max) in [(true, 16_384usize), (false, if lcc_codecs::WEBP_LOSSY { 16_383 } else { 16_384 })] { + let webp = o(ExportFormat::Webp, lossless); + assert_eq!(webp_size_refusal(&webp, (max, 100)), None, "lossless {lossless}: at the limit"); + assert_eq!(webp_size_refusal(&webp, (max - 1, max - 1)), None, "one below"); + for size in [(max + 1, 100), (100, max + 1), (max + 1, max + 1)] { + let why = webp_size_refusal(&webp, size).unwrap_or_default(); + assert!(why.contains(&max.to_string()) && why.contains(&format!("{} × {}", size.0, size.1)), "{size:?}: {why:?}"); + } + } + assert_eq!(lcc_codecs::webp_max_side(true), 16_383); + assert_eq!(lcc_codecs::webp_max_side(false), 16_384); + for format in [ExportFormat::Jpeg, ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Original] { + assert_eq!(webp_size_refusal(&o(format, false), (60_000, 60_000)), None, "{format:?}"); + } + } + + /// The accepted ranges of the numeric options are one set: `validate` takes each end and refuses one past it, + /// `from_json` clamps to it, and a start number of 0 names from 1 like 1 does (the Lightroom importer passes it) + /// (FX-238). Pinned at, below and above each end. + #[test] + fn the_numeric_export_options_share_their_accepted_ranges() { + let ok = |p: serde_json::Value| ExportOptions::validate("app.export", &p).is_ok(); + for (key, (lo, hi)) in [("startNumber", START_NUMBER_RANGE), ("ppi", PPI_RANGE), ("limitKb", LIMIT_KB_RANGE)] { + assert!(ok(json!({ key: lo })) && ok(json!({ key: hi })), "{key}: the ends"); + assert!(ok(json!({ key: lo + 1 })) && ok(json!({ key: hi - 1 })), "{key}: just inside"); + assert!(!ok(json!({ key: u64::from(hi) + 1 })), "{key}: above"); + assert!(!ok(json!({ key: i64::from(lo) - 1 })), "{key}: below"); + } + assert_eq!(START_NUMBER_RANGE, (0, 999_999)); + assert_eq!(ExportOptions::from_json(&json!({"startNumber": 5_000_000})).start_number, START_NUMBER_RANGE.1); + assert_eq!(ExportOptions::from_json(&json!({"ppi": 70_000})).ppi, PPI_RANGE.1 as u16); + assert_eq!(ExportOptions::from_json(&json!({"limitKb": 1u64 << 40})).limit_kb, Some(LIMIT_KB_RANGE.1)); + let size = |v: f64| ok(json!({ "longEdge": v })); + assert!(size(RESIZE_VALUE_RANGE.0) && size(RESIZE_VALUE_RANGE.1) && !size(RESIZE_VALUE_RANGE.1 * 2.0) && !size(-1.0)); + // start number 0 is accepted and names like 1: the first and second files get the same names as with 1 + let p = named("a.jpg"); + let o = |start_number| ExportOptions { naming: "{seq}".into(), start_number, ..Default::default() }; + for seq in [1, 2, 3] { + assert_eq!(o(0).file_name_for(&p, seq), o(1).file_name_for(&p, seq), "seq {seq}"); + } + assert_eq!( + (o(0).file_name_for(&p, 1), o(0).file_name_for(&p, 2), o(2).file_name_for(&p, 1)), + ("001.jpg".into(), "002.jpg".into(), "002.jpg".into()) + ); + } + + /// What the Export dialog's naming help says is what an export does (FX-225): its examples are the names it writes, + /// forbidden characters become `_`, the format's extension is added, and a title that contains the text `{custom}` is + /// not replaced by the Custom text. + #[test] + fn the_export_naming_help_describes_what_export_writes() { + use crate::rename::{TemplateKind, sample_photo}; + let p = sample_photo(); + let name = |naming: &str, custom: &str| { + ExportOptions { naming: naming.into(), custom_text: custom.into(), ..Default::default() }.file_name_for(&p, 1) + }; + for tag in ["{seq}", "{seq:2}", "{custom}", "{name}", "{date}", "{title}", "{ext}"] { + assert_eq!(name(tag, "Gallery"), format!("{}.jpg", TemplateKind::Export.example(tag)), "{tag}"); + } + assert_eq!(name("{camera}:{seq}", ""), "Canon EOS R5_001.jpg", "a forbidden character becomes _, a file gets the format's extension"); + let mut titled = sample_photo(); + titled.meta.title = "About {custom} {Custom}".into(); + let o = ExportOptions { naming: "{title}-{custom}".into(), custom_text: "Trip".into(), ..Default::default() }; + assert_eq!(o.file_name_for(&titled, 1), "About {custom} {Custom}-Trip.jpg", "the literal text in a title stays"); + } + #[test] fn params_round_trip() { let o = ExportOptions { @@ -6161,6 +6703,91 @@ mod tests { assert!(encode_rendered(&ramp(OutputDepth::U16, OutputSpace::DisplayP3), &lossy, None).is_ok()); } + /// What an export embeds beside the pixels (FX-237): every path that writes a file puts in the colour profile of + /// the space it wrote (the named profile of the output space; for float samples the linear matrix profile), the + /// EXIF block and the XMP packet of the metadata it was given, and nothing when it was given none. + #[test] + fn every_encode_path_embeds_the_profile_of_the_space_it_wrote_and_the_metadata_it_was_given() { + let meta = Metadata { copyright: Some("Synthetic export test".into()), make: Some("Make".into()), ..Default::default() }; + let spaces = [OutputSpace::Srgb, OutputSpace::AdobeRgb, OutputSpace::DisplayP3, OutputSpace::ProPhoto, OutputSpace::Rec2020]; + let named = |s: OutputSpace| icc::write_named(named_space(s)); + // what a decoder finds in `bytes`: (profile, has EXIF, has XMP) + let found = |bytes: &[u8]| { + let d = lcc_codecs::decode(bytes, Default::default()).expect("decodes"); + (d.icc, d.exif.is_some(), d.xmp.is_some()) + }; + for space in spaces { + for with in [Some(&meta), None] { + let want = |profile: Vec, exif: bool| (Some(profile), exif && with.is_some(), with.is_some()); + // 8-bit: JPEG and PNG carry EXIF beside the packet (a TIFF's EXIF is its own structure) + for format in [ExportFormat::Jpeg, ExportFormat::Png, ExportFormat::Tiff] { + let o = ExportOptions { format, color_space: space, bit_depth: Some(8), ..Default::default() }; + let bytes = encode_rendered(&ramp(OutputDepth::U8, o.effective_space()), &o, with).unwrap(); + let (icc, exif, xmp) = found(&bytes); + let (wicc, wexif, wxmp) = want(named(o.effective_space()), format != ExportFormat::Tiff); + assert!(icc == wicc, "{format:?} 8-bit in {space:?}: the profile"); + assert_eq!((exif, xmp), (wexif, wxmp), "{format:?} 8-bit in {space:?}"); + } + // 16-bit: the same named profile + for format in [ExportFormat::Png, ExportFormat::Tiff] { + let o = ExportOptions { format, color_space: space, bit_depth: Some(16), ..Default::default() }; + let bytes = encode_rendered(&ramp(OutputDepth::U16, o.effective_space()), &o, with).unwrap(); + let (icc, exif, xmp) = found(&bytes); + let (wicc, wexif, wxmp) = want(named(o.effective_space()), format != ExportFormat::Tiff); + assert!(icc == wicc, "{format:?} 16-bit in {space:?}: the profile"); + assert_eq!((exif, xmp), (wexif, wxmp), "{format:?} 16-bit in {space:?}"); + } + // float TIFF: linear light, so the matrix profile with a linear curve, of the space the render has + let o = ExportOptions { format: ExportFormat::Tiff, color_space: space, bit_depth: Some(32), ..Default::default() }; + let r = ramp(OutputDepth::F32Linear, o.effective_space()); + let linear = icc::write_matrix_trc(&r.deep.as_ref().unwrap().space.rgb_space(), &lcc_codecs::Trc::Linear); + let bytes = encode_rendered(&r, &o, with).unwrap(); + let (icc, _, xmp) = found(&bytes); + assert!(icc == Some(linear), "float TIFF in {space:?}: the profile"); + assert_eq!(xmp, with.is_some(), "float TIFF in {space:?}"); + // a gain map JPEG: the base image's space, as the SDR JPEG has it + let o = ExportOptions { format: ExportFormat::Jpeg, color_space: space, hdr: true, ..Default::default() }; + assert!(o.gain_map()); + let sdr = ramp(OutputDepth::U8, o.effective_space()); + let hdr = ramp(OutputDepth::F32Hdr, o.effective_space()); + let bytes = encode_gain_map_jpeg(&sdr.image, hdr.deep.as_ref().unwrap(), &o, with).unwrap(); + let (icc, exif, xmp) = found(&bytes); + let (wicc, wexif, _) = want(named(o.effective_space()), true); + // (the XMP is there either way: a gain map file carries its own packet) + assert!(icc == wicc, "gain map JPEG in {space:?}: the profile"); + assert_eq!((exif, xmp), (wexif, true), "gain map JPEG in {space:?}"); + } + } + // the pixel density goes into the file the same way: JPEG's JFIF header holds it + let o = ExportOptions { format: ExportFormat::Jpeg, ppi: 123, ..Default::default() }; + let bytes = encode_rendered(&ramp(OutputDepth::U8, OutputSpace::Srgb), &o, None).unwrap(); + let jfif = bytes.windows(5).position(|w| w == b"JFIF\0").expect("a JFIF header"); + assert_eq!(u16::from_be_bytes([bytes[jfif + 8], bytes[jfif + 9]]), 123, "x density"); + } + + /// The embedded parts as the encoders take them, and the bytes a file-size limit can't shrink (FX-237). + #[test] + fn embedded_parts_are_what_the_encoders_get_and_what_a_size_limit_counts() { + let meta = Metadata { copyright: Some("c".into()), ..Default::default() }; + let named = icc::write_named(named_space(OutputSpace::DisplayP3)); + // the named profile of the space, the metadata's Exif and XMP, the density + let e = Embedded::of_metadata(OutputSpace::DisplayP3, None, Some(&meta), 300).unwrap(); + let m = e.encode_meta(); + assert_eq!((m.icc, m.ppi), (Some(named.as_slice()), Some(300))); + let (exif, xmp) = (lcc_meta::write_exif(&meta).unwrap(), lcc_meta::write_xmp(&meta, None)); + assert_eq!((m.exif, m.xmp), (Some(exif.as_slice()), Some(xmp.as_str()))); + assert_eq!(e.len(), named.len() + exif.len() + xmp.len()); + assert_eq!(e.xmp(), Some(xmp.as_str())); + // no metadata: the profile alone; a render's own profile replaces the named one; given parts are kept as they are + let e = Embedded::of_metadata(OutputSpace::Srgb, Some(vec![1, 2, 3]), None, 240).unwrap(); + let m = e.encode_meta(); + assert_eq!((m.icc, m.exif, m.xmp, e.len()), (Some([1u8, 2, 3].as_slice()), None, None, 3)); + let e = Embedded::new(OutputSpace::Srgb, None, Some(vec![9]), Some("".into()), None); + let m = e.encode_meta(); + assert_eq!((m.exif, m.xmp, m.ppi), (Some([9u8].as_slice()), Some(""), None)); + assert_eq!(e.len(), icc::write_named(named_space(OutputSpace::Srgb)).len() + 1 + 4); + } + #[test] fn bit_depth_options_per_format() { let d = |format, bit_depth| ExportOptions { format, bit_depth, ..Default::default() }.effective_depth(); @@ -6180,6 +6807,98 @@ mod tests { } } + /// Every format x requested bit depth x HDR setting answers one table ([`ExportFormat::caps`]): the depth written, + /// whether HDR is written, whether it is a gain map and the output space, and the depths and alpha it offers + /// (FX-236). The requests are `None`, 0, 8, 10, 12, 16, 32 and 255 (what the Export dialog offers, what `from_json` + /// admits, and what no format has), in that order; per request a letter or digit in each string. The three + /// settings: HDR off, HDR on as a single layer, HDR on as a gain map. Depth letters: `b` 8-bit, `s` 16-bit, `l` float + /// linear, `h` float HDR; space letters: `S` sRGB, `R` Rec. 2020. + #[test] + fn every_format_answers_depth_hdr_alpha_and_space_from_one_table() { + use ExportFormat as F; + type Setting = (&'static str, &'static str, &'static str, &'static str); + #[rustfmt::skip] + let table: &[(F, &[u8], bool, [Setting; 3])] = &[ + (ExportFormat::Jpeg, &[8], false, [("bbbbbbbb", "00000000", "00000000", "SSSSSSSS"), ("bbbbbbbb", "11111111", "11111111", "SSSSSSSS"), ("bbbbbbbb", "11111111", "11111111", "SSSSSSSS")]), + (ExportFormat::Png, &[8,16], true, [("bbbbbssb", "00000000", "00000000", "SSSSSSSS"), ("hhhhhhhh", "11111111", "00000000", "RRRRRRRR"), ("hhhhhhhh", "11111111", "00000000", "RRRRRRRR")]), + (ExportFormat::Tiff, &[16,8,32], true, [("ssbsssls", "00000000", "00000000", "SSSSSSSS"), ("ssbssshs", "00000010", "00000000", "SSSSSSSS"), ("ssbssshs", "00000010", "00000000", "SSSSSSSS")]), + (ExportFormat::Psd, &[16,8], false, [("ssbsssss", "00000000", "00000000", "SSSSSSSS"), ("ssbsssss", "00000000", "00000000", "SSSSSSSS"), ("ssbsssss", "00000000", "00000000", "SSSSSSSS")]), + (ExportFormat::Webp, &[8], true, [("bbbbbbbb", "00000000", "00000000", "SSSSSSSS"), ("bbbbbbbb", "00000000", "00000000", "SSSSSSSS"), ("bbbbbbbb", "00000000", "00000000", "SSSSSSSS")]), + (ExportFormat::Avif, &[8,10], false, [("bbbsbssb", "00000000", "00000000", "SSSSSSSS"), ("hhhhhhhh", "11111111", "00000000", "RRRRRRRR"), ("bbbbbbbb", "11111111", "11111111", "SSSSSSSS")]), + (ExportFormat::Jxl, &[8,16], false, [("bbbsbssb", "00000000", "00000000", "SSSSSSSS"), ("hhhhhhhh", "11111111", "00000000", "RRRRRRRR"), ("bbbbbbbb", "11111111", "11111111", "SSSSSSSS")]), + (ExportFormat::Original, &[8], false, [("bbbbbbbb", "00000000", "00000000", "SSSSSSSS"), ("bbbbbbbb", "00000000", "00000000", "SSSSSSSS"), ("bbbbbbbb", "00000000", "00000000", "SSSSSSSS")]), + (ExportFormat::Dng, &[8], false, [("bbbbbbbb", "00000000", "00000000", "SSSSSSSS"), ("bbbbbbbb", "00000000", "00000000", "SSSSSSSS"), ("bbbbbbbb", "00000000", "00000000", "SSSSSSSS")]), + (ExportFormat::RenderedDng, &[16], false, [("llllllll", "00000000", "00000000", "SSSSSSSS"), ("hhhhhhhh", "11111111", "00000000", "SSSSSSSS"), ("hhhhhhhh", "11111111", "00000000", "SSSSSSSS")]), + (ExportFormat::Exr, &[16,32], false, [("llllllll", "00000000", "00000000", "RRRRRRRR"), ("hhhhhhhh", "11111111", "00000000", "RRRRRRRR"), ("hhhhhhhh", "11111111", "00000000", "RRRRRRRR")]), + ]; + let reqs: [Option; 8] = [None, Some(0), Some(8), Some(10), Some(12), Some(16), Some(32), Some(255)]; + let settings = [(false, HdrMode::SingleLayer), (true, HdrMode::SingleLayer), (true, HdrMode::GainMap)]; + let letter = |d: OutputDepth| match d { + OutputDepth::U8 => 'b', + OutputDepth::U16 => 's', + OutputDepth::F32Linear => 'l', + OutputDepth::F32Hdr => 'h', + }; + let bit = |b: bool| if b { '1' } else { '0' }; + let space = |s: OutputSpace| match s { + OutputSpace::Srgb => 'S', + OutputSpace::Rec2020 => 'R', + _ => '?', + }; + assert_eq!(table.len(), 11, "every format has a row"); + for (f, depths, alpha, expected) in table { + assert_eq!(&ExportOptions::bit_depths(*f).iter().map(|d| d.0).collect::>(), depths, "{f:?}: offered depths"); + assert_eq!(f.keeps_alpha(), *alpha, "{f:?}: keeps alpha"); + for ((hdr, mode), want) in settings.iter().zip(expected) { + let os: Vec = + reqs.iter().map(|r| ExportOptions { format: *f, bit_depth: *r, hdr: *hdr, hdr_mode: *mode, ..Default::default() }).collect(); + let got = ( + os.iter().map(|o| letter(o.effective_depth())).collect::(), + os.iter().map(|o| bit(o.hdr_output())).collect::(), + os.iter().map(|o| bit(o.gain_map())).collect::(), + os.iter().map(|o| space(o.effective_space())).collect::(), + ); + assert_eq!( + (got.0.as_str(), got.1.as_str(), got.2.as_str(), got.3.as_str()), + *want, + "{f:?} hdr={hdr} {mode:?}: depth, hdr output, gain map, space" + ); + } + } + // the formats whose HDR file `effective_depth` writes as float are the ones `hdr_output` says write HDR, bar + // gain maps (an 8-bit base image) and TIFF below 32 bits: a Render to DNG with HDR on is one (FX-236) + let dng = ExportOptions { format: F::RenderedDng, hdr: true, ..Default::default() }; + assert!(dng.hdr_output() && dng.effective_depth() == OutputDepth::F32Hdr); + for f in table.iter().map(|r| r.0) { + for r in reqs { + let o = ExportOptions { format: f, bit_depth: r, hdr: true, ..Default::default() }; + assert_eq!( + o.effective_depth() == OutputDepth::F32Hdr, + o.hdr_output() && !o.gain_map(), + "{f:?} {r:?}: float HDR depth <=> HDR output without a gain map" + ); + } + } + // a depth the format offers is written as that depth: 8 is 8-bit wherever it is offered, 16 is 16-bit + for f in table.iter().map(|r| r.0) { + for &(d, _) in ExportOptions::bit_depths(f) { + let o = ExportOptions { format: f, bit_depth: Some(d), ..Default::default() }; + let got = o.effective_depth(); + match (f, d) { + (F::Exr | F::RenderedDng, _) => assert_eq!(got, OutputDepth::F32Linear, "{f:?} {d}"), + (F::Tiff, 32) => assert_eq!(got, OutputDepth::F32Linear, "{f:?} {d}"), + (_, 8) => assert_eq!(got, OutputDepth::U8, "{f:?} {d}"), + (_, _) => assert_eq!(got, OutputDepth::U16, "{f:?} {d}"), + } + } + } + // Edit In offers a format's depths as Export does + use crate::cmd::edit_in::Format as E; + for (e, f) in [(E::Tiff, F::Tiff), (E::Psd, F::Psd), (E::Png, F::Png), (E::Exr, F::Exr)] { + assert_eq!(e.bit_depths(), ExportOptions::bit_depths(f).iter().map(|d| d.0).collect::>().as_slice(), "{e:?}: Edit In's depths"); + } + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn avif_ten_bit() { @@ -6546,6 +7265,22 @@ mod tests { stop_on_error: bool, cancel_at: usize, ) -> (Result, String>, Vec<(String, Vec)>, Vec<(usize, String)>) { + let (outcome, written, seen) = lanes_outcome(s, ids, o, lanes, stop_on_error, cancel_at, None); + (outcome.into_result(), written, seen) + } + + /// [`lanes_batch`] as the batch's [`BatchOutcome`]; with `flag`, a cancel flag the batch watches, which + /// `progress` sets (and keeps returning true) at `cancel_at`. + #[allow(clippy::type_complexity)] + fn lanes_outcome( + s: &mut crate::Session, + ids: &[lcc_catalog::PhotoId], + o: &ExportOptions, + lanes: usize, + stop_on_error: bool, + cancel_at: usize, + flag: Option>, + ) -> (BatchOutcome, Vec<(String, Vec)>, Vec<(usize, String)>) { let items = prepare_batch(s, ids, o).unwrap(); let to = Destination { dir: "out".into(), exact: None, ..Default::default() }; let mut written = Vec::new(); @@ -6554,12 +7289,21 @@ mod tests { Ok(()) }; let mut seen = Vec::new(); + let watched = flag.clone(); let mut progress = |i: usize, name: &str| { seen.push((i, name.to_string())); - i < cancel_at + match &watched { + Some(f) => { + if i >= cancel_at { + f.store(true, std::sync::atomic::Ordering::Relaxed); + } + true + } + None => i < cancel_at, + } }; - let files = run_batch_with(items, &mut Placer::new(o, &to, &mut write, &|_| false, stop_on_error), &mut progress, lanes, None); - (files, written, seen) + let outcome = run_batch_with(items, &mut Placer::new(o, &to, &mut write, &|_| false, stop_on_error), &mut progress, lanes, flag); + (outcome, written, seen) } /// The files of a batch without their byte counts: a GPU render (when another test turns the @@ -6656,7 +7400,7 @@ mod tests { true }; let r = crate::guard::catch("test batch", || { - run_batch_with(items, &mut Placer::new(&o, &to, &mut write, &|_| false, true), &mut progress, 2, None) + run_batch_with(items, &mut Placer::new(&o, &to, &mut write, &|_| false, true), &mut progress, 2, None).into_result() }); tx.send(r.and_then(|r| r)).ok(); }); @@ -6664,6 +7408,32 @@ mod tests { assert!(matches!(r, Ok(Err(_))), "the batch returns an error instead of hanging: {r:?}"); } + /// FX-220: a panic inside one photo's export (here its decoder) is that photo's error, in its place in the results, + /// while the other photos are exported, whether the photos run one at a time or side by side. The panic guard of + /// [`run_gated`] is what turns it into an error: without it the batch ends in the panic, or never ends. + #[test] + fn a_panic_inside_one_photos_export_is_that_photos_error() { + for lanes in [1, 3] { + let o = ExportOptions::from_json(&json!({"format": "jpeg", "longEdge": 32})); + let (mut s, ids, _dir) = crate::tests_export::library_of_jpegs("export-panic", 3); + crate::tests_export::decoder_panics_on(&mut s, "IMG_2.jpg", |_| {}); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let (files, written, _) = lanes_batch(&mut s, &ids, &o, lanes, false, usize::MAX); + tx.send((files, written.len(), ids)).ok(); + }); + let r = rx.recv_timeout(std::time::Duration::from_secs(60)); + let Ok((files, written, ids)) = r else { panic!("{lanes} lanes: the batch neither ends nor fails: {r:?}") }; + let files = files.unwrap_or_else(|e| panic!("{lanes} lanes: the batch ended in {e}")); + assert_eq!(files.len(), 3, "{lanes} lanes: {files:?}"); + assert_eq!((files[1]["photo"].as_u64(), files[1]["file"].as_str()), (Some(ids[1].0), Some("IMG_2.jpg")), "{files:?}"); + let why = files[1]["error"].as_str().unwrap_or_default(); + assert!(why.contains("failed unexpectedly") && why.contains("decoder bug"), "{lanes} lanes: {files:?}"); + assert!([0, 2].iter().all(|&i| files[i]["path"].is_string() && files[i].get("error").is_none()), "{lanes} lanes: {files:?}"); + assert_eq!(written, 2, "{lanes} lanes: the other photos are written"); + } + } + // 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] @@ -6691,6 +7461,51 @@ mod tests { assert_eq!(written.len(), 1, "only the photo before the failure"); } + /// FX-187: a batch that ends early still tells what it wrote, however it ends. Stopped at a failed photo + /// (`stop_on_error`): the photo written before it and the failed photo's entry, `Failed` with its error. + /// Cancelled (by `progress` or the cancel flag): the photos placed until then, `Cancelled`; a cancel asked + /// before the last photo stops it, one asked after the last photo leaves the batch complete. One lane and several. + #[test] + fn a_batch_cut_short_still_reports_what_it_wrote() { + use lcc_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_187), Source::File { path: "no/such/dir/gone.jpg".into() }, "gone.jpg", "JPEG", 600, 400, "2026-12-01T00:00:00"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(gone) }).unwrap(); + ids.insert(1, PhotoId(9_187)); + let n = ids.len(); + let o = ExportOptions::from_json(&json!({"format": "jpeg", "width": 40})); + for lanes in [1, 3] { + // stopped at the failed photo: what was written before it is still there, and the failure is typed + let (out, written, _) = lanes_outcome(&mut s, &ids, &o, lanes, true, usize::MAX, None); + assert_eq!(out.files.len(), 2, "{lanes} lanes: {out:?}"); + assert_eq!(out.files[0]["path"].as_str(), written.first().map(|(p, _)| p.as_str()), "{lanes} lanes: {out:?}"); + assert_eq!(out.files[1]["photo"].as_u64(), Some(9_187), "{lanes} lanes: {out:?}"); + let error = out.files[1]["error"].as_str().unwrap().to_string(); + assert_eq!(out.stopped, Some(BatchStop::Failed(error.clone())), "{lanes} lanes"); + assert!(out.wrote_any()); + assert_eq!(written.len(), 1, "{lanes} lanes: nothing after the failure is written"); + assert_eq!(out.into_result(), Err(error), "the older shape is unchanged"); + for flag in [false, true] { + let watch = || flag.then(|| std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false))); + // cancelled before the last photo: the photos placed until then (the failed one is an entry) + let (out, written, _) = lanes_outcome(&mut s, &ids, &o, lanes, false, n - 1, watch()); + assert_eq!(out.stopped, Some(BatchStop::Cancelled), "{lanes} lanes, flag {flag}: {out:?}"); + assert_eq!(out.files.len(), n - 1, "{lanes} lanes, flag {flag}: {out:?}"); + assert_eq!(written.len(), n - 2, "{lanes} lanes, flag {flag}"); + // a cancel at the first photo: nothing placed, still `Cancelled` + let (out, written, _) = lanes_outcome(&mut s, &ids, &o, lanes, false, 0, watch()); + assert_eq!((out.files.len(), written.len(), out.stopped.clone()), (0, 0, Some(BatchStop::Cancelled)), "{lanes} lanes, flag {flag}"); + assert!(!out.wrote_any()); + // asked only once every photo is placed: complete + let (out, written, _) = lanes_outcome(&mut s, &ids, &o, lanes, false, n, watch()); + assert_eq!((out.files.len(), written.len(), out.stopped), (n, n - 1, None), "{lanes} lanes, flag {flag}"); + } + } + assert_eq!((BatchStop::Cancelled.name(), BatchStop::Failed(String::new()).name()), ("cancelled", "failed")); + } + #[test] fn export_weights_follow_the_source_and_output_sizes() { use crate::media::SourceLevel; diff --git a/crates/engine/src/export_jpeg_meta.rs b/crates/engine/src/export_jpeg_meta.rs new file mode 100644 index 0000000000..788c419502 --- /dev/null +++ b/crates/engine/src/export_jpeg_meta.rs @@ -0,0 +1,280 @@ +//! Fitting a photo's metadata to what one JPEG holds (FX-215). +//! +//! A JPEG carries its EXIF in one APP1 segment ([`lcc_codecs::encode::JPEG_MAX_EXIF`]) and its XMP in another +//! ([`lcc_codecs::encode::JPEG_MAX_XMP`]); Extended XMP is not written. A photo whose caption, keywords or alt text +//! add up to more than that used to fail its export with a message naming no field. Here the largest text fields are +//! left out, one at a time, until what remains fits, and the export says which and how large they were (a warning on +//! that photo's result, as for the formats that hold less metadata, [`super::metadata_left_out`]). The other formats +//! hold the whole text and are not touched. +//! +//! Sources: own design. + +use lcc_codecs::encode::{JPEG_MAX_EXIF, JPEG_MAX_XMP}; +use lcc_meta::Metadata; + +/// A variable-length text field of [`Metadata`] the export can leave out. +struct Field { + /// How the warning names it. + name: &'static str, + /// Bytes of text it holds. + size: fn(&Metadata) -> usize, + clear: fn(&mut Metadata), +} + +fn opt(s: &Option) -> usize { + s.as_ref().map_or(0, String::len) +} + +fn list(v: &[String]) -> usize { + v.iter().map(String::len).sum() +} + +/// The fields that can be left out, in no order: the largest goes first, whatever it is. +const FIELDS: &[Field] = &[ + Field { name: "caption", size: |m| opt(&m.caption), clear: |m| m.caption = None }, + Field { name: "extended description", size: |m| opt(&m.extended_description), clear: |m| m.extended_description = None }, + Field { name: "alt text", size: |m| opt(&m.alt_text), clear: |m| m.alt_text = None }, + Field { + name: "keywords", + + size: |m| list(&m.keywords) + list(&m.hierarchical_keywords), + clear: |m| (m.keywords, m.hierarchical_keywords) = (Vec::new(), Vec::new()), + }, + Field { name: "title", size: |m| opt(&m.title), clear: |m| m.title = None }, + Field { name: "headline", size: |m| opt(&m.headline), clear: |m| m.headline = None }, + Field { name: "caption writer", size: |m| opt(&m.description_writer), clear: |m| m.description_writer = None }, + Field { name: "copyright notice", size: |m| opt(&m.copyright), clear: |m| m.copyright = None }, + Field { name: "usage terms", size: |m| opt(&m.usage_terms), clear: |m| m.usage_terms = None }, + Field { name: "copyright URL", size: |m| opt(&m.copyright_url), clear: |m| m.copyright_url = None }, + Field { name: "creator", size: |m| opt(&m.artist), clear: |m| m.artist = None }, + Field { + name: "creator contact details", + + size: |m| lcc_meta::CreatorContact::KEYS.iter().filter_map(|k| m.contact.get(k)).map(String::len).sum(), + clear: |m| m.contact = Default::default(), + }, + Field { + name: "categories", + + size: |m| opt(&m.category) + list(&m.supplemental_categories) + list(&m.subject_code), + clear: |m| (m.category, m.supplemental_categories, m.subject_code) = (None, Vec::new(), Vec::new()), + }, + Field { + name: "place names", + + size: |m| [&m.sublocation, &m.city, &m.state, &m.country, &m.country_code].into_iter().map(opt).sum(), + clear: |m| (m.sublocation, m.city, m.state, m.country, m.country_code) = (None, None, None, None, None), + }, + Field { + name: "camera and lens names", + + size: |m| { + [&m.make, &m.model, &m.lens_make, &m.lens_model, &m.serial_number, &m.lens_serial_number, &m.software, &m.label] + .into_iter() + .map(opt) + .sum() + }, + clear: |m| { + (m.make, m.model, m.lens_make, m.lens_model) = (None, None, None, None); + (m.serial_number, m.lens_serial_number, m.software, m.label) = (None, None, None, None); + }, + }, +]; + +/// The sizes of the Exif block and the XMP packet `meta` is written as in a JPEG, in bytes. A block that can't be +/// written counts as empty here: the encode reports why ([`super::exif_block`]). +fn written_sizes(meta: &Metadata) -> (usize, usize) { + (lcc_meta::write_exif(meta).map_or(0, |b| b.len()), lcc_meta::write_xmp(meta, None).len()) +} + +/// `n` bytes in whole kilobytes, at least one. +fn kb(n: usize) -> usize { + n.div_ceil(1024).max(1) +} + +/// `meta` as a JPEG of the export `o` holds it, and the warning for a file `name` that had to leave something out. +/// `xmp_reserve` bytes of the XMP packet's room are kept free for what the encoder adds to it (a gain map's container +/// description, [`lcc_codecs::gainmap::XMP_RESERVE`]). Unchanged, and no warning, for other formats and for metadata +/// that fits. +pub(crate) fn fit_for_export( + meta: Option, + o: &super::export::ExportOptions, + xmp_reserve: usize, + name: &str, +) -> (Option, Option) { + if o.format != super::export::ExportFormat::Jpeg { + return (meta, None); + } + let Some(m) = meta else { return (None, None) }; + match fit(&m, xmp_reserve) { + None => (Some(m), None), + Some((fitted, left, was)) => { + let what: Vec = left.iter().map(|(field, n)| format!("{field} ({} KB)", kb(*n))).collect(); + let warning = format!( + "{name}: its metadata is {} KB and a JPEG holds {} KB at most, so it was written without its {}; shorten {}, or export as TIFF, PNG, WebP or JPEG XL to keep {}", + kb(was), + kb(JPEG_MAX_XMP.saturating_sub(xmp_reserve).min(JPEG_MAX_EXIF)), + what.join(", "), + if left.len() == 1 { "it" } else { "them" }, + if left.len() == 1 { "it" } else { "them" }, + ); + (Some(fitted), Some(warning)) + } + } +} + +/// `meta` less its largest text fields until its Exif block and XMP packet (less `xmp_reserve`) fit one JPEG, with the +/// fields left out (name, bytes of text) in the order they went, and the size `meta` was written at before: `None` +/// when it already fits. Every field it can leave out goes if it must; what still doesn't fit is the encoder's refusal. +fn fit(meta: &Metadata, xmp_reserve: usize) -> Option<(Metadata, Vec<(&'static str, usize)>, usize)> { + let xmp_max = JPEG_MAX_XMP.saturating_sub(xmp_reserve); + let (exif0, xmp0) = written_sizes(meta); + if exif0 <= JPEG_MAX_EXIF && xmp0 <= xmp_max { + return None; + } + let mut m = meta.clone(); + let mut left = Vec::new(); + loop { + let (exif, xmp) = written_sizes(&m); + if exif <= JPEG_MAX_EXIF && xmp <= xmp_max { + break; + } + // (the XMP packet holds everything the Exif block does and more, so the largest field is the one to cut + // whichever of the two is over) + let biggest = FIELDS.iter().map(|f| (f, (f.size)(&m))).filter(|(_, n)| *n > 0).max_by_key(|(_, n)| *n); + let Some((field, n)) = biggest else { break }; + (field.clear)(&mut m); + left.push((field.name, n)); + } + Some((m, left, exif0.max(xmp0))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::export::{ExportFormat, ExportOptions}; + + fn text(n: usize) -> Option { + Some("x".repeat(n)) + } + + fn jpeg() -> ExportOptions { + ExportOptions { format: ExportFormat::Jpeg, ..Default::default() } + } + + fn sizes(m: &Metadata) -> (usize, usize) { + written_sizes(m) + } + + /// The caption length at which the XMP packet of a photo with only a caption is exactly `JPEG_MAX_XMP` bytes, + /// found by trying: the packet grows one byte per caption byte. + fn caption_len_at_xmp_cap() -> usize { + let base = sizes(&Metadata { caption: text(1), ..Default::default() }).1; + JPEG_MAX_XMP - (base - 1) + } + + #[test] + fn a_long_caption_is_left_out_and_named_with_its_size() { + let caption = 70_000; + let m = Metadata { caption: text(caption), copyright: Some("(c) Someone".into()), keywords: vec!["tern".into()], ..Default::default() }; + let (fitted, warning) = fit_for_export(Some(m), &jpeg(), 0, "IMG_1.jpg"); + let fitted = fitted.unwrap(); + assert_eq!(fitted.caption, None, "the caption went"); + assert_eq!( + (fitted.copyright.as_deref(), fitted.keywords.as_slice()), + (Some("(c) Someone"), ["tern".to_string()].as_slice()), + "the rest stayed" + ); + let w = warning.expect("a warning"); + assert!(w.starts_with("IMG_1.jpg: ") && w.contains("caption (69 KB)") && !w.contains("keywords"), "{w}"); + assert!(w.contains("a JPEG holds 64 KB at most"), "{w}"); + let (e, x) = sizes(&fitted); + assert!(e <= JPEG_MAX_EXIF && x <= JPEG_MAX_XMP, "what is left fits: {e} {x}"); + } + + /// Fields go largest first, and only as many as it takes. + #[test] + fn only_as_many_fields_go_as_it_takes_the_largest_first() { + // keywords 40 KB + alt text 30 KB: over together, either alone fits; the keywords (larger) go, the alt text stays + let m = Metadata { keywords: vec!["k".repeat(20_000), "j".repeat(20_000)], alt_text: text(30_000), title: text(10), ..Default::default() }; + let (fitted, warning) = fit_for_export(Some(m), &jpeg(), 0, "a.jpg"); + let fitted = fitted.unwrap(); + assert!(fitted.keywords.is_empty() && fitted.hierarchical_keywords.is_empty()); + assert_eq!((fitted.alt_text.map(|s| s.len()), fitted.title.map(|s| s.len())), (Some(30_000), Some(10))); + let w = warning.unwrap(); + assert!(w.contains("keywords (40 KB)") && !w.contains("alt text"), "{w}"); + // two fields that are each over by themselves both go, and the warning names both in the order they went + let m = Metadata { caption: text(70_000), alt_text: text(80_000), ..Default::default() }; + let (fitted, warning) = fit_for_export(Some(m), &jpeg(), 0, "b.jpg"); + let fitted = fitted.unwrap(); + assert_eq!((fitted.caption, fitted.alt_text), (None, None)); + let w = warning.unwrap(); + assert!(w.contains("without its alt text (79 KB), caption (69 KB); shorten them"), "{w}"); + } + + /// At, below and above the XMP cap: a packet of exactly the cap is kept whole, one byte over loses the field. + #[test] + fn the_xmp_boundary_keeps_a_packet_at_the_cap_and_trims_one_byte_over() { + let n = caption_len_at_xmp_cap(); + for (len, kept) in [(n - 1, true), (n, true), (n + 1, false)] { + let m = Metadata { caption: text(len), ..Default::default() }; + let (e, x) = sizes(&m); + // (the caption is in the Exif block too, which holds 23 bytes more than the XMP leaves: only the XMP decides here) + assert!(e <= JPEG_MAX_EXIF, "the Exif block fits at {len}: {e}"); + assert_eq!(x <= JPEG_MAX_XMP, kept, "{len} bytes: packet {x}"); + let (fitted, warning) = fit_for_export(Some(m.clone()), &jpeg(), 0, "c.jpg"); + assert_eq!((fitted.as_ref() == Some(&m), warning.is_none()), (kept, kept), "{len} bytes"); + if let Some(w) = &warning { + assert!(w.contains("caption"), "{w}"); + } + } + } + + /// A notice the Exif block holds as one ASCII value, over the Exif cap and the XMP cap alike. + #[test] + fn a_notice_too_large_for_the_exif_block_goes() { + let m = Metadata { copyright: text(JPEG_MAX_EXIF + 1), keywords: vec!["tern".into()], ..Default::default() }; + let (fitted, warning) = fit_for_export(Some(m), &jpeg(), 0, "d.jpg"); + let fitted = fitted.unwrap(); + assert_eq!((fitted.copyright, fitted.keywords.len()), (None, 1)); + assert!(warning.unwrap().contains("copyright notice")); + } + + #[test] + fn a_gain_map_keeps_room_for_the_container_description() { + let n = caption_len_at_xmp_cap(); + let m = Metadata { caption: text(n), ..Default::default() }; + assert!(fit_for_export(Some(m.clone()), &jpeg(), 0, "e.jpg").1.is_none(), "a plain JPEG holds it"); + let (fitted, warning) = fit_for_export(Some(m), &jpeg(), lcc_codecs::gainmap::XMP_RESERVE, "e.jpg"); + assert_eq!(fitted.unwrap().caption, None); + assert!(warning.is_some(), "a gain map JPEG, which adds to the packet, does not"); + } + + #[test] + fn other_formats_and_no_metadata_are_left_alone() { + let m = Metadata { caption: text(200_000), ..Default::default() }; + for format in [ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp, ExportFormat::Jxl] { + let (fitted, warning) = fit_for_export(Some(m.clone()), &ExportOptions { format, ..Default::default() }, 0, "f"); + assert_eq!((fitted.as_ref(), warning), (Some(&m), None), "{format:?}"); + } + assert_eq!(fit_for_export(None, &jpeg(), 0, "g"), (None, None)); + } + + /// Hostile input: text that can never fit and every field full still ends, leaving the encoder to refuse. + #[test] + fn metadata_that_cannot_fit_whatever_goes_still_ends() { + let big = || text(5 << 20); + let m = Metadata { + caption: big(), + extended_description: big(), + alt_text: big(), + title: big(), + keywords: vec!["k".repeat(1 << 20); 4], + ..Default::default() + }; + let (fitted, warning) = fit_for_export(Some(m), &jpeg(), 0, "h.jpg"); + let (e, x) = sizes(&fitted.unwrap()); + assert!(e <= JPEG_MAX_EXIF && x <= JPEG_MAX_XMP); + assert!(warning.unwrap().contains("caption")); + } +} diff --git a/crates/engine/src/finishing.rs b/crates/engine/src/finishing.rs index e5acedbd1f..1c2c8423fe 100644 --- a/crates/engine/src/finishing.rs +++ b/crates/engine/src/finishing.rs @@ -56,6 +56,7 @@ impl Session { /// Advance the finish (cheap; call every frame): take up a plan the library kept, and forget /// the plan once its work is done or the user stopped it. → whether a finish is at work. pub fn finishing_tick(&mut self) -> bool { + self.poll_smart_scan(); if self.finishing.is_none() && self.finish_pending.is_some() { // someone else's preview build: wait for it, then build ours if self.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) { diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 0fc61c55a7..bf3e806028 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -3412,6 +3412,8 @@ impl Session { /// Use the system clock for import/edit times (native hosts). pub fn with_system_clock(mut self) -> Self { self.clock = Box::new(system_clock); + // On This Day opens on today's date, not on the test clock's + self.memories_day = crate::cmd::library::today_month_day(&self); self } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 33c64fd59a..613ee4efcd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -60,6 +60,7 @@ pub mod enhance; mod errors; pub mod expand; pub mod export; +mod export_jpeg_meta; pub mod export_video; pub mod eye_cull; pub mod eye_prep; @@ -767,6 +768,9 @@ pub struct Session { pub edge_fill: expand::EdgeFillState, /// The last (or running) Build Previews. pub preview_build: Option>, + /// The listing of the smart previews folder that is running on a worker thread, and the background smart preview + /// build whose end starts the next one ([`cmd::previews`]): what the Has Smart Preview rule matches. + pub smart_scan: cmd::previews::SmartScan, /// Builds asked for while one was already running, waiting for their turn /// ([`cmd::previews::drain_queue`] starts the next one when the running build ends). pub preview_queue: std::collections::VecDeque, @@ -1078,6 +1082,7 @@ impl Session { edge_fill: Default::default(), upright_jobs: Default::default(), preview_build: None, + smart_scan: Default::default(), preview_queue: Default::default(), prep: Default::default(), loupe_edge: 0, @@ -2459,6 +2464,15 @@ impl Session { _ => a.cmp(b), }); } + if self.source == LibrarySource::Memories { + // the most recent year first, whatever the sort chosen (the grid groups by year; its + // headers are the grid's own too, so the sort itself is left as it was for other views) + let (cat, sort) = (&self.catalog, lcc_catalog::Sort { ascending: true, ..self.sort }); + visible.sort_by(|a, b| match (cat.photo(*a), cat.photo(*b)) { + (Some(x), Some(y)) => y.captured.cmp(&x.captured).then_with(|| sort.order(x, y)), + _ => a.cmp(b), + }); + } if self.source == LibrarySource::Missing { // only the photos the query kept (library photos, not Local browse records) are checked let (cat, avail) = (&self.catalog, &self.media.availability); @@ -2562,9 +2576,7 @@ impl Session { pub(crate) fn view_filter(&self, source: LibrarySource, base: &Filter) -> Filter { let mut f = source.to_filter(base, &self.catalog); if source == LibrarySource::Memories { - f.capture_month_day = Some(self.memories_day.clone()); - let year = (self.clock)().get(..4).and_then(|year| year.parse::().ok()).unwrap_or(i32::MIN); - f.capture_before_year = Some(year); + self.apply_memories(&mut f); } if source == LibrarySource::Folder { // no folder chosen: nothing (an empty path matches nothing) @@ -2662,7 +2674,8 @@ impl Session { /// What tells one source's total from another's (the catalog's revision and the source's rules aside). fn total_key(&self) -> String { - format!("{:?}|{:?}|{:?}|{}", self.source, self.browse, self.library_folder, self.folder_subfolders) + // the day tells one Memories view from another (the year it cuts off at moves with the clock) + format!("{:?}|{:?}|{:?}|{}|{}", self.source, self.browse, self.library_folder, self.folder_subfolders, self.memories_day) } /// Photos in the current source (folder, album, …) before the filter bar and search narrow @@ -2711,7 +2724,7 @@ impl Session { lcc_catalog::rules::set_now(Some(now.clone())); let f = self.view_filter(self.source, &Filter::default()); let tally = lcc_catalog::tally::FilterTally::of(&self.catalog, &f); - let minute = filter_depends_on_clock(&f, &self.catalog).then(|| clock_minute(&now).to_owned()); + let minute = (self.source == LibrarySource::Memories || filter_depends_on_clock(&f, &self.catalog)).then(|| clock_minute(&now).to_owned()); self.total_counted += 1; let n = tally.len(); self.total = Some(SourceTotal { key, tally, minute }); @@ -2748,6 +2761,13 @@ impl Session { &self.memories_day } + /// What a filter asks to be the Memories view: its day, and captures from earlier years than this one. + pub(crate) fn apply_memories(&self, f: &mut Filter) { + f.capture_month_day = Some(self.memories_day.clone()); + let year = (self.clock)().get(..4).and_then(|year| year.parse::().ok()).unwrap_or(i32::MIN); + f.capture_before_year = Some(year); + } + pub(crate) fn source_key(&self) -> String { match self.source { LibrarySource::LibraryFolder => format!("folder:{}", lcc_catalog::query::folder_key(self.library_folder.as_deref().unwrap_or_default())), @@ -3006,6 +3026,8 @@ mod tests_export_batch; #[cfg(test)] mod tests_export_binning; #[cfg(test)] +mod tests_export_group; +#[cfg(test)] mod tests_export_new_files; #[cfg(test)] #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index d4c93986ba..95406bce97 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -870,6 +870,8 @@ impl Session { self.previous_export.clear(); self.source = LibrarySource::All; self.library_folder = None; + // today for this library (the view file may name the day it was left on) + self.memories_day = crate::cmd::library::today_month_day(self); // what names albums and photos by number means others in another library: no filter // (as after a restart; the view file keeps none), no target album, no photo come from self.filter = Default::default(); @@ -970,6 +972,7 @@ impl Session { if let Some(d) = &self.smart_previews_dir { self.media.smart_dir = Some(d.clone()); } + self.start_smart_scan(); // presets if let Some(f) = settings.read::(files.as_mut(), "presets.json") { self.preset_folders = f.folders; @@ -1112,6 +1115,11 @@ impl Session { crate::cmd::previews::refresh_stale_smart_previews(self); } stages.mark("smart previews"); + #[cfg(not(target_arch = "wasm32"))] + { + crate::cmd::publish::refresh_service_names(self); + stages.mark("publish services"); + } // an import still being finished when the app closed picks up where it stopped self.load_finishing(); stages.mark("unfinished import"); @@ -1406,7 +1414,8 @@ impl Session { fn view_json(&self) -> Vec { let view = ViewFile { source: self.source, - memories_day: self.memories_day.clone(), + // the day only while it is shown, as the folder is + memories_day: if self.source == LibrarySource::Memories { self.memories_day.clone() } else { String::new() }, browse: self.browse.clone(), // only while it is shown: a leftover would be a stale choice nobody made library_folder: self.library_folder.clone().filter(|_| self.source == LibrarySource::LibraryFolder), diff --git a/crates/engine/src/lightroom_smart.rs b/crates/engine/src/lightroom_smart.rs index 13efb2ab67..8bad2d5da9 100644 --- a/crates/engine/src/lightroom_smart.rs +++ b/crates/engine/src/lightroom_smart.rs @@ -203,8 +203,12 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result { _ => Ok(Rule::Group { group: RuleSet { mode: Match::Any, rules } }), } } - "captureTime" | "touchTime" => { - let target = if name == "captureTime" { "captureDate" } else { "editDate" }; + "captureTime" | "touchTime" | "lastExportTimestamp" => { + let target = match name { + "captureTime" => "captureDate", + "touchTime" => "editDate", + _ => "lastExported", + }; match op { "==" => Ok(field(target, "is", json!(date(value).ok_or_else(unsupported)?))), ">" => Ok(field(target, "after", json!(date(value).ok_or_else(unsupported)?))), @@ -269,18 +273,78 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result { }; choice("label", op, label.ok_or_else(unsupported)?).ok_or_else(unsupported) } - // Has Edits: the user changed the settings. Has Adjustments (settings that differ from the - // camera default) has no equal here yet and stays static. - "edit" | "cropped" | "hasGPSData" | "flashFired" => { + // Has Edits: the user changed the settings. Has Adjustments: they differ from the camera default. + // Is Proof and Device Depth have no field (nothing is stored per photo) and stay static. + "edit" + | "hasAdjustments" + | "profileCorrections" + | "removeChromaticAberration" + | "hasPointColor" + | "hdrEditMode" + | "hasAI" + | "hasGenAI" + | "cropped" + | "hasGPSData" + | "flashFired" + | "proxyStatus" + | "snapshots" => { let target = match name { "edit" => "edited", + "hasAdjustments" => "hasAdjustments", + "profileCorrections" => "lensCorrections", + "removeChromaticAberration" => "removeCa", + "hasPointColor" => "hasPointColor", + "hdrEditMode" => "hdrEdit", + "hasAI" => "hasAi", + "hasGenAI" => "hasGenAi", "cropped" => "cropped", "hasGPSData" => "hasGps", + "proxyStatus" => "smartPreview", + "snapshots" => "hasSnapshots", _ => "flash", }; let yes = yes_no(op, value).ok_or_else(unsupported)?; Ok(field(target, "is", json!(yes))) } + // Only the AI edits Cf records on the photo map; the Enhance ones (Raw Details, Super Resolution) make a + // separate file, and Lens Blur, AI Look and the rest have no edit here, so they stay static. + "aiEditStatus" => { + let id = match value.and_then(Lua::str) { + Some("denoise") => "denoise", + Some("none") => "none", + _ => return Err(unsupported()), + }; + choice("aiEdit", op, id).ok_or_else(unsupported) + } + "maskTypeStatus" => { + let id = match value.and_then(Lua::str) { + Some( + v @ ("subject" | "sky" | "background" | "people" | "landscape" | "brush" | "colorRange" | "luminanceRange" | "depthRange" + | "none"), + ) => v, + Some("scribble") => "object", + Some("linearGradient") => "linear", + Some("radialGradient") => "radial", + _ => return Err(unsupported()), + }; + choice("maskType", op, id).ok_or_else(unsupported) + } + // "car" is content-aware remove, the only retouch kind seen stored: Cf's Remove and Content-Aware Fill modes + "hasRetouch" => { + if value.and_then(Lua::str) != Some("car") { + return Err(unsupported()); + } + let aware = vec![field("manualRemove", "is", json!("remove")), field("manualRemove", "is", json!("fill"))]; + match op { + "==" => Ok(Rule::Group { group: RuleSet { mode: Match::Any, rules: aware } }), + "!=" => Ok(Rule::Group { group: RuleSet { mode: Match::None, rules: aware } }), + _ => Err(unsupported()), + } + } + "developPreset" => { + let id = value.and_then(Lua::str).filter(|v| ["default", "specified", "custom"].contains(v)).ok_or_else(unsupported)?; + choice("developPreset", op, id).ok_or_else(unsupported) + } "treatment" => { let id = match value.and_then(Lua::str) { Some("grayscale") => "monochrome", @@ -335,6 +399,9 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result { "title" => "title", "caption" => "caption", "copyname" | "copyName" => "copyName", + // the service's or the published collection's name; a photo's publish links decide, as in Lightroom + "publishedVia" => "publishedVia", + "publishCollection" => "publishCollection", "creator" => "creator", "copyright" => "copyright", "city" => "city", @@ -343,8 +410,12 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result { "location" => "sublocation", "cameraSN" => "cameraSerial", "altText" => "altText", + "extDescr" => "extendedDescription", + "labelText" => "labelText", "folder" => "folder", "all" | "metadata" => "text", + "iptc" => "iptcText", + "exif" => "exifText", "state" => "state", _ => return Err(unsupported()), }; @@ -352,12 +423,21 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result { // Any Searchable Text has no empty or exact test. let allowed: &[&str] = match target { "folder" => &["all", "words", "any"], - "text" => &["all", "words", "any", "noneOf"], + "text" | "iptcText" | "exifText" => &["all", "words", "any", "noneOf"], + // Lightroom offers only is, is not, is empty and isn't empty, and its text is the standard name; a + // name the person gave a label isn't one Cf's field holds + "labelText" => &["==", "!=", "empty", "notEmpty"], _ => &[], }; if !allowed.is_empty() && !allowed.contains(&op) { return Err(unsupported()); } + if target == "labelText" && matches!(op, "==" | "!=") { + let named = value.and_then(Lua::str).unwrap_or_default().to_ascii_lowercase(); + if !["red", "yellow", "green", "blue", "purple"].contains(&named.as_str()) { + return Err(unsupported()); + } + } text_rule(target, op, value.and_then(Lua::str).unwrap_or_default()).ok_or_else(unsupported) } } @@ -465,6 +545,31 @@ mod tests { } } + /// Label Text maps for the five standard names and for empty / not empty; a name the person gave a label is not + /// one Cf's field holds, and Lightroom offers no other operator for it, so those stay static. Job, Metadata + /// Status, Plug-in Metadata and Is DNG With Fast Load Data have no Cf field and stay static too. + #[test] + fn label_text_and_the_criteria_without_a_field() { + for (rule, want) in [ + (r#"criteria = "labelText", operation = "==", value = "Red""#, Some(("labelText", "is", json!("Red")))), + (r#"criteria = "labelText", operation = "!=", value = "Purple""#, Some(("labelText", "isNot", json!("Purple")))), + (r#"criteria = "labelText", operation = "empty", value = """#, Some(("labelText", "isEmpty", Value::Null))), + (r#"criteria = "labelText", operation = "notEmpty", value = """#, Some(("labelText", "isNotEmpty", Value::Null))), + (r#"criteria = "labelText", operation = "==", value = "Hero""#, None), + (r#"criteria = "labelText", operation = "beginsWith", value = "Re""#, None), + (r#"criteria = "jobIdentifier", operation = "==", value = "JOB-042""#, None), + (r#"criteria = "metadataStatus", operation = "==", value = "changedOnDisk""#, None), + (r#"criteria = "allPluginMetadata", operation = "any", value = "test""#, None), + (r#"criteria = "fastLoadDNG", operation = "isTrue", value = true"#, None), + ] { + let got = smart_rules(&format!("s = {{ {{ {rule} }}, combine = \"intersect\" }}"), &[]); + match want { + Some((f, op, v)) => assert_eq!(got.unwrap().rules, vec![field(f, op, v)], "{rule}"), + None => assert!(got.is_err(), "{rule} stays static"), + } + } + } + #[test] fn deep_nesting_is_bounded() { let mut s = String::from("{ criteria = \"rating\", operation = \">=\", value = 1 }"); @@ -542,7 +647,16 @@ mod tests { (r#"criteria = "cropped", operation = "isTrue", value = true"#, Some(("cropped", "is", json!(true)))), (r#"criteria = "cropped", operation = "isFalse", value = true"#, Some(("cropped", "is", json!(false)))), (r#"criteria = "edit", operation = "isTrue", value = true"#, Some(("edited", "is", json!(true)))), - (r#"criteria = "hasAdjustments", operation = "isTrue", value = true"#, None), + (r#"criteria = "hasAdjustments", operation = "isTrue", value = true"#, Some(("hasAdjustments", "is", json!(true)))), + (r#"criteria = "developPreset", operation = "!=", value = "custom""#, Some(("developPreset", "isNot", json!("custom")))), + (r#"criteria = "developPreset", operation = "==", value = "other""#, None), + (r#"criteria = "isProofCopy", operation = "isTrue", value = true"#, None), + (r#"criteria = "aiEditStatus", operation = "!=", value = "denoise""#, Some(("aiEdit", "isNot", json!("denoise")))), + (r#"criteria = "aiEditStatus", operation = "==", value = "rawDetails""#, None), + (r#"criteria = "aiUpdateRequiredStatus", operation = "==", value = "denoise""#, None), + (r#"criteria = "maskTypeStatus", operation = "!=", value = "sky""#, Some(("maskType", "isNot", json!("sky")))), + (r#"criteria = "maskTypeStatus", operation = "==", value = "unknown""#, None), + (r#"criteria = "hasRetouch", operation = "==", value = "other""#, None), (r#"criteria = "treatment", operation = "==", value = "grayscale""#, Some(("treatment", "is", json!("monochrome")))), (r#"criteria = "treatment", operation = "!=", value = "grayscale""#, Some(("treatment", "isNot", json!("monochrome")))), (r#"criteria = "treatment", operation = "==", value = "sepia""#, None), @@ -555,7 +669,10 @@ mod tests { (r#"criteria = "megapixelsCropped", operation = ">", value = 10"#, Some(("megapixels", "gt", json!(10.0)))), (r#"criteria = "widthCropped", operation = ">", value = 3000"#, None), (r#"criteria = "longEdge", operation = ">=", value = 4000"#, None), - (r#"criteria = "lastExportTimestamp", operation = "inLast", value = 3"#, None), + ( + r#"criteria = "lastExportTimestamp", operation = "inLast", value = 3"#, + Some(("lastExported", "inLast", json!({"n": 3.0, "unit": "day"}))), + ), (r#"criteria = "likes", operation = "isTrue", value = true"#, None), (r#"criteria = "comments", operation = "isTrue", value = true"#, None), (r#"criteria = "labelColor", operation = "==", value = 1"#, Some(("label", "is", json!("red")))), diff --git a/crates/engine/src/lightroom_smart_rows.tsv b/crates/engine/src/lightroom_smart_rows.tsv index 7d90522da4..1cd59aa90c 100644 --- a/crates/engine/src/lightroom_smart_rows.tsv +++ b/crates/engine/src/lightroom_smart_rows.tsv @@ -1,4 +1,4 @@ -Exported is after "2026-01-01" s = { { criteria = "lastExportTimestamp", operation = ">", value = "2026-01-01", value2 = "2026-11-20", }, combine = "intersect", } static: rule `lastExportTimestamp >` has no equivalent +Exported is after "2026-01-01" s = { { criteria = "lastExportTimestamp", operation = ">", value = "2026-01-01", value2 = "2026-11-20", }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"after","value":"2026-01-01"}]} SC-ALTTEXT-EMPTY s = { { criteria = "altText", operation = "empty", value = "", value2 = "", }, combine = "intersect", } {"match":"all","rules":[{"field":"altText","op":"isEmpty","value":null}]} SC-ANY-META s = { { criteria = "metadata", operation = "any", value = "calm", }, combine = "intersect", } {"match":"all","rules":[{"field":"text","op":"contains","value":"calm"}]} SC-ANYTEXT s = { { criteria = "all", operation = "any", value = "calm", }, combine = "intersect", } {"match":"all","rules":[{"field":"text","op":"contains","value":"calm"}]} @@ -26,29 +26,29 @@ SC-COPYNAME-EMPTY s = { { criteria = "copyname", operation = "empty", value = "" SC-COPYNAME-SET s = { { criteria = "copyname", operation = "any", value = "Alt", }, combine = "intersect", } {"match":"all","rules":[{"field":"copyName","op":"contains","value":"Alt"}]} SC-COPYRIGHT-STATUS s = { { criteria = "copyrightState", operation = "==", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"copyrightStatus","op":"is","value":"copyrighted"}]} SC-CREATOR s = { { criteria = "creator", operation = "==", value = "Test Photographer", }, combine = "intersect", } {"match":"all","rules":[{"field":"creator","op":"is","value":"Test Photographer"}]} -SC-DEV-ADJ s = { { criteria = "hasAdjustments", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `hasAdjustments isTrue` has no equivalent -SC-DEV-AI s = { { criteria = "hasAI", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `hasAI isTrue` has no equivalent -SC-DEV-AI-EDIT s = { { criteria = "aiEditStatus", operation = "==", value = "denoise", }, combine = "intersect", } static: rule `aiEditStatus ==` has no equivalent +SC-DEV-ADJ s = { { criteria = "hasAdjustments", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasAdjustments","op":"is","value":true}]} +SC-DEV-AI s = { { criteria = "hasAI", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasAi","op":"is","value":true}]} +SC-DEV-AI-EDIT s = { { criteria = "aiEditStatus", operation = "==", value = "denoise", }, combine = "intersect", } {"match":"all","rules":[{"field":"aiEdit","op":"is","value":"denoise"}]} SC-DEV-AI-EDIT-UPD s = { { criteria = "aiUpdateRequiredStatus", operation = "==", value = "rawDetails", }, combine = "intersect", } static: rule `aiUpdateRequiredStatus ==` has no equivalent -SC-DEV-CA s = { { criteria = "removeChromaticAberration", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `removeChromaticAberration isTrue` has no equivalent +SC-DEV-CA s = { { criteria = "removeChromaticAberration", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"removeCa","op":"is","value":true}]} SC-DEV-CROPPED s = { { criteria = "cropped", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"cropped","op":"is","value":true}]} SC-DEV-DEPTH s = { { criteria = "depthMap", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `depthMap isTrue` has no equivalent SC-DEV-EDITS s = { { criteria = "edit", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"edited","op":"is","value":true}]} -SC-DEV-GENAI s = { { criteria = "hasGenAI", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `hasGenAI isTrue` has no equivalent -SC-DEV-HDR s = { { criteria = "hdrEditMode", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `hdrEditMode isTrue` has no equivalent -SC-DEV-LENSCORR s = { { criteria = "profileCorrections", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `profileCorrections isTrue` has no equivalent -SC-DEV-MASKING s = { { criteria = "maskTypeStatus", operation = "==", value = "subject", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent +SC-DEV-GENAI s = { { criteria = "hasGenAI", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasGenAi","op":"is","value":true}]} +SC-DEV-HDR s = { { criteria = "hdrEditMode", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hdrEdit","op":"is","value":true}]} +SC-DEV-LENSCORR s = { { criteria = "profileCorrections", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"lensCorrections","op":"is","value":true}]} +SC-DEV-MASKING s = { { criteria = "maskTypeStatus", operation = "==", value = "subject", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"subject"}]} SC-DEV-NEEDS-UPDATE s = { { criteria = "needsAIUpdate", operation = "==", value = 1, }, combine = "intersect", } static: rule `needsAIUpdate ==` has no equivalent -SC-DEV-POINTCOLOR s = { { criteria = "hasPointColor", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `hasPointColor isTrue` has no equivalent -SC-DEV-PRESET-CUSTOM s = { { criteria = "developPreset", operation = "==", value = "custom", }, combine = "intersect", } static: rule `developPreset ==` has no equivalent -SC-DEV-PRESET-DEFAULT s = { { criteria = "developPreset", operation = "==", value = "default", }, combine = "intersect", } static: rule `developPreset ==` has no equivalent -SC-DEV-PRESET-SPEC s = { { criteria = "developPreset", operation = "==", value = "specified", }, combine = "intersect", } static: rule `developPreset ==` has no equivalent +SC-DEV-POINTCOLOR s = { { criteria = "hasPointColor", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasPointColor","op":"is","value":true}]} +SC-DEV-PRESET-CUSTOM s = { { criteria = "developPreset", operation = "==", value = "custom", }, combine = "intersect", } {"match":"all","rules":[{"field":"developPreset","op":"is","value":"custom"}]} +SC-DEV-PRESET-DEFAULT s = { { criteria = "developPreset", operation = "==", value = "default", }, combine = "intersect", } {"match":"all","rules":[{"field":"developPreset","op":"is","value":"default"}]} +SC-DEV-PRESET-SPEC s = { { criteria = "developPreset", operation = "==", value = "specified", }, combine = "intersect", } {"match":"all","rules":[{"field":"developPreset","op":"is","value":"specified"}]} SC-DEV-PROOF s = { { criteria = "isProofCopy", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `isProofCopy isTrue` has no equivalent -SC-DEV-REMOVE s = { { criteria = "hasRetouch", operation = "==", value = "car", }, combine = "intersect", } static: rule `hasRetouch ==` has no equivalent +SC-DEV-REMOVE s = { { criteria = "hasRetouch", operation = "==", value = "car", }, combine = "intersect", } {"match":"all","rules":[{"group":{"match":"any","rules":[{"field":"manualRemove","op":"is","value":"remove"},{"field":"manualRemove","op":"is","value":"fill"}]}}]} SC-DEV-TREATMENT-BW s = { { criteria = "treatment", operation = "==", value = "grayscale", }, combine = "intersect", } {"match":"all","rules":[{"field":"treatment","op":"is","value":"monochrome"}]} SC-EDIT-LAST-7 s = { { criteria = "touchTime", operation = "inLast", value = 7, value_units = "days", }, combine = "intersect", } {"match":"all","rules":[{"field":"editDate","op":"inLast","value":{"n":7.0,"unit":"day"}}]} SC-EDIT-TODAY s = { { criteria = "touchTime", operation = "==", value = "2026-11-20", value2 = "2026-11-20", }, combine = "intersect", } {"match":"all","rules":[{"field":"editDate","op":"is","value":"2026-11-20"}]} -SC-EXTDESC-EMPTY s = { { criteria = "extDescr", operation = "empty", value = "", value2 = "", }, combine = "intersect", } static: rule `extDescr empty` has no equivalent +SC-EXTDESC-EMPTY s = { { criteria = "extDescr", operation = "empty", value = "", value2 = "", }, combine = "intersect", } {"match":"all","rules":[{"field":"extendedDescription","op":"isEmpty","value":null}]} SC-FASTLOAD s = { { criteria = "fastLoadDNG", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `fastLoadDNG isTrue` has no equivalent SC-FILETYPE-DNG s = { { criteria = "fileFormat", operation = "==", value = "DNG", }, combine = "intersect", } {"match":"all","rules":[{"field":"format","op":"is","value":"DNG"}]} SC-FILETYPE-JPEG s = { { criteria = "fileFormat", operation = "==", value = "JPG", }, combine = "intersect", } {"match":"all","rules":[{"field":"format","op":"is","value":"JPG"}]} @@ -60,8 +60,8 @@ SC-FN-ENDS s = { { criteria = "filename", operation = "endsWith", value = ".jpg" SC-FN-STARTS s = { { criteria = "filename", operation = "beginsWith", value = "EOSR81", }, combine = "intersect", } {"match":"all","rules":[{"field":"fileName","op":"startsWith","value":"EOSR81"}]} SC-FOCAL-GT50 s = { { criteria = "focalLength", operation = ">", value = 50, value2 = 200, }, combine = "intersect", } {"match":"all","rules":[{"field":"focalLength","op":"gt","value":50.0}]} SC-FOCAL-RANGE s = { { criteria = "focalLength", operation = "in", value = 24, value2 = 70, }, combine = "intersect", } {"match":"all","rules":[{"field":"focalLength","op":"between","value":[24.0,70.0]}]} -SC-HAS-SMARTPREVIEW s = { { criteria = "proxyStatus", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `proxyStatus isTrue` has no equivalent -SC-HAS-SNAPSHOTS s = { { criteria = "snapshots", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `snapshots isTrue` has no equivalent +SC-HAS-SMARTPREVIEW s = { { criteria = "proxyStatus", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"smartPreview","op":"is","value":true}]} +SC-HAS-SNAPSHOTS s = { { criteria = "snapshots", operation = "isTrue", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasSnapshots","op":"is","value":true}]} SC-ISO-GE800 s = { { criteria = "isoSpeedRating", operation = ">=", value = 800, }, combine = "intersect", } {"match":"all","rules":[{"field":"iso","op":"gte","value":800.0}]} SC-JOB s = { { criteria = "jobIdentifier", operation = "==", value = "JOB-042", }, combine = "intersect", } static: rule `jobIdentifier ==` has no equivalent SC-KW-CONTAINS s = { { criteria = "keywords", operation = "any", value = "family", }, combine = "intersect", } {"match":"all","rules":[{"field":"keywords","op":"contains","value":"family"}]} @@ -72,7 +72,7 @@ SC-LABEL-BLUE s = { { criteria = "labelColor", operation = "==", value = 4, }, c SC-LABEL-CUSTOM s = { { criteria = "labelColor", operation = "==", value = "custom", }, combine = "intersect", } static: rule `labelColor ==` has no equivalent SC-LABEL-NONE s = { { criteria = "labelColor", operation = "==", value = "none", }, combine = "intersect", } {"match":"all","rules":[{"field":"label","op":"is","value":"none"}]} SC-LABEL-RED s = { { criteria = "labelColor", operation = "==", value = 1, }, combine = "intersect", } {"match":"all","rules":[{"field":"label","op":"is","value":"red"}]} -SC-LABEL-TEXT s = { { criteria = "labelText", operation = "==", value = "Red", value2 = "", }, combine = "intersect", } static: rule `labelText ==` has no equivalent +SC-LABEL-TEXT s = { { criteria = "labelText", operation = "==", value = "Red", value2 = "", }, combine = "intersect", } {"match":"all","rules":[{"field":"labelText","op":"is","value":"Red"}]} SC-LENS s = { { criteria = "lens", operation = "==", value = "RF24-240mm F4-6.3 IS USM", }, combine = "intersect", } {"match":"all","rules":[{"field":"lens","op":"is","value":"RF24-240mm F4-6.3 IS USM"}]} SC-LIKES s = { { criteria = "likes", operation = "isTrue", value = true, }, combine = "intersect", } static: rule `likes isTrue` has no equivalent SC-LOC-CITY s = { { criteria = "city", operation = "==", value = "Naples", }, combine = "intersect", } {"match":"all","rules":[{"field":"city","op":"is","value":"Naples"}]} @@ -87,8 +87,8 @@ SC-PICK-REJ s = { { criteria = "pick", operation = "==", value = -1, }, combine SC-PICK-UNFLAG s = { { criteria = "pick", operation = "==", value = 0, }, combine = "intersect", } {"match":"all","rules":[{"field":"flag","op":"is","value":"none"}]} SC-RATE-EQ0 s = { { criteria = "rating", operation = "==", value = 0, }, combine = "intersect", } {"match":"all","rules":[{"field":"rating","op":"is","value":0.0}]} SC-RATE-GE3 s = { { criteria = "rating", operation = ">=", value = 3, }, combine = "intersect", } {"match":"all","rules":[{"field":"rating","op":"gte","value":3.0}]} -SC-SEARCH-EXIF s = { { criteria = "exif", operation = "any", value = "Canon EOS R8", }, combine = "intersect", } static: rule `exif any` has no equivalent -SC-SEARCH-IPTC s = { { criteria = "iptc", operation = "any", value = "Sunset", }, combine = "intersect", } static: rule `iptc any` has no equivalent +SC-SEARCH-EXIF s = { { criteria = "exif", operation = "any", value = "Canon EOS R8", }, combine = "intersect", } {"match":"all","rules":[{"group":{"match":"any","rules":[{"field":"exifText","op":"contains","value":"Canon"},{"field":"exifText","op":"contains","value":"EOS"},{"field":"exifText","op":"contains","value":"R8"}]}}]} +SC-SEARCH-IPTC s = { { criteria = "iptc", operation = "any", value = "Sunset", }, combine = "intersect", } {"match":"all","rules":[{"field":"iptcText","op":"contains","value":"Sunset"}]} SC-SEARCH-PLUGIN s = { { criteria = "allPluginMetadata", operation = "any", value = "test", }, combine = "intersect", } static: rule `allPluginMetadata any` has no equivalent SC-SHUTTER-FAST s = { { criteria = "shutterSpeed", operation = ">", value = 8.2288186904959, value2 = 0, }, combine = "intersect", } {"match":"all","rules":[{"field":"shutterSpeed","op":"lt","value":0.0033103083181234075}]} SC-SIZE-HEIGHT s = { { criteria = "heightCropped", operation = "<", value = 4000, value2 = 2000, }, combine = "intersect", } static: rule `heightCropped <` has no equivalent @@ -103,11 +103,11 @@ SC-SIZE-WIDTH s = { { criteria = "widthCropped", operation = ">", value = 3000, SC-SIZE-WIDTH-UNCROPPED s = { { criteria = "width", operation = ">", value = 3000, value2 = 2000, }, combine = "intersect", } static: rule `width >` has no equivalent SC-SRC-COLLECTION s = { { criteria = "collection", operation = "any", value = "Holiday", }, combine = "intersect", } {"match":"all","rules":[{"group":{"match":"any","rules":[{"field":"album","op":"is","value":1},{"field":"album","op":"is","value":2}]}}]} SC-SRC-FOLDER s = { { criteria = "folder", operation = "any", value = "local images", }, combine = "intersect", } {"match":"all","rules":[{"group":{"match":"any","rules":[{"field":"folder","op":"contains","value":"local"},{"field":"folder","op":"contains","value":"images"}]}}]} -SC-SRC-PUBLISH-COLL s = { { criteria = "publishCollection", operation = "any", value = "Shared", value2 = "", }, combine = "intersect", } static: rule `publishCollection any` has no equivalent -SC-SRC-PUBLISHED-VIA s = { { criteria = "publishedVia", operation = "any", value = "TestHD", value2 = "", }, combine = "intersect", } static: rule `publishedVia any` has no equivalent +SC-SRC-PUBLISH-COLL s = { { criteria = "publishCollection", operation = "any", value = "Shared", value2 = "", }, combine = "intersect", } {"match":"all","rules":[{"field":"publishCollection","op":"contains","value":"Shared"}]} +SC-SRC-PUBLISHED-VIA s = { { criteria = "publishedVia", operation = "any", value = "TestHD", value2 = "", }, combine = "intersect", } {"match":"all","rules":[{"field":"publishedVia","op":"contains","value":"TestHD"}]} SC-TITLE-EMPTY s = { { criteria = "title", operation = "empty", value = "", }, combine = "intersect", } {"match":"all","rules":[{"field":"title","op":"isEmpty","value":null}]} SC-TITLE-SET s = { { criteria = "title", operation = "any", value = "Sunset", }, combine = "intersect", } {"match":"all","rules":[{"field":"title","op":"contains","value":"Sunset"}]} -SC-OP-adjustments-isfalse s = { { criteria = "hasAdjustments", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `hasAdjustments isFalse` has no equivalent +SC-OP-adjustments-isfalse s = { { criteria = "hasAdjustments", operation = "isFalse", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasAdjustments","op":"is","value":false}]} SC-OP-aperture-between s = { { criteria = "aperture", operation = "in", value = 4.0, value2 = 16, }, combine = "intersect", } {"match":"all","rules":[{"field":"aperture","op":"between","value":[3.96,258.56]}]} SC-OP-aperture-ge s = { { criteria = "aperture", operation = ">=", value = 8, value2 = 0, }, combine = "intersect", } {"match":"all","rules":[{"field":"aperture","op":"gte","value":15.84}]} SC-OP-aperture-gt s = { { criteria = "aperture", operation = ">", value = 7.9, value2 = 0, }, combine = "intersect", } {"match":"all","rules":[{"field":"aperture","op":"gt","value":15.609531075425506}]} @@ -115,7 +115,7 @@ SC-OP-aperture-is s = { { criteria = "aperture", operation = "==", value = 8, va SC-OP-aperture-isnot s = { { criteria = "aperture", operation = "!=", value = 8, value2 = 0, }, combine = "intersect", } static: rule `aperture !=` has no equivalent SC-OP-aperture-le s = { { criteria = "aperture", operation = "<=", value = 8, value2 = 0, }, combine = "intersect", } {"match":"all","rules":[{"field":"aperture","op":"lte","value":16.16}]} SC-OP-aspect-isnot s = { { criteria = "aspectRatio", operation = "!=", value = "landscape", }, combine = "intersect", } {"match":"all","rules":[{"field":"aspect","op":"isNot","value":"landscape"}]} -SC-OP-ca-isfalse s = { { criteria = "removeChromaticAberration", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `removeChromaticAberration isFalse` has no equivalent +SC-OP-ca-isfalse s = { { criteria = "removeChromaticAberration", operation = "isFalse", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"removeCa","op":"is","value":false}]} SC-OP-capture-notinlast s = { { criteria = "captureTime", operation = "notInLast", value = 30, value_units = "days", }, combine = "intersect", } {"match":"all","rules":[{"field":"captureDate","op":"notInLast","value":{"n":30.0,"unit":"day"}}]} SC-OP-capture-thismonth s = { { criteria = "captureTime", operation = "thisMonth", value = false, }, combine = "intersect", } {"match":"all","rules":[{"field":"captureDate","op":"thisMonth","value":null}]} SC-OP-capture-thisweek s = { { criteria = "captureTime", operation = "thisWeek", value = false, }, combine = "intersect", } {"match":"all","rules":[{"field":"captureDate","op":"thisWeek","value":null}]} @@ -141,15 +141,15 @@ SC-OP-edit-thisweek s = { { criteria = "touchTime", operation = "thisWeek", valu SC-OP-edit-thisyear s = { { criteria = "touchTime", operation = "thisYear", value = false, }, combine = "intersect", } {"match":"all","rules":[{"field":"editDate","op":"thisYear","value":null}]} SC-OP-edit-today s = { { criteria = "touchTime", operation = "today", }, combine = "intersect", } {"match":"all","rules":[{"field":"editDate","op":"today","value":null}]} SC-OP-edit-yesterday s = { { criteria = "touchTime", operation = "yesterday", value = false, }, combine = "intersect", } {"match":"all","rules":[{"field":"editDate","op":"yesterday","value":null}]} -SC-OP-exported-before s = { { criteria = "lastExportTimestamp", operation = "<", value = "2027-01-01", value2 = "2026-11-20", }, combine = "intersect", } static: rule `lastExportTimestamp <` has no equivalent -SC-OP-exported-between s = { { criteria = "lastExportTimestamp", operation = "in", value = "2026-01-01", value2 = "2026-12-31", }, combine = "intersect", } static: rule `lastExportTimestamp in` has no equivalent -SC-OP-exported-inlast s = { { criteria = "lastExportTimestamp", operation = "inLast", value = 30, value_units = "days", }, combine = "intersect", } static: rule `lastExportTimestamp inLast` has no equivalent -SC-OP-exported-is s = { { criteria = "lastExportTimestamp", operation = "==", value = "2026-11-19", value2 = "2026-11-19", }, combine = "intersect", } static: rule `lastExportTimestamp ==` has no equivalent -SC-OP-exported-thismonth s = { { criteria = "lastExportTimestamp", operation = "thisMonth", value = false, }, combine = "intersect", } static: rule `lastExportTimestamp thisMonth` has no equivalent -SC-OP-exported-thisweek s = { { criteria = "lastExportTimestamp", operation = "thisWeek", value = false, }, combine = "intersect", } static: rule `lastExportTimestamp thisWeek` has no equivalent -SC-OP-exported-thisyear s = { { criteria = "lastExportTimestamp", operation = "thisYear", value = false, }, combine = "intersect", } static: rule `lastExportTimestamp thisYear` has no equivalent -SC-OP-exported-today s = { { criteria = "lastExportTimestamp", operation = "today", }, combine = "intersect", } static: rule `lastExportTimestamp today` has no equivalent -SC-OP-exported-yesterday s = { { criteria = "lastExportTimestamp", operation = "yesterday", value = false, }, combine = "intersect", } static: rule `lastExportTimestamp yesterday` has no equivalent +SC-OP-exported-before s = { { criteria = "lastExportTimestamp", operation = "<", value = "2027-01-01", value2 = "2026-11-20", }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"before","value":"2027-01-01"}]} +SC-OP-exported-between s = { { criteria = "lastExportTimestamp", operation = "in", value = "2026-01-01", value2 = "2026-12-31", }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"between","value":["2026-01-01","2026-12-31"]}]} +SC-OP-exported-inlast s = { { criteria = "lastExportTimestamp", operation = "inLast", value = 30, value_units = "days", }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"inLast","value":{"n":30.0,"unit":"day"}}]} +SC-OP-exported-is s = { { criteria = "lastExportTimestamp", operation = "==", value = "2026-11-19", value2 = "2026-11-19", }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"is","value":"2026-11-19"}]} +SC-OP-exported-thismonth s = { { criteria = "lastExportTimestamp", operation = "thisMonth", value = false, }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"thisMonth","value":null}]} +SC-OP-exported-thisweek s = { { criteria = "lastExportTimestamp", operation = "thisWeek", value = false, }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"thisWeek","value":null}]} +SC-OP-exported-thisyear s = { { criteria = "lastExportTimestamp", operation = "thisYear", value = false, }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"thisYear","value":null}]} +SC-OP-exported-today s = { { criteria = "lastExportTimestamp", operation = "today", }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"today","value":null}]} +SC-OP-exported-yesterday s = { { criteria = "lastExportTimestamp", operation = "yesterday", value = false, }, combine = "intersect", } {"match":"all","rules":[{"field":"lastExported","op":"yesterday","value":null}]} SC-OP-fastload-isfalse s = { { criteria = "fastLoadDNG", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `fastLoadDNG isFalse` has no equivalent SC-OP-filename-all s = { { criteria = "filename", operation = "all", value = "AE04FF3D jpg", }, combine = "intersect", } {"match":"all","rules":[{"group":{"match":"all","rules":[{"field":"fileName","op":"contains","value":"AE04FF3D"},{"field":"fileName","op":"contains","value":"jpg"}]}}]} SC-OP-filename-noneof s = { { criteria = "filename", operation = "noneOf", value = "AE04FF3D EOSR81", }, combine = "intersect", } {"match":"all","rules":[{"group":{"match":"all","rules":[{"field":"fileName","op":"notContains","value":"AE04FF3D"},{"field":"fileName","op":"notContains","value":"EOSR81"}]}}]} @@ -161,9 +161,9 @@ SC-OP-focal-isnot s = { { criteria = "focalLength", operation = "!=", value = 24 SC-OP-focal-le s = { { criteria = "focalLength", operation = "<=", value = 240, value2 = 200, }, combine = "intersect", } {"match":"all","rules":[{"field":"focalLength","op":"lte","value":240.0}]} SC-OP-focal-lt s = { { criteria = "focalLength", operation = "<", value = 241, value2 = 200, }, combine = "intersect", } {"match":"all","rules":[{"field":"focalLength","op":"lt","value":241.0}]} SC-OP-gps-isnot s = { { criteria = "hasGPSData", operation = "!=", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasGps","op":"is","value":false}]} -SC-OP-hasai-isfalse s = { { criteria = "hasAI", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `hasAI isFalse` has no equivalent -SC-OP-hasgenai-isfalse s = { { criteria = "hasGenAI", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `hasGenAI isFalse` has no equivalent -SC-OP-hdr-isfalse s = { { criteria = "hdrEditMode", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `hdrEditMode isFalse` has no equivalent +SC-OP-hasai-isfalse s = { { criteria = "hasAI", operation = "isFalse", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasAi","op":"is","value":false}]} +SC-OP-hasgenai-isfalse s = { { criteria = "hasGenAI", operation = "isFalse", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasGenAi","op":"is","value":false}]} +SC-OP-hdr-isfalse s = { { criteria = "hdrEditMode", operation = "isFalse", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hdrEdit","op":"is","value":false}]} SC-OP-iso-between s = { { criteria = "isoSpeedRating", operation = "in", value = 250, value2 = 1000, }, combine = "intersect", } {"match":"all","rules":[{"field":"iso","op":"between","value":[250.0,1000.0]}]} SC-OP-iso-gt s = { { criteria = "isoSpeedRating", operation = ">", value = 499, }, combine = "intersect", } {"match":"all","rules":[{"field":"iso","op":"gt","value":499.0}]} SC-OP-iso-is s = { { criteria = "isoSpeedRating", operation = "==", value = 500, }, combine = "intersect", } {"match":"all","rules":[{"field":"iso","op":"is","value":500.0}]} @@ -174,10 +174,10 @@ SC-OP-keywords-begins s = { { criteria = "keywords", operation = "beginsWith", v SC-OP-keywords-noneof s = { { criteria = "keywords", operation = "noneOf", value = "family beach", }, combine = "intersect", } {"match":"all","rules":[{"group":{"match":"all","rules":[{"field":"keywords","op":"notContains","value":"family"},{"field":"keywords","op":"notContains","value":"beach"}]}}]} SC-OP-keywords-words s = { { criteria = "keywords", operation = "words", value = "family beach", }, combine = "intersect", } {"match":"all","rules":[{"field":"keywords","op":"contains","value":"family beach"}]} SC-OP-label-isnot s = { { criteria = "labelColor", operation = "!=", value = 1, }, combine = "intersect", } {"match":"all","rules":[{"field":"label","op":"isNot","value":"red"}]} -SC-OP-lenscorr-isfalse s = { { criteria = "profileCorrections", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `profileCorrections isFalse` has no equivalent +SC-OP-lenscorr-isfalse s = { { criteria = "profileCorrections", operation = "isFalse", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"lensCorrections","op":"is","value":false}]} SC-OP-likes-isfalse s = { { criteria = "likes", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `likes isFalse` has no equivalent SC-OP-pick-isnot s = { { criteria = "pick", operation = "!=", value = 1, }, combine = "intersect", } {"match":"all","rules":[{"field":"flag","op":"isNot","value":"pick"}]} -SC-OP-pointcolor-isfalse s = { { criteria = "hasPointColor", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `hasPointColor isFalse` has no equivalent +SC-OP-pointcolor-isfalse s = { { criteria = "hasPointColor", operation = "isFalse", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasPointColor","op":"is","value":false}]} SC-OP-proof-isfalse s = { { criteria = "isProofCopy", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `isProofCopy isFalse` has no equivalent SC-OP-rating-between s = { { criteria = "rating", operation = "in", value = 2, value2 = 4, }, combine = "intersect", } {"match":"all","rules":[{"field":"rating","op":"between","value":[2.0,4.0]}]} SC-OP-rating-gt s = { { criteria = "rating", operation = ">", value = 2, }, combine = "intersect", } {"match":"all","rules":[{"field":"rating","op":"gt","value":2.0}]} @@ -190,8 +190,8 @@ SC-OP-shutter-is s = { { criteria = "shutterSpeed", operation = "==", value = 6. SC-OP-shutter-isnot s = { { criteria = "shutterSpeed", operation = "!=", value = 6.643856, value2 = 0, }, combine = "intersect", } {"match":"all","rules":[{"group":{"match":"none","rules":[{"field":"shutterSpeed","op":"between","value":[0.00993092626070234,0.010069556825134881]}]}}]} SC-OP-shutter-le s = { { criteria = "shutterSpeed", operation = "<=", value = 6.643856, value2 = 0, }, combine = "intersect", } {"match":"all","rules":[{"field":"shutterSpeed","op":"gte","value":0.00993092626070234}]} SC-OP-shutter-lt s = { { criteria = "shutterSpeed", operation = "<", value = 6.7, value2 = 0, }, combine = "intersect", } {"match":"all","rules":[{"field":"shutterSpeed","op":"gt","value":0.00968521640577333}]} -SC-OP-smartpreview-isfalse s = { { criteria = "proxyStatus", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `proxyStatus isFalse` has no equivalent -SC-OP-snapshots-isfalse s = { { criteria = "snapshots", operation = "isFalse", value = true, }, combine = "intersect", } static: rule `snapshots isFalse` has no equivalent +SC-OP-smartpreview-isfalse s = { { criteria = "proxyStatus", operation = "isFalse", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"smartPreview","op":"is","value":false}]} +SC-OP-snapshots-isfalse s = { { criteria = "snapshots", operation = "isFalse", value = true, }, combine = "intersect", } {"match":"all","rules":[{"field":"hasSnapshots","op":"is","value":false}]} SC-OP-title-notempty s = { { criteria = "title", operation = "notEmpty", value = "", }, combine = "intersect", } {"match":"all","rules":[{"field":"title","op":"isNotEmpty","value":null}]} SC-OP-treatment-isnot s = { { criteria = "treatment", operation = "!=", value = "grayscale", }, combine = "intersect", } {"match":"all","rules":[{"field":"treatment","op":"isNot","value":"monochrome"}]} SC-STRUCT-ALL3 s = { { criteria = "rating", operation = ">=", value = 2, }, { criteria = "keywords", operation = "any", value = "family", }, { criteria = "labelColor", operation = "==", value = 1, }, combine = "intersect", } {"match":"all","rules":[{"field":"rating","op":"gte","value":2.0},{"field":"keywords","op":"contains","value":"family"},{"field":"label","op":"is","value":"red"}]} @@ -216,7 +216,7 @@ SC-VAL-aiedit-dust s = { { criteria = "aiEditStatus", operation = "==", value = SC-VAL-aiedit-expand s = { { criteria = "aiEditStatus", operation = "==", value = "expand", }, combine = "intersect", } static: rule `aiEditStatus ==` has no equivalent SC-VAL-aiedit-lensblur s = { { criteria = "aiEditStatus", operation = "==", value = "lensBlur", }, combine = "intersect", } static: rule `aiEditStatus ==` has no equivalent SC-VAL-aiedit-masking s = { { criteria = "aiEditStatus", operation = "==", value = "masking", }, combine = "intersect", } static: rule `aiEditStatus ==` has no equivalent -SC-VAL-aiedit-none s = { { criteria = "aiEditStatus", operation = "==", value = "none", }, combine = "intersect", } static: rule `aiEditStatus ==` has no equivalent +SC-VAL-aiedit-none s = { { criteria = "aiEditStatus", operation = "==", value = "none", }, combine = "intersect", } {"match":"all","rules":[{"field":"aiEdit","op":"is","value":"none"}]} SC-VAL-aiedit-people s = { { criteria = "aiEditStatus", operation = "==", value = "people", }, combine = "intersect", } static: rule `aiEditStatus ==` has no equivalent SC-VAL-aiedit-rawdetails s = { { criteria = "aiEditStatus", operation = "==", value = "rawDetails", }, combine = "intersect", } static: rule `aiEditStatus ==` has no equivalent SC-VAL-aiedit-reflections s = { { criteria = "aiEditStatus", operation = "==", value = "reflections", }, combine = "intersect", } static: rule `aiEditStatus ==` has no equivalent @@ -228,16 +228,16 @@ SC-VAL-filetype-video s = { { criteria = "fileFormat", operation = "==", value = SC-VAL-label-green s = { { criteria = "labelColor", operation = "==", value = 3, }, combine = "intersect", } {"match":"all","rules":[{"field":"label","op":"is","value":"green"}]} SC-VAL-label-purple s = { { criteria = "labelColor", operation = "==", value = 5, }, combine = "intersect", } {"match":"all","rules":[{"field":"label","op":"is","value":"purple"}]} SC-VAL-label-yellow s = { { criteria = "labelColor", operation = "==", value = 2, }, combine = "intersect", } {"match":"all","rules":[{"field":"label","op":"is","value":"yellow"}]} -SC-VAL-mask-background s = { { criteria = "maskTypeStatus", operation = "==", value = "background", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-brush s = { { criteria = "maskTypeStatus", operation = "==", value = "brush", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-colorrange s = { { criteria = "maskTypeStatus", operation = "==", value = "colorRange", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-depthrange s = { { criteria = "maskTypeStatus", operation = "==", value = "depthRange", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-landscape s = { { criteria = "maskTypeStatus", operation = "==", value = "landscape", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-lineargradient s = { { criteria = "maskTypeStatus", operation = "==", value = "linearGradient", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-luminancerange s = { { criteria = "maskTypeStatus", operation = "==", value = "luminanceRange", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-none s = { { criteria = "maskTypeStatus", operation = "==", value = "none", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-people s = { { criteria = "maskTypeStatus", operation = "==", value = "people", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-radialgradient s = { { criteria = "maskTypeStatus", operation = "==", value = "radialGradient", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-scribble s = { { criteria = "maskTypeStatus", operation = "==", value = "scribble", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent -SC-VAL-mask-sky s = { { criteria = "maskTypeStatus", operation = "==", value = "sky", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent +SC-VAL-mask-background s = { { criteria = "maskTypeStatus", operation = "==", value = "background", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"background"}]} +SC-VAL-mask-brush s = { { criteria = "maskTypeStatus", operation = "==", value = "brush", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"brush"}]} +SC-VAL-mask-colorrange s = { { criteria = "maskTypeStatus", operation = "==", value = "colorRange", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"colorRange"}]} +SC-VAL-mask-depthrange s = { { criteria = "maskTypeStatus", operation = "==", value = "depthRange", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"depthRange"}]} +SC-VAL-mask-landscape s = { { criteria = "maskTypeStatus", operation = "==", value = "landscape", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"landscape"}]} +SC-VAL-mask-lineargradient s = { { criteria = "maskTypeStatus", operation = "==", value = "linearGradient", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"linear"}]} +SC-VAL-mask-luminancerange s = { { criteria = "maskTypeStatus", operation = "==", value = "luminanceRange", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"luminanceRange"}]} +SC-VAL-mask-none s = { { criteria = "maskTypeStatus", operation = "==", value = "none", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"none"}]} +SC-VAL-mask-people s = { { criteria = "maskTypeStatus", operation = "==", value = "people", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"people"}]} +SC-VAL-mask-radialgradient s = { { criteria = "maskTypeStatus", operation = "==", value = "radialGradient", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"radial"}]} +SC-VAL-mask-scribble s = { { criteria = "maskTypeStatus", operation = "==", value = "scribble", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"object"}]} +SC-VAL-mask-sky s = { { criteria = "maskTypeStatus", operation = "==", value = "sky", }, combine = "intersect", } {"match":"all","rules":[{"field":"maskType","op":"is","value":"sky"}]} SC-VAL-mask-unknown s = { { criteria = "maskTypeStatus", operation = "==", value = "unknown", }, combine = "intersect", } static: rule `maskTypeStatus ==` has no equivalent diff --git a/crates/engine/src/memory.rs b/crates/engine/src/memory.rs index 8682e704b7..b9eebd7e5d 100644 --- a/crates/engine/src/memory.rs +++ b/crates/engine/src/memory.rs @@ -271,6 +271,8 @@ fn over(held: u128, limit: usize, bytes: usize) -> bool { bytes > 0 && held > 0 && held.saturating_add(bytes as u128) > limit as u128 } +/// How long [`WorkGate::acquire_until`] waits between looks at its `stop`. +const STOP_STEP: std::time::Duration = std::time::Duration::from_millis(50); /// How long [`WorkGate::acquire_for_job`] waits between looks at the stranded memory while /// abandoned jobs are outstanding (their own clocks run, so it must look again). const JOB_WAIT_STEP: std::time::Duration = std::time::Duration::from_millis(100); @@ -322,6 +324,32 @@ impl WorkGate { Permit { gate: self, bytes, job: None } } + /// [`WorkGate::acquire`] that gives up (`None`) once `stop()` says so while it waits (looked at least every + /// [`STOP_STEP`]); a request that fits at once is granted without asking `stop()`. + pub fn acquire_until(&self, bytes: usize, stop: &dyn Fn() -> bool) -> Option> { + let mut g = self.lock(); + let start = over(g.0, g.1, bytes).then(web_time::Instant::now); + let mut granted = true; + while over(g.0, g.1, bytes) { + if stop() { + granted = false; + break; + } + g = match self.core.cv.wait_timeout(g, STOP_STEP) { + Ok((g, _)) => g, + Err(e) => e.into_inner().0, + }; + } + if let Some(t) = start { + self.count_wait(t.elapsed()); + } + if !granted { + return None; + } + g.0 = g.0.saturating_add(bytes as u128); + Some(Permit { gate: self, bytes, job: None }) + } + /// One acquire that waited `d`: in the gate's counters and this thread's [`gate_wait_nanos`]. fn count_wait(&self, d: std::time::Duration) { self.waits.fetch_add(1, Ordering::Relaxed); @@ -897,3 +925,41 @@ mod budget_tests { assert!(max_budget_of(None) >= 64 * gb); } } + +#[cfg(test)] +mod acquire_until_tests { + use super::WorkGate; + + /// A request waits only when it doesn't fit beside what is held: exactly the room left is granted at once + /// without asking `stop`, one byte more waits and gives up when `stop` says so (and holds nothing then), and + /// the permits are counted until dropped. + #[test] + fn acquire_until_waits_only_past_the_room_left_and_gives_up_on_stop() { + let gate = WorkGate::new(100); + let never = || -> bool { panic!("asked to stop though the request fits") }; + let first = gate.acquire_until(60, &never).expect("fits an empty gate"); + let exact = gate.acquire_until(40, &never).expect("exactly the room left fits"); + assert_eq!(gate.usage().0, 100); + assert!(gate.acquire_until(1, &|| true).is_none(), "one byte over waits, and gives up when asked"); + assert_eq!(gate.usage().0, 100, "a request that gave up holds nothing"); + // it asks again while it waits: gives up at the third look, not the first + let looks = std::cell::Cell::new(0); + assert!( + gate.acquire_until(1, &|| { + looks.set(looks.get() + 1); + looks.get() >= 3 + }) + .is_none() + ); + assert_eq!(looks.get(), 3); + drop(exact); + let one_over = gate.acquire_until(41, &|| true); + assert!(one_over.is_none(), "60 held: 41 does not fit"); + assert!(gate.acquire_until(40, &never).is_some(), "40 does, once the room is back"); + drop(first); + assert_eq!(gate.usage().0, 0); + // nothing held: any request goes ahead, however large; no bytes never wait + assert!(gate.acquire_until(usize::MAX, &never).is_some()); + assert!(gate.acquire_until(0, &never).is_some()); + } +} diff --git a/crates/engine/src/ml.rs b/crates/engine/src/ml.rs index ffe9cb5ab3..57882ea9e8 100644 --- a/crates/engine/src/ml.rs +++ b/crates/engine/src/ml.rs @@ -1567,6 +1567,11 @@ impl Session { let mut failed = 0usize; let mut last_failure = None; for f in finished { + #[cfg(not(target_arch = "wasm32"))] + if f.key == orient::FIT_TRAIN_KEY { + self.orient_fit_train_finished(f.outcome); + continue; + } #[cfg(not(target_arch = "wasm32"))] if let Some(rest) = f.key.strip_prefix(orient::KEY) && let Ok(raw_id) = rest.parse::() @@ -1807,9 +1812,11 @@ impl Session { let active = ready && self.ml.enabled && !self.ml.paused_by_user && !self.ml.paused; let oriented = std::mem::take(&mut self.ml.orient.turned_unseen); let orient_busy = self.ml.orient.busy(); + let orient_fit_done = self.ml.orient.fit_done_unseen.take(); Ok(json!({ "oriented": oriented, "orientBusy": orient_busy, + "orientFitDone": orient_fit_done, "active": active, "ready": ready, "enabled": self.ml.enabled, @@ -2118,6 +2125,7 @@ impl Session { Ok(json!({ "oriented": 0, "orientBusy": false, + "orientFitDone": null, "active": false, "ready": false, "enabled": self.ml_enabled(), @@ -2150,9 +2158,22 @@ impl Session { Err(bad("ml.orientation.fit", "AI orientation detection is not available in the web build")) } + pub(crate) fn ml_orientation_clear(&mut self, _p: &Value) -> crate::Result { + Err(bad("ml.orientation.clear", "AI orientation detection is not available in the web build")) + } + pub(crate) fn ml_orientation_status(&mut self, _p: &Value) -> crate::Result { - Ok( - json!({"classifier": {"available": false, "reason": "AI orientation detection is not available in the web build"}, "running": null, "last": null}), - ) + Ok(json!({ + "classifier": { + "available": false, + "modelInstalled": false, + "reason": "AI orientation detection is not available in the web build", + }, + "running": null, + "fitting": null, + "last": null, + "lastFit": null, + "libraryPhotos": 0, + })) } } diff --git a/crates/engine/src/ml_orient.rs b/crates/engine/src/ml_orient.rs index 527dd0c635..ef8556e63e 100644 --- a/crates/engine/src/ml_orient.rs +++ b/crates/engine/src/ml_orient.rs @@ -15,6 +15,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; +use chrono::{DateTime, Utc}; use lcc_catalog::{Op, PhotoId}; use lcc_develop::DevelopSettings; use lcc_geom::Orientation; @@ -22,10 +23,10 @@ use lcc_ml::orient::{self, Example, FitOptions, Head, Verdict}; use lcc_ml::{Ctx, Encoder, Job, JobError, Outcome, Priority, RgbImage}; use serde_json::{Value, json}; -use crate::Session; use crate::activity::{Cancel, TaskGuard}; use crate::cmd::bad; use crate::ml::Output; +use crate::{AiModel, EngineError, Session}; /// The activity row's kind and labels. pub(crate) const ROW_KIND: &str = "mlOrient"; @@ -33,6 +34,10 @@ const ROW_LABEL: &str = "Detecting orientation"; const FIT_ROW_LABEL: &str = "Fitting the orientation classifier"; /// The jobs' key prefix on the AI queue. pub(crate) const KEY: &str = "orient:"; +/// The job key for the gradient-descent fit step that runs once all photo views are embedded. +pub(crate) const FIT_TRAIN_KEY: &str = "orient-fit:train"; +/// Minimum number of upright photos required to fit and validate a classifier (`orient::fit` needs 8 train + 2 held-out). +const MIN_FIT_PHOTOS: usize = 10; /// The long edge each photo is rendered at: CLIP's 224 px crop with room to downscale from. const VIEW_EDGE: usize = 448; /// How long `wait: true` waits by default, and at most (`photo.autoOrient`; the fit has its own). @@ -48,6 +53,11 @@ struct ViewsOutput { embeddings: Vec>, } +/// What the background gradient-descent fit job gives back once the head has been written to disk. +struct FitTrainOutput { + summary: Value, +} + struct Found { id: PhotoId, shown: Orientation, @@ -67,13 +77,19 @@ struct Run { cancel: Arc, } -/// An `ml.orientation.fit` run. +/// An `ml.orientation.fit` run (phase 1 embeds photo views; phase 2 runs `orient::fit` on the AI queue). struct Fit { waiting: HashSet, total: usize, examples: Vec, failed: usize, + embedder: String, + embed_dim: usize, + steps: usize, + out: PathBuf, + training: bool, row: TaskGuard, + cancel: Arc, } #[derive(Default)] @@ -82,8 +98,12 @@ pub(crate) struct State { fit: Option, /// The last finished run's answer (`ml.orientation.status`). last: Option, + /// The last finished fit's answer (`ml.orientation.status`). + last_fit: Option, /// Photos turned by finished runs since the frontend last asked (`ml.pump` reports and clears it). pub(crate) turned_unseen: usize, + /// Finished background fit event not yet reported by `ml.pump`. + pub(crate) fit_done_unseen: Option, } impl State { @@ -115,25 +135,42 @@ fn verdict_json(f: &Found, applied: bool) -> Value { } impl Session { - /// The orientation classifier for `enc`, and where it comes from: one fitted with `ml.orientation.fit` for this - /// exact model, else the one built in for it. - fn orientation_head(&self, enc: &dyn Encoder) -> Result<(Head, &'static str), String> { + /// Loads the active CLIP encoder, flagging a missing download as [`AiModel::Clip`] when a models folder exists. + fn ensure_orient_encoder(&mut self, cmd: &'static str, fresh: bool) -> crate::Result> { + match self.ensure_ml_encoder(fresh) { + Ok(enc) => Ok(enc), + Err(why) => { + if self.ml_models_dir.is_some() && self.selected_ml_model().is_none() { + Err(EngineError::ModelMissing { model: AiModel::Clip, msg: bad(cmd, why).to_string() }) + } else { + Err(bad(cmd, why)) + } + } + } + } + + /// The orientation classifier for `enc`, where it comes from (`fitted` or `builtIn`), and the fitted file's path + /// when loaded from disk. + fn orientation_head(&self, enc: &dyn Encoder) -> Result<(Head, &'static str, Option), String> { let m = enc.manifest(); let tag = m.tag(); if let Some(dir) = &self.ml_models_dir { let path = fitted_head_path(dir, &m.id); if path.is_file() { match read_capped(&path).and_then(|b| Head::from_json(&b)) { - Ok(h) if h.embedder == tag => return Ok((h, "fitted")), + Ok(h) if h.embedder == tag => return Ok((h, "fitted", Some(path))), Ok(h) => log::warn!("ml: {} was fitted for {}, not {tag}; it is not used", path.display(), h.embedder), Err(e) => log::warn!("ml: {} is not used: {e}", path.display()), } } } if let Some(h) = orient::builtin(&tag) { - return Ok((h, "builtIn")); + return Ok((h, "builtIn", None)); } - Err(format!("there is no orientation classifier for {} yet: fit one on a library of upright photos with `ml.orientation.fit`", m.name)) + Err(format!( + "there is no orientation classifier for {} yet: fit one on a library of upright photos in Settings ▸ AI Models (or with `ml.orientation.fit`)", + m.name + )) } /// Queues photo `id`'s four views on the AI queue. `false` when it can't be (not in the catalogue, queue full). @@ -192,8 +229,14 @@ impl Session { log::warn!("ml: photo {} left out of the orientation fit: {why}", id.0); } } - let done = fit.total - fit.waiting.len(); + let done = fit.total.saturating_sub(fit.waiting.len()); fit.row.progress(done as u64, fit.total as u64); + if let Some(name) = self.catalog.photo(id).map(|p| p.file_name.clone()) { + fit.row.detail(&name); + } + if fit.waiting.is_empty() { + self.start_orient_fit_training(); + } return; } let Some(run) = self.ml.orient.run.as_mut() else { return }; @@ -204,7 +247,7 @@ impl Session { Ok((out, verdict)) => run.found.push(Found { id: out.id, shown: out.shown, verdict }), Err(why) => run.failed.push((id, why)), } - let done = run.total - run.waiting.len(); + let done = run.total.saturating_sub(run.waiting.len()); run.row.progress(done as u64, run.total as u64); if let Some(name) = self.catalog.photo(id).map(|p| p.file_name.clone()) { run.row.detail(&name); @@ -214,19 +257,110 @@ impl Session { } } - /// Called on every drain: a run whose ✕ was clicked stops here (its waiting jobs cancelled, nothing turned). - pub(crate) fn orient_check_cancel(&mut self) { - let cancelled = self.ml.orient.run.as_ref().is_some_and(|r| r.cancel.load(Ordering::Relaxed)); - if !cancelled { + /// Starts phase 2 of `ml.orientation.fit`: runs softmax regression and writes the head on the AI queue so the UI + /// thread never blocks. + fn start_orient_fit_training(&mut self) { + if self.ml.orient.fit.as_ref().is_some_and(|f| f.cancel.load(Ordering::Relaxed)) { + self.orient_check_cancel(); + return; + } + let lib_dir = self.library.as_ref().map(|l| l.dir.display().to_string()).unwrap_or_default(); + let Some(fit) = self.ml.orient.fit.as_mut() else { return }; + if fit.training { return; } - if let Some(run) = self.ml.orient.run.take() { + fit.training = true; + fit.row.detail("Fitting"); + let examples = std::mem::take(&mut fit.examples); + let embedder = fit.embedder.clone(); + let embed_dim = fit.embed_dim; + let source = format!("{} photos in {lib_dir}", examples.len()); + let steps = fit.steps; + let out = fit.out.clone(); + let failed = fit.failed; + let not_reached = fit.waiting.len(); + let cancel = Arc::clone(&fit.cancel); + let work = Job::new(FIT_TRAIN_KEY, move |ctx: &Ctx| -> Result { + ctx.check()?; + if cancel.load(Ordering::Relaxed) { + return Err(JobError::Cancelled); + } + let opts = FitOptions { steps, ..FitOptions::default() }; + let head = orient::fit(&examples, &embedder, embed_dim, &source, &opts).map_err(JobError::Failed)?; + ctx.check()?; + if cancel.load(Ordering::Relaxed) { + return Err(JobError::Cancelled); + } + let bytes = head.to_json().map_err(JobError::Failed)?; + if let Some(parent) = out.parent() { + std::fs::create_dir_all(parent).map_err(|e| JobError::Failed(format!("{}: {e}", parent.display())))?; + } + crate::denoise::write_atomic(&out, &bytes).map_err(|e| JobError::Failed(format!("{}: {e}", out.display())))?; + let summary = json!({ + "done": true, + "ok": true, + "path": out.display().to_string(), + "embedder": head.embedder, + "photos": examples.len(), + "failed": failed, + "notReached": not_reached, + "minConfidence": head.min_confidence, + "report": head.report, + }); + Ok(Box::new(FitTrainOutput { summary })) + }) + .name("Fitting") + .priority(Priority::Interactive); + if let Err(e) = self.ml_submit(work) { + self.ml.orient.fit = None; + let v = json!({"done": true, "ok": false, "error": format!("could not start orientation classifier fit: {e}")}); + self.ml.orient.last_fit = Some(v.clone()); + self.ml.orient.fit_done_unseen = Some(v); + } + } + + /// Completes phase 2 of `ml.orientation.fit` once [`FIT_TRAIN_KEY`] finishes on the AI queue. + pub(crate) fn orient_fit_train_finished(&mut self, outcome: Outcome) { + if self.ml.orient.fit.take().is_none() { + return; + } + let summary = match outcome { + Outcome::Done(any) => match any.downcast::() { + Ok(out) => out.summary, + Err(_) => json!({"done": true, "ok": false, "error": "an answer of the wrong kind"}), + }, + Outcome::Cancelled => json!({"done": true, "cancelled": true}), + Outcome::Failed(why) => json!({"done": true, "ok": false, "error": why}), + }; + self.ml.orient.last_fit = Some(summary.clone()); + self.ml.orient.fit_done_unseen = Some(summary); + } + + /// Called on every drain: a run or fit whose ✕ was clicked stops here (its waiting jobs cancelled, nothing saved). + pub(crate) fn orient_check_cancel(&mut self) { + if self.ml.orient.run.as_ref().is_some_and(|r| r.cancel.load(Ordering::Relaxed)) + && let Some(run) = self.ml.orient.run.take() + { if let Some(q) = self.ml.queue.as_ref() { for id in &run.waiting { q.cancel(&format!("{KEY}{}", id.0)); } } - self.ml.orient.last = Some(json!({"cancelled": true, "checked": run.total - run.waiting.len(), "total": run.total, "turned": []})); + let checked = run.total.saturating_sub(run.waiting.len()); + self.ml.orient.last = Some(json!({"cancelled": true, "checked": checked, "total": run.total, "turned": []})); + } + if self.ml.orient.fit.as_ref().is_some_and(|f| f.cancel.load(Ordering::Relaxed)) + && let Some(fit) = self.ml.orient.fit.take() + { + if let Some(q) = self.ml.queue.as_ref() { + for id in &fit.waiting { + q.cancel(&format!("{KEY}{}", id.0)); + } + q.cancel(FIT_TRAIN_KEY); + } + let v = json!({"done": true, "cancelled": true, "checked": fit.total.saturating_sub(fit.waiting.len()), "total": fit.total}); + self.ml.orient.last_fit = Some(v.clone()); + self.ml.orient.fit_done_unseen = Some(v); } } @@ -305,8 +439,10 @@ impl Session { if self.ml.orient.busy() { return Err(bad(C, "orientation detection is already running; wait for it, or stop it in the activity stack")); } - let enc = self.ensure_ml_encoder(true).map_err(|e| bad(C, e))?; - let (head, _) = self.orientation_head(&*enc).map_err(|e| bad(C, e))?; + let enc = self.ensure_orient_encoder(C, true)?; + let (head, _, _) = self + .orientation_head(&*enc) + .map_err(|e| EngineError::ModelMissing { model: AiModel::OrientationClassifier, msg: bad(C, e).to_string() })?; let min_confidence = min_confidence.unwrap_or(head.min_confidence); let cancel = Arc::new(AtomicBool::new(false)); @@ -343,7 +479,8 @@ impl Session { v } (Some(run), _) => { - json!({"done": false, "queued": run.total, "checked": run.total - run.waiting.len(), "skipped": skipped, "minConfidence": min_confidence}) + let checked = run.total.saturating_sub(run.waiting.len()); + json!({"done": false, "queued": run.total, "checked": checked, "skipped": skipped, "minConfidence": min_confidence}) } (None, None) => json!({"done": false, "queued": 0, "skipped": skipped}), }) @@ -362,8 +499,9 @@ impl Session { self.drain_ml_results(); } - /// `ml.orientation.fit {ids?, out?, steps?: 600, budgetMs?}`: fits the classifier on the library's photos (or - /// `ids`) as they are shown, taken to be upright, and saves it where `photo.autoOrient` finds it (or at `out`). + /// `ml.orientation.fit {ids?, out?, steps?: 600, wait?: true, budgetMs?}`: fits the classifier on the library's + /// photos (or `ids`) as they are shown, taken to be upright, and saves it where `photo.autoOrient` finds it (or at + /// `out`). With `wait: false`, runs asynchronously in the background and finishes via `ml.pump`. pub(crate) fn ml_orientation_fit(&mut self, p: &Value) -> crate::Result { const C: &str = "ml.orientation.fit"; let ids: Vec = match p.get("ids") { @@ -371,71 +509,192 @@ impl Session { Some(_) => self.targets(p).map_err(|e| bad(C, e.to_string()))?, }; let steps = p.get("steps").and_then(Value::as_u64).unwrap_or(600).clamp(10, 20_000) as usize; + let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(true); let budget = p.get("budgetMs").and_then(Value::as_u64).unwrap_or(FIT_WAIT_MS).clamp(1, FIT_WAIT_MAX_MS); if self.ml.orient.busy() { - return Err(bad(C, "orientation detection is already running")); + return Err(bad(C, "orientation detection is already running; wait for it, or stop it in the activity stack")); } - let enc = self.ensure_ml_encoder(true).map_err(|e| bad(C, e))?; + let enc = self.ensure_orient_encoder(C, true)?; let m = enc.manifest().clone(); let out = match p.get("out").and_then(Value::as_str) { Some(path) => PathBuf::from(path), None => fitted_head_path(self.ml_models_dir.as_deref().ok_or_else(|| bad(C, "no AI models folder is configured"))?, &m.id), }; - let row = self.activity.start(ROW_KIND, FIT_ROW_LABEL, Cancel::No); + if ids.len() < MIN_FIT_PHOTOS { + return Err(bad( + C, + format!( + "the open library has {} photo(s); at least {MIN_FIT_PHOTOS} upright photos are needed to fit an orientation classifier", + ids.len() + ), + )); + } + let cancel = Arc::new(AtomicBool::new(false)); + let row = self.activity.start(ROW_KIND, FIT_ROW_LABEL, Cancel::Flag(Arc::clone(&cancel))); + let priority = if wait { Priority::Interactive } else { Priority::Background }; let mut waiting = HashSet::new(); for id in ids { - if !waiting.contains(&id) && self.queue_orient_views(&enc, id, Priority::Interactive) { + if !waiting.contains(&id) && self.queue_orient_views(&enc, id, priority) { waiting.insert(id); } } + if waiting.len() < MIN_FIT_PHOTOS { + if let Some(q) = self.ml.queue.as_ref() { + for id in &waiting { + q.cancel(&format!("{KEY}{}", id.0)); + } + } + return Err(bad( + C, + format!( + "only {} photo(s) could be queued; at least {MIN_FIT_PHOTOS} upright photos are needed to fit an orientation classifier", + waiting.len() + ), + )); + } let total = waiting.len(); row.progress(0, total as u64); - self.ml.orient.fit = Some(Fit { waiting, total, examples: Vec::new(), failed: 0, row }); - self.wait_orient(Duration::from_millis(budget), |s| s.ml.orient.fit.as_ref().is_none_or(|f| f.waiting.is_empty())); - let fit = self.ml.orient.fit.take().ok_or_else(|| bad(C, "the fit was lost"))?; - if let Some(q) = self.ml.queue.as_ref() { - for id in &fit.waiting { - q.cancel(&format!("{KEY}{}", id.0)); + self.ml.orient.last_fit = None; + self.ml.orient.fit_done_unseen = None; + self.ml.orient.fit = Some(Fit { + waiting, + total, + examples: Vec::new(), + failed: 0, + embedder: m.tag(), + embed_dim: m.embed_dim as usize, + steps, + out, + training: false, + row, + cancel, + }); + if !wait { + return Ok(json!({ + "done": false, + "queued": total, + "checked": 0, + "total": total, + "phase": "embedding", + })); + } + self.wait_orient(Duration::from_millis(budget), |s| s.ml.orient.fit.is_none()); + if let Some(fit) = self.ml.orient.fit.take() { + if let Some(q) = self.ml.queue.as_ref() { + for id in &fit.waiting { + q.cancel(&format!("{KEY}{}", id.0)); + } + q.cancel(FIT_TRAIN_KEY); } + if fit.training { + return Err(bad(C, "orientation classifier fit timed out while fitting")); + } + fit.row.detail("Fitting"); + let lib_dir = self.library.as_ref().map(|l| l.dir.display().to_string()).unwrap_or_default(); + let source = format!("{} photos in {lib_dir}", fit.examples.len()); + let opts = FitOptions { steps: fit.steps, ..FitOptions::default() }; + let head = orient::fit(&fit.examples, &fit.embedder, fit.embed_dim, &source, &opts).map_err(|e| bad(C, e))?; + let bytes = head.to_json().map_err(|e| bad(C, e))?; + if let Some(parent) = fit.out.parent() { + std::fs::create_dir_all(parent).map_err(|e| bad(C, format!("{}: {e}", parent.display())))?; + } + crate::denoise::write_atomic(&fit.out, &bytes).map_err(|e| bad(C, e))?; + let summary = json!({ + "done": true, + "ok": true, + "path": fit.out.display().to_string(), + "embedder": head.embedder, + "photos": fit.examples.len(), + "failed": fit.failed, + "notReached": fit.waiting.len(), + "minConfidence": head.min_confidence, + "report": head.report, + }); + self.ml.orient.last_fit = Some(summary.clone()); + self.ml.orient.fit_done_unseen = None; + return Ok(summary); } - fit.row.detail("Fitting"); - let source = format!("{} photos in {}", fit.examples.len(), self.library.as_ref().map(|l| l.dir.display().to_string()).unwrap_or_default()); - let opts = FitOptions { steps, ..FitOptions::default() }; - let head = orient::fit(&fit.examples, &m.tag(), m.embed_dim as usize, &source, &opts).map_err(|e| bad(C, e))?; - let bytes = head.to_json().map_err(|e| bad(C, e))?; - if let Some(parent) = out.parent() { - std::fs::create_dir_all(parent).map_err(|e| bad(C, format!("{}: {e}", parent.display())))?; - } - crate::denoise::write_atomic(&out, &bytes).map_err(|e| bad(C, e))?; + self.ml.orient.fit_done_unseen = None; + match self.ml.orient.last_fit.clone() { + Some(v) if v.get("ok").and_then(Value::as_bool) == Some(true) => Ok(v), + Some(v) if v.get("cancelled").and_then(Value::as_bool) == Some(true) => { + Err(EngineError::Cancelled("orientation classifier fit cancelled".into())) + } + Some(v) => Err(bad(C, v.get("error").and_then(Value::as_str).unwrap_or("orientation classifier fit failed"))), + None => Err(bad(C, "the orientation classifier fit did not produce a result")), + } + } + + /// `ml.orientation.clear {}`: removes the fitted orientation classifier file for the active CLIP model. + pub(crate) fn ml_orientation_clear(&mut self, _p: &Value) -> crate::Result { + const C: &str = "ml.orientation.clear"; + if self.ml.orient.busy() { + return Err(bad(C, "orientation detection is already running; wait for it, or stop it in the activity stack")); + } + let dir = self.ml_models_dir.clone().ok_or_else(|| bad(C, "no AI models folder is configured"))?; + let model_id = match self.ensure_ml_encoder(false) { + Ok(enc) => enc.manifest().id.clone(), + Err(_) => self.selected_ml_model().ok_or_else(|| bad(C, "no AI embedding model is installed"))?, + }; + let path = fitted_head_path(&dir, &model_id); + let removed = if path.is_file() { + std::fs::remove_file(&path).map_err(|e| bad(C, format!("{}: {e}", path.display())))?; + true + } else { + false + }; + self.ml.orient.last_fit = None; Ok(json!({ - "path": out.display().to_string(), - "embedder": head.embedder, - "photos": fit.examples.len(), - "failed": fit.failed, - "notReached": fit.waiting.len(), - "minConfidence": head.min_confidence, - "report": head.report, + "removed": removed, + "path": path.display().to_string(), })) } /// `ml.orientation.status {}`. pub(crate) fn ml_orientation_status(&mut self, _p: &Value) -> crate::Result { + let model_installed = self.selected_ml_model().is_some(); let head = match self.ensure_ml_encoder(false) { Ok(enc) => match self.orientation_head(&*enc) { - Ok((h, origin)) => json!({ - "available": true, - "origin": origin, - "embedder": h.embedder, - "minConfidence": h.min_confidence, - "source": h.source, - "report": h.report, - }), - Err(why) => json!({"available": false, "reason": why}), + Ok((h, origin, path)) => { + let fitted_at = path + .as_deref() + .and_then(|p| std::fs::metadata(p).ok()) + .and_then(|m| m.modified().ok()) + .map(|t| DateTime::::from(t).format("%Y-%m-%d").to_string()); + json!({ + "available": true, + "modelInstalled": true, + "origin": origin, + "embedder": h.embedder, + "minConfidence": h.min_confidence, + "source": h.source, + "report": h.report, + "path": path.map(|p| p.display().to_string()), + "fittedAt": fitted_at, + }) + } + Err(why) => json!({"available": false, "modelInstalled": true, "reason": why}), }, - Err(why) => json!({"available": false, "reason": why}), + Err(why) => json!({"available": false, "modelInstalled": model_installed, "reason": why}), }; - let running = self.ml.orient.run.as_ref().map(|r| json!({"checked": r.total - r.waiting.len(), "total": r.total})); - Ok(json!({"classifier": head, "running": running, "last": self.ml.orient.last})) + let running = self.ml.orient.run.as_ref().map(|r| json!({"checked": r.total.saturating_sub(r.waiting.len()), "total": r.total})); + let fitting = self.ml.orient.fit.as_ref().map(|f| { + json!({ + "phase": if f.training { "fitting" } else { "embedding" }, + "checked": f.total.saturating_sub(f.waiting.len()), + "total": f.total, + "failed": f.failed, + }) + }); + let library_photos = self.catalog.photos().filter(|ph| ph.in_library()).count(); + Ok(json!({ + "classifier": head, + "running": running, + "fitting": fitting, + "last": self.ml.orient.last, + "lastFit": self.ml.orient.last_fit, + "libraryPhotos": library_photos, + })) } } @@ -660,4 +919,98 @@ mod tests { assert_eq!(r["turnedCount"], 1, "{r}"); assert_eq!(orientation(&s, "p03.png"), Orientation::Normal); } + + #[test] + fn missing_classifier_and_clip_report_model_missing_error_kind() { + let (mut s, _, _) = session_with("missing-kind", &[("a.png", 0)]); + let err = s.execute("photo.autoOrient", &json!({"ids": [id_of(&s, "a.png").0], "wait": true})).unwrap_err(); + assert_eq!(err.kind(), crate::ErrorKind::ModelMissing(AiModel::OrientationClassifier), "{err}"); + + // without any installed CLIP model, auto orient reports ModelMissing(Clip) + let d = temp_dir("missing-clip"); + let mut s2 = Session::new().with_fs(); + s2.ml_models_dir = Some(d.join("ml-models")); + s2.open_library(d.join("lib"), false).unwrap(); + let p = d.join("photos").join("a.png"); + write_sky_png(&p, 0, 40); + s2.execute("library.import", &json!({"paths": [p.to_string_lossy()]})).unwrap(); + let err = s2.execute("photo.autoOrient", &json!({"ids": [id_of(&s2, "a.png").0], "wait": true})).unwrap_err(); + assert_eq!(err.kind(), crate::ErrorKind::ModelMissing(AiModel::Clip), "{err}"); + } + + #[test] + fn fit_rejects_too_few_photos_immediately() { + let (mut s, _, _) = session_with("too-few", &[("a.png", 0), ("b.png", 0)]); + let err = s.execute("ml.orientation.fit", &json!({"wait": false})).unwrap_err(); + assert!(err.to_string().contains("at least 10"), "{err}"); + assert!(!s.ml.orient.busy(), "failed validation must not leave a fit running"); + } + + #[test] + fn background_fit_completes_through_ml_pump_and_clear_removes_it() { + let names: Vec = (0..20).map(|i| format!("bg{i:02}.png")).collect(); + let photos: Vec<(&str, u8)> = names.iter().map(|n| (n.as_str(), 0)).collect(); + let (mut s, models, tag) = session_with("bg-fit", &photos); + + let started = s.execute("ml.orientation.fit", &json!({"steps": 100, "wait": false})).unwrap(); + assert_eq!(started["done"], false, "{started}"); + assert_eq!(started["queued"], 20, "{started}"); + assert!(s.activity.list().iter().any(|t| t.kind == ROW_KIND && t.label == FIT_ROW_LABEL)); + + let st = s.execute("ml.orientation.status", &json!({})).unwrap(); + assert!(st["fitting"].is_object(), "{st}"); + assert_eq!(st["libraryPhotos"], 20, "{st}"); + + let mut fit_done = None; + for _ in 0..1500 { + let pump = s.execute("ml.pump", &json!({})).unwrap(); + if !pump["orientFitDone"].is_null() { + fit_done = Some(pump["orientFitDone"].clone()); + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + let fit_done = fit_done.expect("background fit finishes through ml.pump"); + assert_eq!(fit_done["ok"], true, "{fit_done}"); + assert_eq!(fit_done["photos"], 20, "{fit_done}"); + assert_eq!(fit_done["embedder"], tag.as_str(), "{fit_done}"); + assert!(s.activity.list().iter().all(|t| t.kind != ROW_KIND), "activity row goes when fit finishes"); + + let st = s.execute("ml.orientation.status", &json!({})).unwrap(); + assert_eq!(st["classifier"]["available"], true, "{st}"); + assert_eq!(st["classifier"]["origin"], "fitted", "{st}"); + assert!(st["classifier"]["path"].is_string(), "{st}"); + assert!(st["classifier"]["fittedAt"].is_string(), "{st}"); + assert!(st["fitting"].is_null(), "{st}"); + + let id = id_of(&s, "bg05.png"); + s.execute("photo.rotateLeft", &json!({"ids": [id.0]})).unwrap(); + let r = s.execute("photo.autoOrient", &json!({"ids": [id.0], "wait": true})).unwrap(); + assert_eq!(r["turnedCount"], 1, "{r}"); + assert_eq!(orientation(&s, "bg05.png"), Orientation::Normal); + + // clear removes the fitted head and status returns to not fitted + let cleared = s.execute("ml.orientation.clear", &json!({})).unwrap(); + assert_eq!(cleared["removed"], true, "{cleared}"); + assert!(!fitted_head_path(&models, "test-clip").exists()); + let st = s.execute("ml.orientation.status", &json!({})).unwrap(); + assert_eq!(st["classifier"]["available"], false, "{st}"); + assert_eq!(st["classifier"]["modelInstalled"], true, "{st}"); + } + + #[test] + fn cancelling_background_fit_stops_without_writing_classifier() { + let names: Vec = (0..20).map(|i| format!("cn{i:02}.png")).collect(); + let photos: Vec<(&str, u8)> = names.iter().map(|n| (n.as_str(), 0)).collect(); + let (mut s, models, _) = session_with("bg-cancel", &photos); + + let started = s.execute("ml.orientation.fit", &json!({"steps": 200, "wait": false})).unwrap(); + assert_eq!(started["done"], false, "{started}"); + let task_id = s.activity.list().iter().find(|t| t.kind == ROW_KIND).expect("fit activity row").id; + s.execute("activity.cancel", &json!({"id": task_id})).unwrap(); + let pump = s.execute("ml.pump", &json!({})).unwrap(); + assert_eq!(pump["orientFitDone"]["cancelled"], true, "{pump}"); + assert!(!s.ml.orient.busy()); + assert!(!fitted_head_path(&models, "test-clip").exists()); + } } diff --git a/crates/engine/src/raw_decoder.rs b/crates/engine/src/raw_decoder.rs index 772cbce341..93d5c33b41 100644 --- a/crates/engine/src/raw_decoder.rs +++ b/crates/engine/src/raw_decoder.rs @@ -1,4 +1,5 @@ -//! Which raw decoder reads each camera body's files: **Auto**, the app's own decoder (`lcc-raw`) or **LibRaw**. +//! Which raw decoder reads each camera body's files: **Auto**, the app's own decoder (`lcc-raw`), **LibRaw** or +//! **dnglab** (its pure-Rust `rawler` library). //! //! The person's choice is kept per camera (the library label, [`lcc_catalog::camera_label`] of the file's Exif make //! and model) in the library preferences (`library.preferences` `rawDecoder`) and installed here @@ -6,16 +7,18 @@ //! decoder reads it, the mosaic is demosaiced, coloured and developed by the app's own (pure Rust) pipeline. //! //! LibRaw itself is not part of the app (it is C++): a host that can run it hands a [`Backend`] to -//! [`install_libraw`]. Where none is installed (the web build, Android, a desktop without it) a camera set to LibRaw -//! is read by `lcc-raw`, and the Settings panel says LibRaw is not available. +//! [`install_libraw`]. dnglab's decoder is Rust, built in with the engine's `dnglab` feature (the desktop app and the +//! CLI; not the web build, where a panic in a decoder can't be caught), or installed with [`install_dnglab`]. Where a +//! chosen decoder is missing, the camera is read by `lcc-raw` and the Settings panel says that decoder is not +//! available. //! //! - **Auto** (the default, and every camera without a choice): `lcc-raw`, exactly as before; a file it refuses as an -//! unsupported variant goes to LibRaw when LibRaw is available, else to the embedded preview as before. -//! - **lcc-raw**: `lcc-raw` only, never LibRaw. -//! - **LibRaw**: LibRaw first; when it fails (or is not available) the file is read by `lcc-raw`. +//! unsupported variant goes to LibRaw, then dnglab, whichever are available, else to the embedded preview as before. +//! - **lcc-raw**: `lcc-raw` only, never another decoder. +//! - **LibRaw** / **dnglab**: that decoder first; when it fails (or is not available) the file is read by `lcc-raw`. //! //! A backend returns the file's mosaic as a [`Frame`]; [`Frame::into_raw_image`] checks it as hostile input and fills -//! in what LibRaw doesn't say (metadata, orientation, embedded lens corrections, default crop) from `lcc-raw`'s +//! in what the decoder doesn't say (metadata, orientation, embedded lens corrections, default crop) from `lcc-raw`'s //! header probe of the same file when that agrees on the sensor geometry. use std::collections::BTreeMap; @@ -35,10 +38,12 @@ pub enum Decoder { Lcc, /// LibRaw, with `lcc-raw` when LibRaw fails or is not available. Libraw, + /// dnglab (`rawler`), with `lcc-raw` when it fails or is not available. + Dnglab, } impl Decoder { - pub const ALL: [Decoder; 3] = [Decoder::Auto, Decoder::Lcc, Decoder::Libraw]; + pub const ALL: [Decoder; 4] = [Decoder::Auto, Decoder::Lcc, Decoder::Libraw, Decoder::Dnglab]; /// The id commands and `prefs.json` use. pub fn id(self) -> &'static str { @@ -46,21 +51,23 @@ impl Decoder { Decoder::Auto => "auto", Decoder::Lcc => "lcc", Decoder::Libraw => "libraw", + Decoder::Dnglab => "dnglab", } } - /// An id as a person may type it (`auto`, `lcc`, `lcc-raw`, `lccraw`, `libraw`), any case. + /// An id as a person may type it (`auto`, `lcc`, `lcc-raw`, `lccraw`, `libraw`, `dnglab`, `rawler`), any case. pub fn parse(s: &str) -> Option { match s.trim().to_ascii_lowercase().replace(['-', '_', ' '], "").as_str() { "auto" | "" | "default" => Some(Decoder::Auto), "lcc" | "lccraw" | "builtin" => Some(Decoder::Lcc), "libraw" => Some(Decoder::Libraw), + "dnglab" | "rawler" => Some(Decoder::Dnglab), _ => None, } } } -/// A raw file's mosaic as an external decoder (LibRaw) unpacked it, before any processing: no black subtraction, +/// A raw file's mosaic as another decoder (LibRaw, dnglab) unpacked it, before any processing: no black subtraction, /// scaling, white balance or demosaic. #[derive(Clone, Debug, PartialEq)] pub struct Frame { @@ -79,6 +86,9 @@ pub struct Frame { pub white: f32, /// The image area within the data (LibRaw `left_margin`, `top_margin`, `width`, `height`). pub active_area: lcc_raw::Rect, + /// The default crop within the image area, when the decoder knows one (dnglab's camera data); used only when + /// `lcc-raw`'s header probe doesn't see the same image area. + pub crop: Option, /// As-shot white balance multipliers, green = 1 (LibRaw `cam_mul`), when known. pub wb_multipliers: Option<[f32; 3]>, /// XYZ (D65) → camera matrix (LibRaw `cam_xyz`), when the decoder knows one; used only when the app has none. @@ -93,18 +103,18 @@ impl Frame { /// orientation, opcodes and crop taken from `lcc-raw`'s header probe of `bytes` when it reads the same sensor /// area, else from its Exif. pub fn into_raw_image(self, bytes: &[u8]) -> Result { - let Frame { width, height, data, cfa, bits, black, white, active_area, wb_multipliers, xyz_to_camera } = self; - let samples = width.checked_mul(height).ok_or("LibRaw frame size overflows")?; + let Frame { width, height, data, cfa, bits, black, white, active_area, crop, wb_multipliers, xyz_to_camera } = self; + let samples = width.checked_mul(height).ok_or("the decoder's frame size overflows")?; if width == 0 || height == 0 || samples > MAX_SAMPLES { - return Err(format!("LibRaw frame is {width} x {height}, outside the sizes the app reads")); + return Err(format!("the decoder's frame is {width} x {height}, outside the sizes the app reads")); } if data.len() != samples { - return Err(format!("LibRaw frame has {} samples for {width} x {height}", data.len())); + return Err(format!("the decoder's frame has {} samples for {width} x {height}", data.len())); } if let Some(c) = &cfa { let cells = c.width.checked_mul(c.height).unwrap_or(0); if c.width == 0 || c.height == 0 || c.width > 16 || c.height > 16 || c.pattern.len() != cells || c.pattern.iter().any(|&p| p > 2) { - return Err("LibRaw frame has an unusable colour filter pattern".into()); + return Err("the decoder's frame has an unusable colour filter pattern".into()); } } let a = active_area; @@ -113,7 +123,7 @@ impl Frame { && a.x.checked_add(a.width).is_some_and(|r| r <= width) && a.y.checked_add(a.height).is_some_and(|b| b <= height); if !fits { - return Err("LibRaw frame's image area lies outside its data".into()); + return Err("the decoder's frame has its image area outside its data".into()); } let black_ok = black.repeat_rows > 0 && black.repeat_cols > 0 @@ -122,19 +132,19 @@ impl Frame { && black.values.len() == black.repeat_rows * black.repeat_cols && black.values.iter().chain(&black.delta_h).chain(&black.delta_v).all(|v| v.is_finite()); if !black_ok || !white.is_finite() || white <= black.mean() || white > 65535.0 { - return Err(format!("LibRaw frame has unusable levels (black {}, white {white})", black.mean())); + return Err(format!("the decoder's frame has unusable levels (black {}, white {white})", black.mean())); } let wb_multipliers = wb_multipliers.filter(|m| m.iter().all(|v| v.is_finite() && *v > 0.0)); let xyz_to_camera = xyz_to_camera.filter(|m| m.0.iter().flatten().all(|v| v.is_finite()) && m.0.iter().flatten().any(|v| *v != 0.0)); - // what LibRaw doesn't describe comes from the app's own reading of the headers, when it sees the same area + // what the decoder doesn't describe comes from the app's own reading of the headers, when it sees the same area let header = lcc_raw::probe_info(bytes).ok(); let same_area = header.as_ref().is_some_and(|h| h.active_area.width == a.width && h.active_area.height == a.height); let metadata = header.as_ref().map(|h| h.metadata.clone()).unwrap_or_else(|| lcc_meta::extract(bytes)); let orientation = header.as_ref().map(|h| h.orientation).or(metadata.orientation).unwrap_or(lcc_raw::Orientation::Normal); let format = header.as_ref().map(|h| h.format).or_else(|| lcc_raw::probe(bytes)).unwrap_or(lcc_raw::RawFormat::OtherTiff); let mut color = header.as_ref().map(|h| h.color.clone()).unwrap_or_default(); - // LibRaw's matrix is the last resort: the file's own comes first, then the app's camera table (applied later, and + // the decoder's matrix is the last resort: the file's own comes first, then the app's camera table (applied later, and // only when the file has none), so a body the app knows keeps its measured matrices on this path as on lcc-raw's if !lcc_raw::color::has_matrix(&color) && !app_table_has_matrix(metadata.make.as_deref(), metadata.model.as_deref()) @@ -145,7 +155,7 @@ impl Frame { } let (crop, opcodes, lens_metadata, pixel_aspect) = match header.filter(|_| same_area) { Some(h) => (h.crop, h.opcodes, h.lens_metadata, h.pixel_aspect), - None => (lcc_raw::Rect::new(0, 0, a.width, a.height), Default::default(), Default::default(), 1.0), + None => (crop.unwrap_or(lcc_raw::Rect::new(0, 0, a.width, a.height)), Default::default(), Default::default(), 1.0), }; let wb_multipliers = wb_multipliers.map(|m| { let g = if m[1] > 0.0 { m[1] } else { 1.0 }; @@ -182,11 +192,11 @@ fn app_table_has_matrix(make: Option<&str>, model: Option<&str>) -> bool { lcc_raw::spectral::find(make, model).is_some() || lcc_camdb::find(make, model).is_some_and(|e| lcc_raw::color::has_matrix(&e.color_data())) } -/// Something that runs LibRaw on a file's bytes (installed by the host that can, see [`install_libraw`]). +/// Something that runs another decoder (LibRaw, dnglab) on a file's bytes (see [`install_libraw`], [`install_dnglab`]). pub trait Backend: Send + Sync { /// Shown in Settings and logs, e.g. `LibRaw 0.22`. fn name(&self) -> String; - /// The file's unpacked mosaic, or why LibRaw can't read it. + /// The file's unpacked mosaic, or why the decoder can't read it. fn decode(&self, bytes: &[u8]) -> Result; } @@ -209,6 +219,48 @@ fn built_in() -> Option> { None } +fn dnglab_slot() -> &'static RwLock>> { + static R: OnceLock>>> = OnceLock::new(); + R.get_or_init(|| RwLock::new(linked_dnglab())) +} + +/// dnglab, when this build has it (the `dnglab` feature). +fn linked_dnglab() -> Option> { + #[cfg(feature = "dnglab")] + return Some(Arc::new(Dnglab)); + #[cfg(not(feature = "dnglab"))] + None +} + +/// dnglab's `rawler` built into the app (`lcc-dnglab`). +#[cfg(feature = "dnglab")] +struct Dnglab; + +#[cfg(feature = "dnglab")] +impl Backend for Dnglab { + fn name(&self) -> String { + lcc_dnglab::name() + } + fn decode(&self, bytes: &[u8]) -> Result { + let u = lcc_dnglab::decode(bytes)?; + let [x, y, w, h] = u.image_area; + let crop = u.crop.map(|[cx, cy, cw, ch]| lcc_raw::Rect::new(cx, cy, cw, ch)); + Ok(Frame { + width: u.width, + height: u.height, + data: u.data, + cfa: u.pattern.map(|p| lcc_raw::Cfa { width: p.width, height: p.height, pattern: p.colors }), + bits: u.bits, + black: lcc_raw::BlackLevel { repeat_rows: u.black.rows, repeat_cols: u.black.cols, values: u.black.values, ..Default::default() }, + white: u.white, + active_area: lcc_raw::Rect::new(x, y, w, h), + crop, + wb_multipliers: u.as_shot, + xyz_to_camera: u.xyz_to_camera.map(lcc_raw::Mat3), + }) + } +} + /// LibRaw linked into the app (`lcc-libraw`). #[cfg(feature = "libraw")] struct Linked; @@ -236,6 +288,7 @@ impl Frame { black: lcc_raw::BlackLevel { repeat_rows: u.black.rows, repeat_cols: u.black.cols, values: u.black.values, ..Default::default() }, white: u.white, active_area: lcc_raw::Rect::new(x, y, w, h), + crop: None, wb_multipliers: u.as_shot, xyz_to_camera: u.xyz_to_camera.map(lcc_raw::Mat3), } @@ -254,19 +307,23 @@ fn ensure_key() { ONCE.get_or_init(refresh_key); } -/// [`key`]: a hash of the choices and the backend's name, 0 with neither, stable from one run to the next (it is in +/// [`key`]: a hash of the choices and the backends' names, 0 with none, stable from one run to the next (it is in /// the thumbnail cache's keys on disk). static KEY: AtomicU64 = AtomicU64::new(0); fn refresh_key() { let map = choices().read().unwrap_or_else(PoisonError::into_inner).clone(); - let name = libraw_name(); - let key = if map.is_empty() && name.is_none() { + let names = [libraw_name(), dnglab_name()]; + let key = if map.is_empty() && names.iter().all(Option::is_none) { 0 } else { // FNV-1a over the choices and the backend's name let mut h: u64 = 0xcbf2_9ce4_8422_2325; - let text = map.iter().map(|(c, d)| format!("{c}={};", d.id())).collect::() + "|" + name.as_deref().unwrap_or_default(); + let text = map.iter().map(|(c, d)| format!("{c}={};", d.id())).collect::() + + "|" + + names[0].as_deref().unwrap_or_default() + + "|" + + names[1].as_deref().unwrap_or_default(); for b in text.bytes() { h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); } @@ -294,6 +351,26 @@ pub fn install_libraw(backend: Option>) { refresh_key(); } +/// Install (or remove, `None`) the dnglab backend. +pub fn install_dnglab(backend: Option>) { + *dnglab_slot().write().unwrap_or_else(PoisonError::into_inner) = backend; + refresh_key(); +} + +/// The dnglab backend's name, when one is installed. +pub fn dnglab_name() -> Option { + dnglab().map(|b| b.name()) +} + +/// Whether this build can run dnglab: false on the web and in builds made without the `dnglab` feature. +pub fn dnglab_built_in() -> bool { + dnglab().is_some() +} + +fn dnglab() -> Option> { + dnglab_slot().read().unwrap_or_else(PoisonError::into_inner).clone() +} + /// The LibRaw backend's name, when one is installed. pub fn libraw_name() -> Option { libraw().map(|b| b.name()) @@ -313,8 +390,8 @@ fn choice_in(map: &BTreeMap, camera: &str) -> Decoder { map.get(&camera_key(camera)).copied().unwrap_or_default() } -/// Changes whenever a choice or the backend changes: part of the decode and render cache keys, so pictures read by -/// the other decoder are not reused. 0 with no choices and no LibRaw (the cache keys are then what they were before +/// Changes whenever a choice or a backend changes: part of the decode and render cache keys, so pictures read by +/// another decoder are not reused. 0 with no choices and no other decoder (the cache keys are then what they were before /// decoders could be chosen). pub fn key() -> u64 { ensure_key(); @@ -326,9 +403,10 @@ pub fn key() -> u64 { pub enum Used { Lcc, Libraw, + Dnglab, } -/// Decode a raw file with its camera's decoder (see the module docs). With no choices and no LibRaw this is +/// Decode a raw file with its camera's decoder (see the module docs). With no choices and no other decoder this is /// [`lcc_raw::decode`]. pub fn decode(bytes: &[u8]) -> lcc_raw::Result { decode_reporting(bytes).map(|(r, _)| r) @@ -336,9 +414,9 @@ pub fn decode(bytes: &[u8]) -> lcc_raw::Result { /// [`decode`], saying which decoder read the file. pub fn decode_reporting(bytes: &[u8]) -> lcc_raw::Result<(lcc_raw::RawImage, Used)> { - let backend = libraw(); + let (libraw, dnglab) = (libraw(), dnglab()); let any_choice = !choices().read().unwrap_or_else(PoisonError::into_inner).is_empty(); - if backend.is_none() && !any_choice { + if libraw.is_none() && dnglab.is_none() && !any_choice { return lcc_raw::decode(bytes).map(|r| (r, Used::Lcc)); } let choice = if any_choice { @@ -347,34 +425,49 @@ pub fn decode_reporting(bytes: &[u8]) -> lcc_raw::Result<(lcc_raw::RawImage, Use } else { Decoder::Auto }; - decode_as(bytes, choice, backend.as_deref()) + decode_as(bytes, choice, libraw.as_deref(), dnglab.as_deref()) } -/// Decode `bytes` as `choice` says, with `backend` as LibRaw. -pub fn decode_as(bytes: &[u8], choice: Decoder, backend: Option<&dyn Backend>) -> lcc_raw::Result<(lcc_raw::RawImage, Used)> { - let with_libraw = |b: &dyn Backend| -> Result { b.decode(bytes)?.into_raw_image(bytes) }; - match (choice, backend) { - (Decoder::Lcc, _) | (Decoder::Auto, None) => lcc_raw::decode(bytes).map(|r| (r, Used::Lcc)), - (Decoder::Libraw, None) => { - log::info!("raw decoder: LibRaw is chosen for this camera but not available here; reading the file with lcc-raw"); - lcc_raw::decode(bytes).map(|r| (r, Used::Lcc)) +/// Decode `bytes` as `choice` says, with `libraw` and `dnglab` as those decoders (`None`: not available). +pub fn decode_as( + bytes: &[u8], + choice: Decoder, + libraw: Option<&dyn Backend>, + dnglab: Option<&dyn Backend>, +) -> lcc_raw::Result<(lcc_raw::RawImage, Used)> { + let lcc = || lcc_raw::decode(bytes).map(|r| (r, Used::Lcc)); + let with = |b: &dyn Backend| -> Result { b.decode(bytes)?.into_raw_image(bytes) }; + // the chosen decoder first, lcc-raw when it fails or is missing + let chosen = |b: Option<&dyn Backend>, used: Used, what: &str| match b { + None => { + log::info!("raw decoder: {what} is chosen for this camera but not available here; reading the file with lcc-raw"); + lcc() } - (Decoder::Libraw, Some(b)) => match with_libraw(b) { - Ok(r) => Ok((r, Used::Libraw)), + Some(b) => match with(b) { + Ok(r) => Ok((r, used)), Err(e) => { log::warn!("raw decoder: {} could not read the file ({e}); reading it with lcc-raw", b.name()); - lcc_raw::decode(bytes).map(|r| (r, Used::Lcc)) + lcc() } }, - (Decoder::Auto, Some(b)) => match lcc_raw::decode(bytes) { + }; + match choice { + Decoder::Lcc => lcc(), + Decoder::Libraw => chosen(libraw, Used::Libraw, "LibRaw"), + Decoder::Dnglab => chosen(dnglab, Used::Dnglab, "dnglab"), + Decoder::Auto => match lcc_raw::decode(bytes) { Ok(r) => Ok((r, Used::Lcc)), - Err(lcc_raw::RawError::Unsupported(why)) => match with_libraw(b) { - Ok(r) => Ok((r, Used::Libraw)), - Err(e) => { - log::info!("raw decoder: {} could not read an unsupported variant either ({e})", b.name()); - Err(lcc_raw::RawError::Unsupported(why)) + // a variant lcc-raw refuses goes to LibRaw, then dnglab; when neither reads it the refusal stands + Err(lcc_raw::RawError::Unsupported(why)) => { + for (b, used) in [(libraw, Used::Libraw), (dnglab, Used::Dnglab)] { + let Some(b) = b else { continue }; + match with(b) { + Ok(r) => return Ok((r, used)), + Err(e) => log::info!("raw decoder: {} could not read an unsupported variant either ({e})", b.name()), + } } - }, + Err(lcc_raw::RawError::Unsupported(why)) + } Err(e) => Err(e), }, } diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index be33f7069f..1642059e1b 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -82,6 +82,37 @@ pub fn portable_name(name: &str, replacement: char) -> String { s } +/// Most bytes one file or folder name may have: APFS, ext4 and NTFS all stop at 255, and a longer +/// name fails at write time with a bare "File name too long". (The path as a whole has limits too, +/// Windows' among them, which depend on the destination and aren't checked here.) +pub const MAX_NAME_BYTES: usize = 255; + +/// Bytes a file's stem leaves free in [`MAX_NAME_BYTES`] for what is added after naming: a +/// collision number (`_2`… `-1000000`) and a sidecar's `.xmp`. +pub const NAME_SPARE_BYTES: usize = 16; + +/// `name` cut to at most `max` bytes at a character boundary, with the dots and spaces the cut leaves +/// at the end dropped (a name can't end in one, [`portable_name`]); `true` when it was cut. The one +/// length rule for every name the app builds from a template. +pub fn cap_name_bytes(name: String, max: usize) -> (String, bool) { + if name.len() <= max { + return (name, false); + } + let mut n = max; + while !name.is_char_boundary(n) { + n -= 1; + } + let kept = name.get(..n).unwrap_or_default().trim_end_matches(|c: char| c == '.' || c.is_whitespace()); + (kept.to_string(), true) +} + +/// A file's stem cut so that `stem` + `.` + an extension of `ext_bytes` bytes + [`NAME_SPARE_BYTES`] +/// fit [`MAX_NAME_BYTES`] (an absurdly long extension still leaves [`NAME_SPARE_BYTES`] for the stem); `true` when it was cut. +pub fn cap_stem_bytes(stem: String, ext_bytes: usize) -> (String, bool) { + let room = MAX_NAME_BYTES.saturating_sub(NAME_SPARE_BYTES).saturating_sub(ext_bytes.saturating_add(1)).max(NAME_SPARE_BYTES); + cap_name_bytes(stem, room) +} + /// Rename Photos and import folder levels replace a forbidden character with `-`. fn sanitize(s: &str) -> String { portable_name(s, '-') @@ -276,6 +307,99 @@ pub const TEMPLATE_NOTES: &[&str] = &[ "Characters not allowed in file names (/ \\ : * ? \" < > |) become -; an existing name gets -1, -2….", ]; +/// Where a template is used. Rename Photos and import renaming share [`TOKENS`] and [`TEMPLATE_NOTES`]; export file +/// naming has the same tokens plus [`EXPORT_ONLY_TOKENS`], expands a bare `{seq}` to 3 digits, replaces forbidden +/// characters with `_` and numbers a taken name from `-2`, so its help, examples and unknown-tag check come from +/// here, not from the rename text (FX-225). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TemplateKind { + /// Rename Photos, import renaming and import folders. + Rename, + /// The Export dialog's File Naming. + Export, +} + +/// Tokens only export file naming has: `{custom}` is the Export dialog's **Custom text**. +pub const EXPORT_ONLY_TOKENS: &[TokenHelp] = + &[TokenHelp { tag: "{custom}", aliases: &[], meaning: "The Custom text field, as typed (up to 120 characters)" }]; + +/// How export file names behave, one sentence each (shown under the token list in the Export dialog). +pub const EXPORT_NOTES: &[&str] = &[ + "The format's extension is added (an Original export keeps its own); {ext} only puts the original one inside the name as well.", + "A blank template keeps the original names.", + "{date} is the capture time; a photo without one uses the time it was imported.", + "Missing metadata ({camera}, {title}…) leaves an empty gap; a name that comes out empty keeps the original name.", + "Unknown tags stay as typed, so check the preview for a {typo}.", + "Characters not allowed in file names (/ \\ : * ? \" < > |) become _; a name over 255 bytes is cut.", + "With If file exists set to Add number, a name already taken gets -2, -3….", +]; + +/// The `{custom}` token of an export template: `text` trimmed and cut to [`MAX_TEXT`] characters, used as typed (its own +/// braces aren't expanded again). The `extra` of [`expand_tokens_with`] for export file names, which the help's +/// examples use too. +pub fn custom_token(text: &str) -> impl Fn(&str, Option<&str>, &str) -> Option { + let custom: String = text.trim().chars().take(MAX_TEXT).collect(); + move |token, _, _| (token == "custom").then(|| custom.clone()) +} + +impl TemplateKind { + /// Every token the template language has here, in the order the help shows them: [`TOKENS`], then the tokens only + /// this place has (`{custom}` before the `{text:…}` tag, which stays last). + pub fn tokens(self) -> Vec { + let mut all = TOKENS.to_vec(); + if self == Self::Export { + let at = all.iter().position(|t| t.tag.starts_with("{text:")).unwrap_or(all.len()); + all.splice(at..at, EXPORT_ONLY_TOKENS.iter().copied()); + } + all + } + + /// How templates behave here, one sentence each. + pub fn notes(self) -> &'static [&'static str] { + match self { + Self::Rename => TEMPLATE_NOTES, + Self::Export => EXPORT_NOTES, + } + } + + /// Digits of a bare `{seq}`. + fn seq_width(self) -> usize { + match self { + Self::Rename => 1, + Self::Export => 3, + } + } + + /// `tag` expanded for [`sample_photo`] (sequence number 1) as this place expands it: the help's example column. + pub fn example(self, tag: &str) -> String { + let filled = fill_texts(tag, &|_| Some("R+A".into())); + match self { + Self::Rename => expand_tokens(&filled, &sample_photo(), 1, self.seq_width()), + Self::Export => expand_tokens_with(&filled, &sample_photo(), 1, self.seq_width(), &custom_token("Gallery")), + } + } + + /// The `{…}` tags in `template` that aren't tokens here (they stay as typed), for a warning. + pub fn unknown_tokens(self, template: &str) -> Vec { + let p = sample_photo(); + let expand = |tag: &str| match self { + Self::Rename => expand_tokens(tag, &p, 1, 1), + Self::Export => expand_tokens_with(tag, &p, 1, 1, &custom_token("x")), + }; + let mut out = Vec::new(); + let mut rest = template; + while let Some(i) = rest.find('{') { + let Some(j) = rest[i..].find('}') else { break }; + let tag = &rest[i..i + j + 1]; + if expand(tag) == tag && !out.iter().any(|t| t == tag) { + out.push(tag.to_string()); + } + rest = &rest[i + j + 1..]; + } + out + } +} + /// The tokens as one line (`{name} {num} {seq} …`), for compact hints. pub fn token_summary() -> String { TOKENS.iter().map(|t| t.tag).collect::>().join(" ") @@ -314,7 +438,7 @@ pub fn sample_photo() -> Photo { /// The token as expanded for [`sample_photo`] (sequence number 1), for the help's example column. pub fn token_example(tag: &str) -> String { - expand_tokens(&fill_texts(tag, &|_| Some("R+A".into())), &sample_photo(), 1, 1) + TemplateKind::Rename.example(tag) } /// Why a folder template (`{date:%Y}/{date:%Y%m%d}`) can't be used, if it can't: it must be @@ -346,26 +470,16 @@ pub fn expand_folder(template: &str, p: &Photo, seq: usize) -> Vec { .map(str::trim) .filter(|s| !s.is_empty() && !matches!(*s, "." | "..")) .map(|s| { - let v = sanitize(&expand_tokens(s, p, seq, 1)); + let v = cap_name_bytes(sanitize(&expand_tokens(s, p, seq, 1)), MAX_NAME_BYTES).0; if v.is_empty() { "unknown".to_string() } else { v } }) .collect() } -/// The `{…}` tags in `template` that aren't tokens (they stay as typed), for a warning. +/// The `{…}` tags in `template` that aren't tokens (they stay as typed), for a warning +/// ([`TemplateKind::unknown_tokens`] for Rename Photos and import renaming). pub fn unknown_tokens(template: &str) -> Vec { - let p = sample_photo(); - let mut out = Vec::new(); - let mut rest = template; - while let Some(i) = rest.find('{') { - let Some(j) = rest[i..].find('}') else { break }; - let tag = &rest[i..i + j + 1]; - if expand_tokens(tag, &p, 1, 1) == tag && !out.iter().any(|t| t == tag) { - out.push(tag.to_string()); - } - rest = &rest[i + j + 1..]; - } - out + TemplateKind::Rename.unknown_tokens(template) } /// Every token with its meaning and example, the date directives and the notes, as JSON (the @@ -398,6 +512,8 @@ pub fn expand(template: &str, p: &Photo, seq: usize) -> String { if stem_out.is_empty() { stem_out = sanitize(stem); } + // a name over the file system's limit fails at write time; the cut one is what the plan shows + stem_out = cap_stem_bytes(stem_out, ext.len()).0; if stem_out.is_empty() { stem_out = "photo".into(); } @@ -1683,6 +1799,39 @@ pub(crate) mod tests { use super::*; use std::cell::RefCell; + /// A name over the file system's limit is cut at a character boundary, for a file (with room for its + /// extension and what is added after naming) and for a folder level (FX-224): at the limit, one byte + /// below, one above, and a multi-byte character straddling the cut. + #[test] + fn names_are_cut_to_the_file_system_length_at_a_character_boundary() { + let cut = |s: &str, max: usize| cap_name_bytes(s.to_string(), max); + assert_eq!(cut(&"a".repeat(255), 255), ("a".repeat(255), false), "exactly 255"); + assert_eq!(cut(&"a".repeat(254), 255), ("a".repeat(254), false), "one below"); + assert_eq!(cut(&"a".repeat(256), 255), ("a".repeat(255), true), "one above"); + // é is two bytes: starting at byte 254 it would end at 256 + assert_eq!(cut(&format!("{}é", "a".repeat(254)), 255), ("a".repeat(254), true), "straddles the cut"); + assert_eq!(cut(&format!("{}é", "a".repeat(253)), 255), (format!("{}é", "a".repeat(253)), false), "ends at the cut"); + assert_eq!(cut(&format!("{}😀", "a".repeat(252)), 255), ("a".repeat(252), true), "four-byte character straddles"); + assert_eq!(cut(&format!("{}.. b", "a".repeat(253)), 255), ("a".repeat(253), true), "dots and spaces left at the end go"); + assert_eq!(cut("anything", 0), (String::new(), true)); + // a file's stem leaves room for its extension and the spare + let room = MAX_NAME_BYTES - NAME_SPARE_BYTES - ".jpg".len(); + assert_eq!(cap_stem_bytes("x".repeat(room), 3), ("x".repeat(room), false)); + assert_eq!(cap_stem_bytes("x".repeat(room + 1), 3), ("x".repeat(room), true)); + let (kept, was_cut) = cap_stem_bytes("x".repeat(1000), 10_000); + assert!(was_cut && kept.len() == NAME_SPARE_BYTES, "an absurd extension still leaves the spare: {}", kept.len()); + // Rename Photos and import folders + let mut p = sample_photo(); + p.file_name = "IMG_1.NEF".into(); + p.meta.title = format!("{}é", "t".repeat(MAX_NAME_BYTES - 1)); + let renamed = expand("{title}", &p, 1); + assert!(renamed.len() <= MAX_NAME_BYTES - NAME_SPARE_BYTES && renamed.ends_with(".NEF"), "{} bytes", renamed.len()); + let folders = expand_folder("{title}/{creator}", &p, 1); + assert_eq!(folders[0], "t".repeat(MAX_NAME_BYTES - 1), "a folder level keeps up to 255 bytes"); + p.meta.title = "t".repeat(MAX_NAME_BYTES); + assert_eq!(expand_folder("{title}", &p, 1), ["t".repeat(MAX_NAME_BYTES)], "exactly 255 stays whole"); + } + /// Every name the app builds from a template (an export's file, Rename Photos, an import folder /// level, an Edit In copy) is `portable_name` of the expansion, each with its own replacement /// character and fallback: no forbidden or control character, no leading or trailing dot or @@ -2340,6 +2489,38 @@ pub(crate) mod tests { } } + /// The Export dialog's tag help is one table with `{custom}` in it, expanded as an export expands (a bare `{seq}` + /// has 3 digits), with its own notes, and its unknown-tag check knows `{custom}` (FX-225). Rename keeps its own + /// table, where `{custom}` is not a token. + #[test] + fn export_tag_help_is_one_table_that_has_custom() { + let export = TemplateKind::Export; + let tokens = export.tokens(); + assert_eq!(tokens.len(), TOKENS.len() + EXPORT_ONLY_TOKENS.len()); + assert_eq!(TemplateKind::Rename.tokens(), TOKENS); + assert!(tokens.last().is_some_and(|t| t.tag.starts_with("{text:")), "the text tag stays last"); + assert_eq!(tokens.iter().filter(|t| t.tag == "{custom}").count(), 1); + for t in &tokens { + for tag in std::iter::once(&t.tag).chain(t.aliases) { + let v = export.example(tag); + assert!(!v.contains('{') && !v.is_empty(), "{tag} is not an export token (example {v:?})"); + } + } + assert_eq!(export.example("{custom}"), "Gallery"); + assert_eq!((export.example("{seq}"), TemplateKind::Rename.example("{seq}")), ("001".to_string(), "1".to_string())); + assert_eq!(token_example("{seq:3}"), export.example("{seq:3}")); + // the unknown-tag check: `{custom}` is known to export, a typo is not, and Rename Photos still lists `{custom}` + assert!(export.unknown_tokens("{custom}-{seq:1}").is_empty()); + assert_eq!(export.unknown_tokens("{custom}{camra}{Custom}{camra}"), vec!["{camra}".to_string()]); + assert_eq!(TemplateKind::Rename.unknown_tokens("{custom}"), vec!["{custom}".to_string()]); + assert_eq!(unknown_tokens("{custom}"), vec!["{custom}".to_string()]); + // the notes say what export does: `_`, a numbering from -2, the length cut, the format's extension + let notes = export.notes().join(" "); + assert!(notes.contains("become _") && notes.contains("-2, -3") && notes.contains(&MAX_NAME_BYTES.to_string()), "{notes}"); + assert!(!notes.contains("always added") && !notes.contains("become -") && !notes.contains("-1, -2"), "{notes}"); + assert_eq!(TemplateKind::Rename.notes(), TEMPLATE_NOTES); + } + #[test] fn templates() { let mut p = Photo::new(PhotoId(1), Source::Demo { scene: 1 }, "IMG_0042.CR2", "CR2", 1, 1, "2026-01-01T00:00:00"); diff --git a/crates/engine/src/run_presets.rs b/crates/engine/src/run_presets.rs index d9beb22e5b..9073a0e228 100644 --- a/crates/engine/src/run_presets.rs +++ b/crates/engine/src/run_presets.rs @@ -7,7 +7,7 @@ use serde_json::{Value, json}; -use crate::export::{CANCELLED, Destination, DestinationMode, ExportOptions, PreparedExport, TakenNames, prepare_batch, run_batch_sharing}; +use crate::export::{BatchStop, Destination, DestinationMode, ExportOptions, PreparedExport, TakenNames, prepare_batch, run_batch_sharing}; /// The most presets one run takes. pub const MAX_PRESETS: usize = 32; @@ -32,6 +32,8 @@ pub struct Prepared { steps: Vec, /// Photos that couldn't be prepared for a recipe: `{photo, preset, error}`. failed: Vec, + /// The plug-in export destination every file of the run goes to (`pluginDestination`), if one was named. + destination: Option, } /// What a run did. @@ -107,7 +109,16 @@ fn folder_arg(p: &Value, key: &str) -> Result, String> { } } -/// Set up `export.runPresets {presetIds, ids?, dir?, fallbackDir?}`: every argument is checked and every recipe's +/// The plug-in export destination of `p.pluginDestination` (`{plugin, destination, args?}`): absent, or well formed. +fn destination_arg(p: &Value) -> Result, String> { + match p.get("pluginDestination") { + None | Some(Value::Null) => Ok(None), + Some(d) if crate::export::is_plugin_destination(d) => Ok(Some(d.clone())), + Some(v) => Err(format!("`pluginDestination` must be {{plugin, destination, args?: object}}, got {v}")), + } +} + +/// Set up `export.runPresets {presetIds, ids?, dir?, fallbackDir?, pluginDestination?}`: every argument is checked and every recipe's /// folder known before anything is decoded or written. `dir` replaces every preset's folder; `fallbackDir` is the /// folder of the presets that name none (and export to a specific folder), the others keep their own. pub fn prepare(s: &mut crate::Session, p: &Value) -> Result { @@ -115,6 +126,7 @@ pub fn prepare(s: &mut crate::Session, p: &Value) -> Result { let ids = photo_ids(s, p)?; let dir = folder_arg(p, "dir")?; let fallback = folder_arg(p, "fallbackDir")?; + let destination = destination_arg(p)?; let mut recipes = Vec::with_capacity(names.len()); for name in &names { let mut call = json!({"preset": name}); @@ -163,7 +175,7 @@ pub fn prepare(s: &mut crate::Session, p: &Value) -> Result { } } } - Ok(Prepared { recipes, steps, failed }) + Ok(Prepared { recipes, steps, failed, destination }) } impl Prepared { @@ -176,12 +188,27 @@ impl Prepared { self.steps.is_empty() } + /// The photos of the run, each once, in the order of their first step: what Previous Export holds afterwards + /// ([`crate::Session::record_export`], which keeps what it is given as it is). + pub fn photos(&self) -> Vec { + let mut seen = std::collections::HashSet::new(); + self.steps.iter().map(|s| s.photo).filter(|id| seen.insert(*id)).collect() + } + + /// The plug-in export destination the whole run was given (`pluginDestination`): it gets every file of every + /// preset, after the export hooks. + pub fn plugin_destination(&self) -> Option<&Value> { + self.destination.as_ref() + } + /// Export photo by photo, each decoded once for all recipes; `progress(done, file)` before each - /// photo. A set `cancel` stops it between steps; the files written so far stay. The run is one export as far - /// as its own files go: one never replaces another, whichever photo and preset wrote it ([`TakenNames`]). - pub fn run(self, cancel: &std::sync::atomic::AtomicBool, progress: &mut dyn FnMut(usize, &str)) -> Report { + /// photo. A set `cancel` stops it at once: between photos and presets, and within the one in flight, which gives + /// up at its next step (decode, render, encode) and writes nothing; the files written so far stay (FX-218). The + /// run is one export as far as its own files go: one never replaces another, whichever photo and preset wrote it + /// ([`TakenNames`]). + pub fn run(self, cancel: &std::sync::Arc, progress: &mut dyn FnMut(usize, &str)) -> Report { use std::sync::atomic::Ordering; - let Prepared { recipes, steps, failed } = self; + let Prepared { recipes, steps, failed, .. } = self; let mut per: Vec> = vec![Vec::new(); recipes.len()]; for f in failed { if let Some(ri) = recipes.iter().position(|r| f.get("preset").and_then(Value::as_str) == Some(r.name.as_str())) { @@ -189,7 +216,6 @@ impl Prepared { } } let stopped = || cancel.load(Ordering::Relaxed); - let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let (mut decodes, photos) = (0, steps.len()); let mut cancelled = false; let mut taken = TakenNames::default(); @@ -213,8 +239,9 @@ impl Prepared { break; } let (Some(r), Some(out)) = (recipes.get(ri), per.get_mut(ri)) else { continue }; - flag.store(false, Ordering::Relaxed); - let res = run_batch_sharing( + // (the run's own cancel flag, so a cancel reaches the photo in flight; with a flag the batch's one photo + // renders on a lane thread of its own, which is what lets the run leave at once) + let outcome = run_batch_sharing( vec![item], &r.opts, &r.to, @@ -222,13 +249,14 @@ impl Prepared { &|path| std::path::Path::new(path).exists(), false, &mut |_, _| !stopped(), - Some(flag.clone()), + Some(cancel.clone()), &mut taken, ); - match res { - Ok(files) => out.extend(files), - Err(e) if e == CANCELLED => cancelled = true, - Err(e) => out.push(json!({"photo": step.photo.0, "file": step.label, "error": e})), + // (a failed photo is an entry of `files`: the run doesn't stop at a failure) + out.extend(outcome.files); + // a cancel the batch saw itself counts too, also one that came after the check above (FX-187) + if outcome.stopped == Some(BatchStop::Cancelled) { + cancelled = true; } } if cancelled { @@ -242,9 +270,22 @@ impl Prepared { } } -/// `export.runPresets`: prepare, run with one activity row (✕ stops it), mark the photos exported. +/// `export.runPresets`: prepare, run with one activity row (✕ stops it), then what a single `app.export` does once +/// its files are written: mark the photos exported, make them Previous Export, run the plug-in export hooks and the +/// plug-in destination (`pluginDestination`; results in `plugins`). +/// +/// The run is on the calling thread, as every engine command is (the CLI and the MCP server have no other; the desktop +/// app's control channel answers on its UI thread, where the row's ✕ can't be clicked until the run is over: a window +/// that wants the background run uses `app.runPresets`, which goes through [`prepare`] and [`Prepared::run`] on a +/// worker). Refused while another export is in flight ([`crate::export::ensure_none_running`]), as `app.runPresets` is +/// (FX-217). +/// +/// Not done, because they can't mean one thing for several presets: Apple Photos (a preset that adds to it is +/// refused by [`prepare`]) and Export with Previous (`last_export` holds one preset's options, and a run has several). pub fn run_command(s: &mut crate::Session, p: &Value) -> Result { + crate::export::ensure_none_running(&s.activity)?; let prepared = prepare(s, p)?; + let (photos, destination) = (prepared.photos(), prepared.plugin_destination().cloned()); let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let row = s.activity.start_batch("export", "Exporting", crate::activity::Cancel::Flag(cancel.clone())); let total = prepared.len() as u64; @@ -257,7 +298,17 @@ pub fn run_command(s: &mut crate::Session, p: &Value) -> Result { }); drop(row); crate::export::mark_exported(s, &report.files); - Ok(report.json()) + // the Previous Export source in the Library panel, as after `app.export` + s.record_export(&photos); + let mut out = report.json(); + // plug-in export hooks, then the destination the run named: given every file the presets wrote + #[cfg(not(target_arch = "wasm32"))] + if let Some(plugins) = crate::cmd::plugins::after_export(s, &report.files, destination.as_ref()) { + out["plugins"] = json!(plugins); + } + #[cfg(target_arch = "wasm32")] + let _ = destination; + Ok(out) } #[cfg(test)] @@ -288,7 +339,6 @@ mod tests { json!({"presetIds": [""]}), json!({"presetIds": ["No Such Preset"], "ids": [id]}), json!({"presetIds": ["Small", "small"], "ids": [id]}), - json!({"presetIds": vec!["Small"; MAX_PRESETS + 1], "ids": [id]}), json!({"presetIds": ["Small"], "ids": [u64::MAX]}), json!({"presetIds": ["Small"], "ids": [-1]}), json!({"presetIds": ["Small"], "ids": "x"}), @@ -304,6 +354,54 @@ mod tests { assert!(err.contains("dir"), "{err}"); } + /// The cap is on the number of presets (FX-242): 33 distinct ones are refused, naming the cap, before anything is + /// written; 32 are accepted, and so is one fewer. (33 copies of one name are refused too, but by the duplicate + /// check, which says nothing of the cap.) + #[test] + fn at_most_the_cap_of_distinct_presets_are_accepted() { + assert_eq!(MAX_PRESETS, 32, "the manual and this test name the number"); + let dir = lcc_testkit::TempDir::new("lcc-run-presets-cap"); + let mut s = Session::with_demo(); + let names: Vec = (1..=MAX_PRESETS + 1).map(|i| format!("Preset {i:02}")).collect(); + for n in &names { + let d = dir.join(n); + s.execute("export.savePreset", &json!({"name": n, "params": {"format": "jpeg", "longEdge": 32, "dir": d.to_string_lossy()}})).unwrap(); + } + let id = s.visible_cloned()[0].0; + let mut try_with = |count: usize| prepare(&mut s, &json!({"presetIds": &names[..count], "ids": [id]})).map(|p| p.recipes.len()); + for count in [MAX_PRESETS - 1, MAX_PRESETS] { + assert_eq!(try_with(count), Ok(count), "{count} presets"); + } + let err = try_with(MAX_PRESETS + 1).expect_err("one past the cap is refused"); + assert!(err.contains("33 presets") && err.contains("at most 32"), "{err}"); + assert!(!dir.join(&names[0]).exists(), "nothing written for a refused run"); + // the cap counts the names given and is checked before the duplicate check: a long list of one name is a + // list over the cap + let twice = prepare(&mut s, &json!({"presetIds": vec![names[0].as_str(); MAX_PRESETS + 1], "ids": [id]})).err().unwrap(); + assert!(twice.contains("at most 32"), "the cap is checked first: {twice}"); + } + + /// Previous Export holds each photo of a run once, in the run's order, however many presets exported it (and + /// whatever the steps hold: the same photo twice, or in several steps, is one photo). + #[test] + fn previous_export_holds_each_photo_of_a_run_once_in_order() { + let dir = lcc_testkit::TempDir::new("lcc-run-presets-once"); + let mut s = session_with_presets(&dir); + let ids: Vec = s.visible_cloned().iter().take(3).map(|p| p.0).collect(); + // exported by two presets each, asked for in an order that is not the catalog's, one photo named twice + let order = [ids[2], ids[0], ids[2], ids[1]]; + s.execute("export.runPresets", &json!({"presetIds": ["Small", "Smaller"], "ids": order})).unwrap(); + let prev: Vec = s.previous_export.iter().map(|p| p.0).collect(); + assert_eq!(prev, vec![ids[2], ids[0], ids[1]], "once each, first-seen order"); + // the photos of a run set up with a photo in several steps + let mut prepared = prepare(&mut s, &json!({"presetIds": ["Small", "Smaller"], "ids": [ids[0], ids[1]]})).unwrap(); + for photo in [ids[1], ids[0], ids[1], ids[2]] { + prepared.steps.push(Step { photo: lcc_catalog::PhotoId(photo), label: String::new(), items: Vec::new() }); + } + let photos: Vec = prepared.photos().iter().map(|p| p.0).collect(); + assert_eq!(photos, vec![ids[0], ids[1], ids[2]]); + } + #[test] fn several_presets_share_one_decode_per_photo_and_one_activity_row() { let dir = lcc_testkit::TempDir::new("lcc-run-presets"); @@ -329,13 +427,82 @@ mod tests { assert!(ids.iter().all(|id| s.catalog.photo(lcc_catalog::PhotoId(*id)).unwrap().exported.is_some())); } + /// What a single `app.export` does once its files are written (FX-193): the photos become Previous Export, the + /// plug-in export hooks get the files, and a plug-in destination the run names gets them after the hooks. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_run_makes_previous_export_and_runs_the_plugin_hooks_and_destination() { + use crate::cmd::plugins::{ + manager, + tests::{hook_module, turn}, + }; + let _plugins = crate::cmd::plugins::TEST_PLUGINS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _turn = turn(); + manager().get_or_insert_with(lcc_plugins::Manager::in_memory).install_bytes(&hook_module("test.runpresets"), None, false).unwrap(); + let dir = lcc_testkit::TempDir::new("lcc-run-presets-after"); + let mut s = session_with_presets(&dir); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + assert!(s.previous_export.is_empty()); + let dest = json!({"plugin": "test.runpresets", "destination": "d"}); + let r = s.execute("export.runPresets", &json!({"presetIds": ["Small", "Smaller"], "ids": ids, "pluginDestination": dest})); + let r = r.unwrap(); + assert_eq!(r["written"], 4, "{r}"); + // Previous Export is the run's photos + let mut prev: Vec = s.previous_export.iter().map(|p| p.0).collect(); + prev.sort_unstable(); + let mut want = ids.clone(); + want.sort_unstable(); + assert_eq!(prev, want); + // the export hook ran, then the destination (the last entry) + let plugins = r["plugins"].as_array().unwrap_or_else(|| panic!("no plug-in results: {r}")); + assert_eq!(plugins.len(), 2, "{plugins:?}"); + assert!(plugins[0]["plugin"] == "test.runpresets" && plugins[0]["ok"]["seen"] == true, "{plugins:?}"); + assert!(plugins[1]["destination"] == "d" && plugins[1]["ok"]["seen"] == true, "{plugins:?}"); + // without a destination only the hook runs; a destination that isn't there is reported, not skipped + let r = s.execute("export.runPresets", &json!({"presetIds": ["Small"], "ids": ids})).unwrap(); + assert_eq!(r["plugins"].as_array().unwrap().len(), 1, "{r}"); + let gone = json!({"plugin": "test.runpresets", "destination": "nope"}); + let r = s.execute("export.runPresets", &json!({"presetIds": ["Small"], "ids": ids, "pluginDestination": gone})).unwrap(); + assert!(r["plugins"].as_array().unwrap().last().unwrap()["error"].is_string(), "{r}"); + manager().get_or_insert_with(lcc_plugins::Manager::in_memory).uninstall("test.runpresets").unwrap(); + // no plug-in, no `plugins`; the photos are still Previous Export + let r = s.execute("export.runPresets", &json!({"presetIds": ["Small"], "ids": [ids[0]]})).unwrap(); + assert!(r.get("plugins").is_none(), "{r}"); + assert_eq!(s.previous_export.iter().map(|p| p.0).collect::>(), vec![ids[0]]); + } + + #[test] + fn a_malformed_plugin_destination_is_refused_before_anything_is_written() { + let dir = lcc_testkit::TempDir::new("lcc-run-presets-dest"); + let mut s = session_with_presets(&dir); + let id = s.visible_cloned()[0].0; + for d in [ + json!("d"), + json!(5), + json!([]), + json!({}), + json!({"plugin": "p"}), + json!({"destination": "d"}), + json!({"plugin": 1, "destination": "d"}), + json!({"plugin": "p", "destination": "d", "args": 3}), + ] { + let p = json!({"presetIds": ["Small"], "ids": [id], "pluginDestination": d}); + assert!(s.execute("export.runPresets", &p).is_err(), "{d}"); + } + assert!(!dir.join("Small").exists()); + assert!(s.previous_export.is_empty(), "a refused run leaves Previous Export alone"); + // null is "none" + let p = json!({"presetIds": ["Small"], "ids": [id], "pluginDestination": null}); + assert!(s.execute("export.runPresets", &p).is_ok()); + } + #[test] fn a_cancelled_run_stops_between_photos() { let dir = lcc_testkit::TempDir::new("lcc-run-presets-cancel"); let mut s = session_with_presets(&dir); let ids: Vec = s.visible_cloned().iter().take(3).map(|p| p.0).collect(); let prepared = prepare(&mut s, &json!({"presetIds": ["Small", "Smaller"], "ids": ids})).unwrap(); - let cancel = std::sync::atomic::AtomicBool::new(false); + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let report = prepared.run(&cancel, &mut |done, _| { if done == 1 { cancel.store(true, std::sync::atomic::Ordering::Relaxed); @@ -344,4 +511,138 @@ mod tests { assert!(report.cancelled); assert_eq!(report.json()["written"], 2); } + + /// A cancel reaches the photo in flight (FX-218): the run leaves at once though that photo's decode is stuck, and + /// writes nothing more. The run used to hand its photos a flag of its own that nothing set, so it waited for the + /// photo in flight to finish, however long that took. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_cancel_interrupts_the_photo_in_flight() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex, mpsc}; + use std::time::Duration; + let dir = lcc_testkit::TempDir::new("lcc-run-presets-inflight"); + let (mut s, ids, _lib) = crate::tests_export::library_of_jpegs("run-presets-inflight", 2); + let out = dir.join("Small"); + s.execute("export.savePreset", &json!({"name": "Small", "params": {"format": "jpeg", "longEdge": 64, "dir": out.to_string_lossy()}})) + .unwrap(); + // the first decode (the run's shared one) fails, which leaves the photo to its own export, whose decode then + // blocks, so the photo is in flight when the cancel comes + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel::<()>(); + let (entered_tx, release_rx) = (Mutex::new(entered_tx), Mutex::new(release_rx)); + let calls = AtomicUsize::new(0); + let inner = s.media.file_loader.clone().expect("a session with file hooks"); + s.media.file_loader = Some(Arc::new(move |path: &str, edge, options| match calls.fetch_add(1, Ordering::SeqCst) { + 0 => Err("the shared decode fails".to_string()), + 1 => { + entered_tx.lock().unwrap().send(()).ok(); + release_rx.lock().unwrap().recv_timeout(Duration::from_secs(30)).ok(); + Err("released".to_string()) + } + _ => inner(path, edge, options), + })); + let raw: Vec = ids.iter().map(|p| p.0).collect(); + let prepared = prepare(&mut s, &json!({"presetIds": ["Small"], "ids": raw})).unwrap(); + let cancel = Arc::new(AtomicBool::new(false)); + let (done_tx, done_rx) = mpsc::channel(); + let c = cancel.clone(); + let worker = std::thread::spawn(move || { + let report = prepared.run(&c, &mut |_, _| {}); + done_tx.send((report.cancelled, report.files.len())).ok(); + }); + entered_rx.recv_timeout(Duration::from_secs(30)).expect("the first photo is in flight"); + cancel.store(true, Ordering::Relaxed); + let result = done_rx.recv_timeout(Duration::from_secs(10)); + // (let the photo in flight go whatever happened, so the run ends) + release_tx.send(()).ok(); + let (cancelled, files) = result.expect("the run leaves within moments of the cancel, the photo in flight still stuck"); + worker.join().unwrap(); + assert!(cancelled); + assert_eq!(files, 0, "the photo in flight wrote nothing"); + assert!(std::fs::read_dir(&out).map(|d| d.count()).unwrap_or(0) == 0, "nothing was written"); + } + + /// A cancel ends the shared decode's wait for memory (FX-220): the run leaves at once though the first photo is + /// still waiting for the export memory, and writes nothing. The decode takes its memory from the same gate as the + /// export, and an uninterruptible wait for it would have made the cancel wait for whoever holds it. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_cancel_ends_the_wait_for_memory_of_the_shared_decode() { + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, mpsc}; + use std::time::Duration; + let dir = lcc_testkit::TempDir::new("lcc-run-presets-gatewait"); + let mut s = session_with_presets(&dir); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + let prepared = prepare(&mut s, &json!({"presetIds": ["Small", "Smaller"], "ids": ids})).unwrap(); + let cancel = Arc::new(AtomicBool::new(false)); + let (started_tx, started_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + // every other photo of the process waits for memory while this test holds the gate: the first photo of the + // run is then waiting for its memory when the cancel comes + let gate = crate::memory::export_gate(); + let held = gate.acquire(gate.usage().1); + let c = cancel.clone(); + let worker = std::thread::spawn(move || { + let report = prepared.run(&c, &mut |done, _| { + if done == 0 { + started_tx.send(()).ok(); + } + }); + done_tx.send((report.cancelled, report.files.len())).ok(); + }); + started_rx.recv_timeout(Duration::from_secs(30)).expect("the run starts"); + std::thread::sleep(Duration::from_millis(200)); + cancel.store(true, Ordering::Relaxed); + let result = done_rx.recv_timeout(Duration::from_secs(10)); + // (give the memory back whatever happened, so the run and the other tests can go on) + drop(held); + let (cancelled, files) = result.expect("the run leaves within moments of the cancel, the first photo still waiting for memory"); + worker.join().unwrap(); + assert!(cancelled); + assert_eq!(files, 0, "nothing was written"); + std::thread::sleep(Duration::from_millis(300)); + for name in ["Small", "Smaller"] { + let written = std::fs::read_dir(dir.join(name)).map(|d| d.count()).unwrap_or(0); + assert_eq!(written, 0, "{name}: nothing was written"); + } + } + + /// A run's presets of a photo whose decoder panics (FX-220): that photo fails for each preset, with the panic as + /// its error, and the run goes on with the others instead of ending ("stopped unexpectedly", nothing marked + /// exported, no plug-in hooks). Every decode, the shared one included, holds the export memory gate. + #[test] + fn a_decoder_panic_is_that_photos_error_and_the_run_goes_on() { + use std::sync::{Arc, Mutex}; + let dir = lcc_testkit::TempDir::new("lcc-run-presets-panic"); + let (mut s, ids, _lib) = crate::tests_export::library_of_jpegs("run-presets-panic", 3); + for (name, edge) in [("Small", 64), ("Smaller", 48)] { + let d = dir.join(name); + s.execute("export.savePreset", &json!({"name": name, "params": {"format": "jpeg", "longEdge": edge, "dir": d.to_string_lossy()}})) + .unwrap(); + } + let held = Arc::new(Mutex::new(Vec::new())); + let h = held.clone(); + crate::tests_export::decoder_panics_on(&mut s, "IMG_2.jpg", move |bytes| h.lock().unwrap().push(bytes)); + let raw: Vec = ids.iter().map(|p| p.0).collect(); + let r = s.execute("export.runPresets", &json!({"presetIds": ["Small", "Smaller"], "ids": raw})).expect("the run ends, not in the panic"); + assert_eq!((r["photos"].as_u64(), r["written"].as_u64(), r["cancelled"].as_bool()), (Some(3), Some(4), Some(false)), "{r}"); + assert_eq!(r["decodes"], 2, "the two photos that decode: {r}"); + for p in r["presets"].as_array().unwrap() { + let files = p["files"].as_array().unwrap(); + let failed: Vec<_> = files.iter().filter(|f| f.get("error").is_some()).collect(); + assert_eq!(failed.len(), 1, "{p}"); + assert_eq!((failed[0]["photo"].as_u64(), failed[0]["file"].as_str()), (Some(ids[1].0), Some("IMG_2.jpg")), "{p}"); + let why = failed[0]["error"].as_str().unwrap_or_default(); + assert!(why.contains("failed unexpectedly") && why.contains("decoder bug"), "{p}"); + assert_eq!(files.len(), 3, "{p}"); + } + // the photos that exported are marked, the one that failed is not + let exported = |i: usize| s.catalog.photo(ids[i]).unwrap().exported.is_some(); + assert_eq!((exported(0), exported(1), exported(2)), (true, false, true)); + // each decode held the export memory + let held = held.lock().unwrap(); + assert!(!held.is_empty() && held.iter().all(|b| *b > 0), "{held:?}"); + } } diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 0e04f05109..d2882afeb3 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -2078,7 +2078,7 @@ mod tests { let dir = std::env::temp_dir().join(format!("lcc-file-orientation-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - let exif = lcc_meta::write_exif(&lcc_meta::Metadata { orientation: Some(lcc_meta::Orientation::Rotate90), ..Default::default() }); + let exif = lcc_meta::write_exif(&lcc_meta::Metadata { orientation: Some(lcc_meta::Orientation::Rotate90), ..Default::default() }).unwrap(); let span = super::ORIENTATION_SPAN as usize; let (o6, o8) = (Some(lcc_meta::Orientation::Rotate90), Some(lcc_meta::Orientation::Rotate270)); // a WebP: VP8X, then `chunks` @@ -2098,7 +2098,7 @@ mod tests { let exif_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif].concat()); // an EXIF chunk over the span (orientation 6 too), one stating no orientation, and an XMP packet stating 8 let huge_exif = (&b"EXIF"[..], [&b"Exif\0\0"[..], &exif, &vec![0; span]].concat()); - let plain = lcc_meta::write_exif(&lcc_meta::Metadata::default()); + let plain = lcc_meta::write_exif(&lcc_meta::Metadata::default()).unwrap(); let plain_chunk = (&b"EXIF"[..], [&b"Exif\0\0"[..], &plain].concat()); let packet = lcc_meta::write_xmp(&lcc_meta::Metadata { orientation: o8, ..Default::default() }, None); let xmp_chunk = (&b"XMP "[..], packet.clone().into_bytes()); diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index 61a0d04c90..c95193d301 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -324,6 +324,11 @@ fn files(dir: &Path) -> Vec { found } +/// The proxy file names ([`file_name`]) in `dir`, in either layout. +pub fn names(dir: &Path) -> std::collections::HashSet { + files(dir).into_iter().filter_map(|f| f.file_name().and_then(|n| n.to_str()).map(str::to_string)).collect() +} + /// The number of smart previews in `dir` and their total size in bytes. pub fn stats(dir: &Path) -> (usize, u64) { files(dir).into_iter().fold((0usize, 0u64), |(count, bytes), path| { diff --git a/crates/engine/src/tests_custom_order.rs b/crates/engine/src/tests_custom_order.rs index 1cd513a5c6..32fa4928cc 100644 --- a/crates/engine/src/tests_custom_order.rs +++ b/crates/engine/src/tests_custom_order.rs @@ -140,9 +140,10 @@ fn duplicated_and_new_albums_start_from_the_shown_order_and_then_own_theirs() { s.execute("edit.undo", &json!({})).unwrap(); s.execute("edit.undo", &json!({})).unwrap(); assert!(s.catalog.album(AlbumId(b)).is_none(), "one undo step each"); - // not for folders, smart albums or unknown ids - let f = s.execute("album.create", &json!({"name": "F", "folder": true})).unwrap()["id"].as_u64().unwrap(); - for id in [f, 999_999] { + // not for the Quick Collection or unknown ids + let quick = s.catalog.alloc_album_id(); + s.commit("Quick", Op::AddAlbum { album: lcc_catalog::Album { quick: true, ..lcc_catalog::Album::new(quick, "Quick Collection") } }).unwrap(); + for id in [quick.0, 999_999] { assert!(s.execute("album.duplicate", &json!({"id": id})).is_err()); } assert!(s.execute("album.duplicate", &json!({})).is_err()); @@ -383,3 +384,124 @@ fn a_folder_order_follows_a_renamed_folder_and_undo_brings_it_back() { assert!(s.catalog.folder_record(&holiday).is_none()); let _ = std::fs::remove_dir_all(&dir); } + +fn id_of(r: Value) -> u64 { + r["id"].as_u64().unwrap() +} + +#[test] +fn a_duplicated_smart_collection_keeps_the_rules_and_is_its_own() { + let mut s = Session::with_demo(); + let set = id_of(s.execute("album.create", &json!({"name": "Sets", "folder": true})).unwrap()); + let rules = json!({"ruleSet": {"match": "any", "rules": [{"field": "rating", "op": "gte", "value": 4}, {"group": {"match": "all", "rules": [{"field": "city", "op": "is", "value": "rome"}]}}]}}); + let a = id_of(s.execute("album.createSmart", &json!({"name": "Good", "parent": set, "rules": rules})).unwrap()); + let b = id_of(s.execute("album.duplicate", &json!({"id": a})).unwrap()); + let (ca, cb) = (s.catalog.album(AlbumId(a)).unwrap().clone(), s.catalog.album(AlbumId(b)).unwrap().clone()); + assert_ne!(a, b); + assert_eq!(cb.name, "Good copy"); + assert_eq!(cb.parent, ca.parent, "the copy sits beside the original"); + assert_eq!(cb.smart, ca.smart, "same rules"); + assert!(cb.photos.is_empty()); + s.execute("album.setRules", &json!({"id": b, "replace": true, "rules": {"ruleSet": {"rules": []}}})).unwrap(); + assert_ne!(s.catalog.album(AlbumId(b)).unwrap().smart, s.catalog.album(AlbumId(a)).unwrap().smart, "editing the copy leaves the original"); + assert_eq!(s.catalog.album(AlbumId(a)).unwrap().smart, ca.smart); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.album(AlbumId(b)).is_none(), "one undo removes the copy"); +} + +#[test] +fn a_duplicated_set_copies_what_is_inside_it_as_one_undo_step() { + let mut s = Session::with_demo(); + let (a, ids) = album(&mut s); + let rev: Vec = ids.iter().rev().copied().collect(); + s.execute("album.setPhotoOrder", &json!({"album": a, "ids": rev})).unwrap(); + let set = id_of(s.execute("album.create", &json!({"name": "Trip", "folder": true})).unwrap()); + let sub = id_of(s.execute("album.create", &json!({"name": "Day 1", "folder": true, "parent": set})).unwrap()); + s.execute("album.move", &json!({"id": a, "parent": sub})).unwrap(); + let smart = id_of(s.execute("album.createSmart", &json!({"name": "Fives", "parent": set, "rules": {"rating": 5}})).unwrap()); + let creation = s.catalog.alloc_album_id(); + let print = lcc_catalog::Album { + parent: Some(AlbumId(set)), + creation: Some(lcc_catalog::Creation { kind: "print".into(), document: "{}".into() }), + ..lcc_catalog::Album::new(creation, "Print") + }; + s.commit("Creation", Op::AddAlbum { album: print }).unwrap(); + let before = s.catalog.albums().count(); + + let r = s.execute("album.duplicate", &json!({"id": set})).unwrap(); + let copy = AlbumId(id_of(r.clone())); + assert_eq!(r["skipped"], 1, "the saved print is not copied, and the result says so"); + assert_eq!(s.catalog.albums().count(), before + 4, "the set, its sub-set, its collection and its smart collection"); + let c = s.catalog.album(copy).unwrap(); + assert_eq!((c.name.as_str(), c.folder, c.parent), ("Trip copy", true, None)); + let kids = s.catalog.album_children(Some(copy)); + assert_eq!(kids.iter().map(|k| k.name.as_str()).collect::>(), ["Day 1", "Fives"], "same nesting; the creation is left out"); + let (day, five) = (kids[0].id, kids[1].id); + let inner = s.catalog.album_children(Some(day)); + assert_eq!(inner.len(), 1); + let inner_id = inner[0].id; + assert_eq!(inner[0].photos, s.catalog.album(AlbumId(a)).unwrap().photos); + assert_eq!(s.catalog.album_photo_order(inner_id).iter().map(|p| p.0).collect::>(), rev, "Custom Order carries over"); + assert_eq!(s.catalog.album(five).unwrap().smart, s.catalog.album(AlbumId(smart)).unwrap().smart); + + // the copy and the original are independent, each way + s.execute("album.rename", &json!({"id": inner_id.0, "name": "Changed"})).unwrap(); + assert_eq!(s.catalog.album(AlbumId(a)).unwrap().name, "Story"); + s.execute("album.rename", &json!({"id": a, "name": "Renamed"})).unwrap(); + s.execute("album.setPhotoOrder", &json!({"album": a, "ids": ids})).unwrap(); + assert_eq!(s.catalog.album(inner_id).unwrap().name, "Changed"); + assert_eq!(s.catalog.album_photo_order(inner_id).iter().map(|p| p.0).collect::>(), rev, "the copy keeps its own order"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.albums().count(), before, "one undo removes the whole copy"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.catalog.albums().count(), before + 4, "redo brings it back"); +} + +#[test] +fn a_set_nested_too_deep_is_refused_and_leaves_nothing_behind() { + let mut s = Session::with_demo(); + let mut parent = None; + let mut top = 0; + for i in 0..40 { + let mut p = json!({"name": format!("L{i}"), "folder": true}); + if let Some(pa) = parent { + p["parent"] = json!(pa); + } + let id = id_of(s.execute("album.create", &p).unwrap()); + top = if i == 0 { id } else { top }; + parent = Some(id); + } + let before = s.catalog.albums().count(); + let err = s.execute("album.duplicate", &json!({"id": top})).unwrap_err().to_string(); + assert!(err.contains("nested more than"), "refused for its depth: {err}"); + assert_eq!(s.catalog.albums().count(), before, "no half-copied set"); + + // a set with too many collections is refused whole as well + let wide = id_of(s.execute("album.create", &json!({"name": "Wide", "folder": true})).unwrap()); + for i in 0..60 { + s.execute("album.create", &json!({"name": format!("C{i}"), "parent": wide})).unwrap(); + } + let before = s.catalog.albums().count(); + let err = s.execute("album.duplicate", &json!({"id": wide})).unwrap_err().to_string(); + assert!(err.contains("collections can't be duplicated at once"), "refused for its size: {err}"); + assert_eq!(s.catalog.albums().count(), before, "no half-copied set"); + let set = id_of(s.execute("album.create", &json!({"name": "Only prints", "folder": true})).unwrap()); + let c = s.catalog.alloc_album_id(); + let set_only_creations = Op::AddAlbum { + album: lcc_catalog::Album { + parent: Some(AlbumId(set)), + creation: Some(lcc_catalog::Creation { kind: "book".into(), document: "{}".into() }), + ..lcc_catalog::Album::new(c, "Book") + }, + }; + s.commit("Creation", set_only_creations).unwrap(); + assert!(s.execute("album.duplicate", &json!({"id": c.0})).is_err(), "a saved creation itself is not duplicated"); + let r = s.execute("album.duplicate", &json!({"id": set})).unwrap(); + assert_eq!(r["skipped"], 1); + assert!(s.catalog.album_children(Some(AlbumId(id_of(r)))).is_empty(), "a set of only creations copies as an empty set"); +} diff --git a/crates/engine/src/tests_edit_in.rs b/crates/engine/src/tests_edit_in.rs index 16f21ae629..6ae917dc1e 100644 --- a/crates/engine/src/tests_edit_in.rs +++ b/crates/engine/src/tests_edit_in.rs @@ -424,6 +424,41 @@ fn an_action_step_that_chooses_a_program_stops_the_action() { let _ = std::fs::remove_dir_all(&dir); } +/// An Edit In copy (TIFF and PNG) carries the photo's metadata under export's own policy: the rights and capture +/// details, and the position only while the photo is not inside a private saved place (FX-241; Edit In has its own +/// options, not the export dialog's, so nothing else checks it against the policy). +#[test] +fn edit_in_copies_follow_the_export_metadata_policy() { + let dir = temp_dir("metadata-policy"); + let src = dir.join("lake.png"); + write_png(&src, 5, 24, 16); + let mut s = session(&dir); + let id = import(&mut s, &src); + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.copyright = "EditCopyright".into(); + meta.creator = "EditCreator".into(); + meta.title = "EditTitle".into(); + meta.gps = Some((48.8566, 2.3522)); + meta.city = "EditCity".into(); + s.catalog.apply(lcc_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + for private in [false, true] { + if private { + s.execute("map.saveLocation", &json!({"name": "Home", "lat": 48.8566, "lon": 2.3522, "radius": 2000, "private": true})).unwrap(); + } + for format in ["tiff", "png"] { + let r = s + .execute("photo.editIn", &json!({"id": id.0, "preset": "External Editor", "format": format, "colorSpace": "srgb", "bitDepth": 8})) + .unwrap(); + let path = r["path"].as_str().unwrap().to_string(); + let back = lcc_meta::extract(&std::fs::read(&path).unwrap()); + let at = format!("{format}, private place {private}: {path}"); + assert_eq!((back.copyright.as_deref(), back.artist.as_deref()), (Some("EditCopyright"), Some("EditCreator")), "{at}"); + assert_eq!(back.title.as_deref(), Some("EditTitle"), "{at}"); + assert_eq!((back.gps.is_some(), back.city.is_some()), (!private, !private), "{at}: the position and place of a private place stay home"); + } + } +} + /// The copy formats beyond TIFF/PSD: a PNG copy embeds the linked XMP, a 32-bit float TIFF holds /// linear samples with Rec. 2020 accepted, an OpenEXR copy carries its link in a sidecar, and a /// DNG copy keeps the raw data (a rendered photo has none and is told so). diff --git a/crates/engine/src/tests_export.rs b/crates/engine/src/tests_export.rs index 5dfea6450c..c6ee72907b 100644 --- a/crates/engine/src/tests_export.rs +++ b/crates/engine/src/tests_export.rs @@ -146,6 +146,76 @@ fn a_preset_depth_is_judged_against_the_format_written() { } } +/// FX-191: a preset's format against the extension of the caller's exact path is refused, not +/// written as a file named one thing with another's bytes (`{preset: "JPEG (Small)", path: +/// "a.png"}` wrote JPEG bytes to `a.png`). A path naming no format, the same format under another +/// spelling, a preset without `format`, and the call's own `format` (theirs to set beside their +/// own `path`, as before) are unchanged. +#[test] +fn a_preset_format_is_refused_against_a_path_naming_another() { + let mut s = Session::with_demo(); + s.export_presets.push(crate::export::ExportPreset { name: "Plain".into(), params: json!({"quality": 70}), ..Default::default() }); + s.export_presets.push(crate::export::ExportPreset { name: "Raw".into(), params: json!({"format": "original"}), ..Default::default() }); + s.export_presets.push(crate::export::ExportPreset { name: "Tiff".into(), params: json!({"format": "tiff"}), ..Default::default() }); + let run = |p: serde_json::Value| s.export_params(&p).and_then(|p| ExportOptions::from_params(&p).map_err(|e| e.to_string())); + for (preset, path) in [("JPEG (Small)", "/x/a.png"), ("JPEG (Small)", "/x/a.tif"), ("JPEG (Small)", "/x/a.JXL"), ("Tiff", "/x/a.jpg")] { + let e = run(json!({"preset": preset, "path": path})).unwrap_err(); + assert!(e.contains(&format!("preset `{preset}`")) && e.contains("`path` ends in"), "{preset} {path}: {e}"); + } + // the refusal names the extension to give + let e = run(json!({"preset": "JPEG (Small)", "path": "/x/a.png"})).unwrap_err(); + assert!(e.contains("ends in `.png`") && e.contains("`.jpg`"), "{e}"); + // the preset's format with a path that agrees, whatever the spelling or case + for (preset, path, format) in [ + ("JPEG (Small)", "/x/a.jpg", ExportFormat::Jpeg), + ("JPEG (Small)", "/x/a.JPEG", ExportFormat::Jpeg), + ("Tiff", "/x/a.tif", ExportFormat::Tiff), + ("Tiff", "/x/a.tiff", ExportFormat::Tiff), + // a path naming no format keeps the preset's; the dots of a folder are not an extension + ("JPEG (Small)", "/x/a", ExportFormat::Jpeg), + ("JPEG (Small)", "/x/a.xyz", ExportFormat::Jpeg), + ("JPEG (Small)", "/x.png/a", ExportFormat::Jpeg), + ("JPEG (Small)", "/x/a.", ExportFormat::Jpeg), + // Original takes the source's own extension, which a path can't know + ("Raw", "/x/a.jpg", ExportFormat::Original), + ] { + assert_eq!(run(json!({"preset": preset, "path": path})).unwrap().format, format, "{preset} {path}"); + } + // a folder export has no path to compare; a null path is "not given" + assert_eq!(run(json!({"preset": "JPEG (Small)", "dir": "/x"})).unwrap().format, ExportFormat::Jpeg); + assert_eq!(run(json!({"preset": "JPEG (Small)", "path": null})).unwrap().format, ExportFormat::Jpeg); + // a preset without `format` follows the path + assert_eq!(run(json!({"preset": "Plain", "path": "/x/a.png"})).unwrap().format, ExportFormat::Png); + // the call's own `format` beside its own `path` is unchanged: the format named wins; `null` is the default + assert_eq!(run(json!({"preset": "JPEG (Small)", "format": "png", "path": "/x/a.jpg"})).unwrap().format, ExportFormat::Png); + assert_eq!(run(json!({"format": "png", "path": "/x/a.jpg"})).unwrap().format, ExportFormat::Png); + assert!(run(json!({"preset": "JPEG (Small)", "format": null, "path": "/x/a.png"})).unwrap_err().contains("`path` ends in")); +} + +/// FX-192: the folder a Choose folder later export was given is not part of what is remembered of +/// it. Saved as a preset or replayed, it keeps the mode and asks again; before, `dir` stayed and the +/// preset (and Export with Previous) wrote into the old folder without asking. Any other mode keeps +/// its folder, a setting as in Lightroom's presets. +#[test] +fn choose_folder_later_keeps_the_mode_not_the_folder() { + let mut s = Session::with_demo(); + s.last_export = Some(json!({"format": "jpeg", "quality": 80, "destinationMode": "chooseLater", "dir": "/out"})); + s.execute("export.savePreset", &json!({"name": "Ask"})).unwrap(); + assert_eq!(s.export_presets[0].params, json!({"format": "jpeg", "quality": 80, "destinationMode": "chooseLater"})); + // the previous export keeps its folder (it prefills the dialog and Settings); only a replay drops it + assert_eq!(s.last_export.as_ref().unwrap()["dir"], "/out"); + for (mode, keeps) in [("specificFolder", true), ("sameAsOriginal", true), ("chooseLater", false)] { + let p = ExportOptions::without_chosen_folder(json!({"destinationMode": mode, "dir": "/out", "quality": 80})); + assert_eq!(p.get("dir").is_some(), keeps, "{mode}: {p}"); + assert_eq!(p["destinationMode"], mode); + assert_eq!(p["quality"], 80, "everything else stays"); + } + // no mode stored: the default, a specific folder, keeps its folder; no `dir` to drop is fine + assert_eq!(ExportOptions::without_chosen_folder(json!({"dir": "/out"}))["dir"], "/out"); + assert_eq!(ExportOptions::without_chosen_folder(json!({"destinationMode": "chooseLater"})), json!({"destinationMode": "chooseLater"})); + assert_eq!(ExportOptions::without_chosen_folder(json!(null)), json!(null)); +} + /// FX-139: a caller that fills every field (a script, an agent) and passes `null` for a key the /// preset sets keeps the preset's value. Before, `null` was copied over the preset and then read /// as "not given", so the default replaced the preset's privacy settings: Remove Location off and @@ -357,6 +427,37 @@ fn library_with_jpeg(tag: &str) -> (Session, lcc_catalog::PhotoId, lcc_testkit:: (s, id, dir, src, bytes) } +/// A library of `n` small JPEG files named `IMG_1.jpg` … `IMG_.jpg`, imported in that order: the session (which +/// decodes through its file loader) and the photos' ids in file order. +pub(crate) fn library_of_jpegs(tag: &str, n: usize) -> (Session, Vec, lcc_testkit::TempDir) { + let dir = temp_dir(tag); + let paths: Vec = (1..=n) + .map(|i| { + // (each file differs: the import skips a file it already has) + let img = lcc_raster::Rgba8::from_fn(48, 32, |x, y| [(x * 5) as u8, (y * 7) as u8, (40 * i) as u8, 255]); + let bytes = crate::export::encode_image(&img, &ExportOptions::default()).unwrap(); + let path = dir.join(format!("IMG_{i}.jpg")); + std::fs::write(&path, &bytes).unwrap(); + path.to_string_lossy().into_owned() + }) + .collect(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": paths})).unwrap(); + let ids = (1..=n).map(|i| s.catalog.photos().find(|p| p.file_name == format!("IMG_{i}.jpg")).map(|p| p.id).expect("imported")).collect(); + (s, ids, dir) +} + +/// From now on the session's decoder panics on the file named `file` (a decoder bug), and `seen(held)` is called with the +/// bytes the export memory gate holds each time any file is decoded. +pub(crate) fn decoder_panics_on(s: &mut Session, file: &'static str, seen: impl Fn(usize) + Send + Sync + 'static) { + let inner = s.media.file_loader.clone().expect("a session with file hooks"); + s.media.file_loader = Some(std::sync::Arc::new(move |path: &str, edge, options| { + seen(crate::memory::export_gate().usage().0); + assert!(!path.ends_with(file), "decoder bug"); + inner(path, edge, options) + })); +} + /// An Original export of a large file stops within the file when the export is cancelled, rather /// than reading all of it first (a movie may be gigabytes). #[test] @@ -553,6 +654,47 @@ fn an_export_batch_reports_written_then_skipped_with_its_photo() { assert!(matches!(FileOutcome::of(&again[0]), FileOutcome::Skipped { photo: Some(p), .. } if p == id), "{again:?}"); } +/// A title too long for a file system gives a file with a cut name and a warning saying so, not a bare +/// "File name too long" from the write (FX-224). +#[test] +fn a_title_too_long_for_a_file_name_is_cut_and_reported() { + use crate::export::Destination; + let (mut s, id, dir, _src, _original) = library_with_jpeg("export-long-title"); + s.execute("photo.setMeta", &json!({"ids": [id.0], "title": "é".repeat(4000)})).unwrap(); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let to = Destination { dir: out.to_string_lossy().into(), exact: None, ..Default::default() }; + let o = ExportOptions { naming: "{title}".into(), ..Default::default() }; + let done = disk_batch(&mut s, id, &o, &to).unwrap(); + assert!(done[0].get("error").is_none(), "{done:?}"); + let written = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect::>(); + assert_eq!(written.len(), 1, "{written:?}"); + assert!(written[0].len() <= crate::rename::MAX_NAME_BYTES && written[0].ends_with(".jpg"), "{} bytes", written[0].len()); + let warnings = done[0]["warnings"].to_string(); + assert!(warnings.contains("file name") && warnings.contains("cut"), "the cut is reported: {done:?}"); + // an ordinary name carries no such warning + let plain = disk_batch(&mut s, id, &ExportOptions { naming: "{name}".into(), ..Default::default() }, &to).unwrap(); + assert!(plain[0].get("warnings").is_none(), "{plain:?}"); + let _ = std::fs::remove_dir_all(dir); +} + +/// A WebP export larger than the format takes is refused before the render, naming the limit and the size, and leaves +/// the rest of the batch alone (FX-226). +#[test] +fn a_webp_larger_than_the_format_takes_is_refused_before_it_renders() { + let (mut s, id, _dir, _src, _original) = library_with_jpeg("export-webp-limit"); + for lossless in [true, false] { + let o = ExportOptions { + format: ExportFormat::Webp, + webp_lossless: lossless, + resize: Some(crate::export::Resize { dont_enlarge: false, ..crate::export::Resize::long_edge(16_385) }), + ..Default::default() + }; + let why = crate::export::prepare_export(&mut s, id, &o, 1).err().unwrap_or_default(); + assert!(why.contains("IMG_1.jpg") && why.contains("at most") && why.contains("16385 × "), "lossless {lossless}: {why:?}"); + } +} + /// Upstream #1405: explicit paths honour the same conflict policy as folder exports, sidecars included, and an /// original or a folder named as the path is refused under every policy. #[test] @@ -1044,6 +1186,26 @@ fn hdr_exports_are_pq_or_hlg_rec2020_and_sdr_edits_stay_plain() { assert!(hdr > 1.2 && hdr <= 4.0 + 1e-3, "HDR float TIFF max {hdr}"); } +/// HDR JPEG XL with Lossless on says its samples are PQ (Rec. 2100), as the lossy file does (FX-195). It used to embed +/// the linear Rec. 2020 profile made for the float TIFF in place of that, so the file declared its PQ code values +/// linear light. It still carries its metadata. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn lossless_hdr_jpeg_xl_says_pq() { + let mut s = Session::with_demo(); + let id = sunset(&mut s); + s.execute("develop.hdr", &json!({"enabled": true, "maxEv": 2})).unwrap(); + for lossless in [false, true] { + let o = ExportOptions::from_json(&json!({"longEdge": 96, "format": "jxl", "hdr": true, "quality": 90, "jxlLossless": lossless})); + assert_eq!(o.jxl_lossless, lossless); + let e = export_photo(&mut s, id, &o, 1).unwrap(); + let img = jxl_oxide::JxlImage::builder().read(std::io::Cursor::new(&e.bytes)).unwrap(); + let c = format!("{:?}", img.image_header().metadata.colour_encoding); + assert!(c.contains("Bt2100") && c.contains("Pq") && !c.contains("IccProfile"), "lossless {lossless}: {c}"); + assert_eq!(lcc_meta::extract(&e.bytes).title.as_deref(), Some("Golden horizon"), "lossless {lossless}: the title in the XMP box"); + } +} + /// An exported AVIF's metadata reads back (issue #693: HEIF-family files had no metadata reader). /// avif-serialize writes the EXIF as an `Exif` item in two extents, its offset field and the TIFF. #[test] @@ -1096,7 +1258,7 @@ fn remove_location_holds_for_original_and_dng_exports() { // a JPEG with GPS in its EXIF let jpg = dir.join("Geo.jpg"); let img = lcc_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 8) as u8, (y * 10) as u8, 90, 255]); - let exif = lcc_meta::write_exif(&gps); + let exif = lcc_meta::write_exif(&gps).unwrap(); let meta = lcc_codecs::EncodeMeta { exif: Some(&exif), ..Default::default() }; std::fs::write(&jpg, lcc_codecs::encode_jpeg(&lcc_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap()).unwrap(); let mut s = Session::new().with_fs(); @@ -1391,7 +1553,7 @@ fn metadata_none_in_any_case_exports_no_metadata() { /// the `meta` box's `idat`. fn heic_with_gps_in_its_thumbnail() -> Vec { let gps = lcc_meta::Gps { latitude: 48.85, longitude: 2.35, altitude: None }; - let exif = [&[0u8, 0, 0, 0][..], &lcc_meta::write_exif(&lcc_meta::Metadata { gps: Some(gps), ..Default::default() })].concat(); + let exif = [&[0u8, 0, 0, 0][..], &lcc_meta::write_exif(&lcc_meta::Metadata { gps: Some(gps), ..Default::default() }).unwrap()].concat(); heic_with_metadata_in_its_thumbnail(b"Exif", &exif) } @@ -1447,7 +1609,7 @@ fn remove_location_refuses_a_heic_whose_gps_cannot_be_ruled_out() { } // Ordinary files without GPS still export, with and without an EXIF item. - for exif in [None, Some(lcc_meta::write_exif(&lcc_meta::Metadata { model: Some("Synthetic".into()), ..Default::default() }))] { + for exif in [None, Some(lcc_meta::write_exif(&lcc_meta::Metadata { model: Some("Synthetic".into()), ..Default::default() }).unwrap())] { let mut spec = lcc_heif::testdata::Spec::new(32, 32, &|_, _| [0, 0, 0]); spec.exif = exif; let bytes = lcc_heif::testdata::build(&spec); @@ -1969,6 +2131,57 @@ fn overwrite_never_clobbers_a_file_of_the_same_batch() { let _ = std::fs::remove_dir_all(&dir); } +/// FX-190: under Skip, a name already written by this same batch was skipped as if an earlier run had left it, so +/// the second of two photos that render to one name was never exported. It now takes a number, as under Overwrite; +/// a file from before the export is still skipped, at the numbered name too, so running the export again skips both. +#[test] +fn skip_numbers_a_name_the_same_batch_wrote() { + use crate::export::{Conflict, Destination, FileOutcome}; + let (mut s, _, dir, _src, _) = library_with_jpeg("export-skip-collide"); + let other = dir.join("b").join("IMG_1.jpg"); + std::fs::create_dir_all(other.parent().unwrap()).unwrap(); + let img = lcc_raster::Rgba8::from_fn(48, 32, |x, _| [200, (x * 3) as u8, 10, 255]); + std::fs::write(&other, crate::export::encode_image(&img, &ExportOptions::default()).unwrap()).unwrap(); + s.execute("library.import", &json!({"paths": [other.to_string_lossy()]})).unwrap(); + let ids: Vec<_> = s.catalog.photos().map(|p| p.id).collect(); + assert_eq!(ids.len(), 2); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let to = Destination { dir: out.to_string_lossy().to_string(), exact: None, ..Default::default() }; + let o = ExportOptions { naming: "{name}".into(), conflict: Conflict::Skip, ..Default::default() }; + let run = |s: &mut Session| { + let files = crate::export::export_batch(s, &ids, &o, &to, &mut crate::export::write_file, &|p| std::path::Path::new(p).exists()).unwrap(); + files + .iter() + .map(|f| match FileOutcome::of(f) { + FileOutcome::Written { path, .. } => format!("written {}", path.rsplit(['/', '\\']).next().unwrap_or(path)), + FileOutcome::Skipped { path, .. } => format!("skipped {}", path.rsplit(['/', '\\']).next().unwrap_or(path)), + _ => format!("{f}"), + }) + .collect::>() + }; + // both photos exported: the second at the next number + assert_eq!(run(&mut s), ["written IMG_1.jpg", "written IMG_1-2.jpg"]); + // again: the plain name is from before this export, so the first photo is skipped there; this export then + // wrote nothing under that name, so the second is skipped there too (Skip never numbers past a file from before) + let first = std::fs::read(out.join("IMG_1.jpg")).unwrap(); + let second = std::fs::read(out.join("IMG_1-2.jpg")).unwrap(); + assert_eq!(run(&mut s), ["skipped IMG_1.jpg", "skipped IMG_1.jpg"]); + assert_eq!((std::fs::read(out.join("IMG_1.jpg")).unwrap(), std::fs::read(out.join("IMG_1-2.jpg")).unwrap()), (first.clone(), second)); + // only the numbered file is left from before: the first photo is written, the second still skipped there + std::fs::remove_file(out.join("IMG_1.jpg")).unwrap(); + std::fs::write(out.join("IMG_1-2.jpg"), b"an earlier run").unwrap(); + assert_eq!(run(&mut s), ["written IMG_1.jpg", "skipped IMG_1-2.jpg"]); + assert_eq!(std::fs::read(out.join("IMG_1-2.jpg")).unwrap(), b"an earlier run", "a file from before is never replaced"); + assert_eq!(std::fs::read(out.join("IMG_1.jpg")).unwrap(), first); + // nothing from before: both written again, as the first time + std::fs::remove_file(out.join("IMG_1.jpg")).unwrap(); + std::fs::remove_file(out.join("IMG_1-2.jpg")).unwrap(); + assert_eq!(run(&mut s), ["written IMG_1.jpg", "written IMG_1-2.jpg"]); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 2); + let _ = std::fs::remove_dir_all(&dir); +} + /// A library with one 300 × 200 PNG: transparent, with an opaque red 150 × 100 rectangle in the middle. fn library_with_transparent_png(tag: &str) -> (Session, lcc_catalog::PhotoId, lcc_testkit::TempDir) { let dir = temp_dir(tag); @@ -2360,7 +2573,7 @@ fn jpeg_with_iim_city(city: &str) -> Vec { /// (`Metadata::gps` is `None`), yet anyone can read them out of the file. fn jpeg_with_refless_exif_gps() -> Vec { let m = lcc_meta::Metadata { gps: Some(lcc_meta::Gps { latitude: 45.0, longitude: 7.0, altitude: None }), ..Default::default() }; - let mut exif = lcc_meta::write_exif(&m); + let mut exif = lcc_meta::write_exif(&m).unwrap(); let le = exif.starts_with(b"II"); let u16b = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() }; // the GPSLatitudeRef (1) and GPSLongitudeRef (3) entries, ASCII (2), become unknown tags @@ -2488,3 +2701,40 @@ fn preset_export_rejects_malformed_ids_without_replacing_the_output() { assert_eq!(s.execute("preset.export", &json!({"path": path_text, "ids": ["lc.warm-glow"], "group": "Nope"})).unwrap()["count"], 1); let _ = std::fs::remove_dir_all(dir); } + +/// FX-215: a caption too long for a JPEG's one XMP segment no longer fails the photo's export. The JPEG is written +/// without the caption, the result's warnings name it and its size, the rest of the metadata is kept, and the formats +/// that hold the whole text still carry it. Before, the export failed with an error naming no field. +#[test] +fn a_caption_too_long_for_a_jpeg_is_left_out_with_a_warning_naming_it() { + let dir = temp_dir("export-long-caption"); + let src = dir.join("IMG_1.jpg"); + std::fs::write(&src, jpeg_with_xmp(&lcc_meta::Metadata::default())).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.caption = "word ".repeat(14_000); + meta.copyright = "(c) The Photographer".into(); + meta.keywords = vec!["tern".into(), "harbour".into()]; + s.catalog.apply(lcc_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + + let e = export_photo(&mut s, id, &ExportOptions::default(), 1).expect("a JPEG export of a long caption"); + let back = lcc_meta::extract(&e.bytes); + assert_eq!(back.caption, None, "the caption did not fit one XMP segment"); + assert_eq!(back.copyright.as_deref(), Some("(c) The Photographer")); + assert_eq!(back.keywords, ["tern", "harbour"], "what fits stays"); + let w = e.warnings.iter().find(|w| w.contains("caption")).unwrap_or_else(|| panic!("no warning names the caption: {:?}", e.warnings)); + assert!(w.contains("(69 KB)") && w.contains("a JPEG holds 64 KB at most") && w.contains(&e.file_name), "{w}"); + + // formats without the one-segment limit keep the whole caption, and say nothing + let o = ExportOptions { format: ExportFormat::Png, ..Default::default() }; + let e = export_photo(&mut s, id, &o, 1).unwrap(); + // (the trailing space of the last word is trimmed on the way in) + assert!(lcc_meta::extract(&e.bytes).caption.is_some_and(|c| c.len() >= 69_990), "the whole caption"); + assert!(e.warnings.is_empty(), "{:?}", e.warnings); + + // under Metadata: None there is nothing to leave out + let o = ExportOptions { metadata: crate::export::MetadataPolicy::None, ..Default::default() }; + assert!(export_photo(&mut s, id, &o, 1).unwrap().warnings.is_empty()); +} diff --git a/crates/engine/src/tests_export_batch.rs b/crates/engine/src/tests_export_batch.rs index cccedef1ac..c38de6a910 100644 --- a/crates/engine/src/tests_export_batch.rs +++ b/crates/engine/src/tests_export_batch.rs @@ -107,6 +107,30 @@ fn several_presets_never_replace_another_file_of_the_run() { assert_eq!((files_in(&two).len(), r["written"].as_u64()), (3, Some(2)), "{:?} {r}", files_in(&two)); } +/// FX-190: under Skip, Export with Several Presets skipped the second of two presets sharing a folder and a naming +/// (and the second of two photos one preset names alike) as if an earlier run had written the name. They now take a +/// number, as under Overwrite; a second run skips them all, its files being from before it. +#[test] +fn several_presets_under_skip_number_a_name_the_run_wrote() { + let dir = lcc_testkit::TempDir::new("lcc-run-presets-skip"); + let mut s = Session::with_demo(); + let two = dir.join("two"); + for (name, edge) in [("A", 32), ("B", 24)] { + save_preset(&mut s, name, json!({"format": "jpeg", "longEdge": edge, "naming": "{name}", "conflict": "skip", "dir": two.to_string_lossy()})); + } + save_preset( + &mut s, + "Fixed", + json!({"format": "jpeg", "longEdge": 32, "naming": "fixed", "conflict": "skip", "dir": dir.join("one").to_string_lossy()}), + ); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + let r = s.execute("export.runPresets", &json!({"presetIds": ["A", "B", "Fixed"], "ids": ids})).unwrap(); + assert_eq!((files_in(&two).len(), files_in(&dir.join("one")).len(), r["written"].as_u64()), (4, 2, Some(6)), "{r}"); + // run again: everything is from before, nothing written or replaced + let r = s.execute("export.runPresets", &json!({"presetIds": ["A", "B", "Fixed"], "ids": ids})).unwrap(); + assert_eq!((files_in(&two).len(), files_in(&dir.join("one")).len(), r["written"].as_u64()), (4, 2, Some(0)), "{r}"); +} + /// `fallbackDir` (what the desktop sends once it asked for a folder) is the folder of the presets that name none; a /// preset with its own folder keeps it. `dir` replaces every preset's folder, as documented. #[test] @@ -133,3 +157,54 @@ fn several_presets_keep_their_own_folders_beside_one_that_names_none() { assert!(s.execute("export.runPresets", &json!({"presetIds": ["None"], "ids": ids, "fallbackDir": bad})).is_err(), "{bad}"); } } + +/// FX-217: `export.runPresets` and `export.contactSheet` run a whole export on the calling thread, so a window's own +/// export (a worker holding a row of kind `export`) could run beside them and race it for the same folders. They are +/// refused while an `export` row is in flight, as the window's `app.runPresets` is, and nothing is written; other +/// kinds of task don't count (a face scan, a preview build), and the row's end lifts the refusal. +#[test] +fn the_export_commands_are_refused_while_another_export_runs() { + use crate::activity::Cancel; + let dir = lcc_testkit::TempDir::new("lcc-export-busy"); + let mut s = Session::with_demo(); + let out = dir.join("out"); + save_preset(&mut s, "Small", json!({"format": "jpeg", "longEdge": 32, "dir": out.to_string_lossy()})); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + let sheet = dir.join("sheet.pdf"); + let presets = json!({"presetIds": ["Small"], "ids": ids}); + let contact = json!({"path": sheet.to_string_lossy(), "ids": ids, "columns": 3, "rows": 3}); + // below: another kind of task is no export + let other = s.activity.start("faces", "Finding faces", Cancel::No); + for (cmd, p) in [("export.runPresets", &presets), ("export.contactSheet", &contact)] { + assert!(s.execute(cmd, p).is_ok(), "{cmd} runs beside a task of another kind"); + } + drop(other); + for f in [&out, &sheet] { + let _ = std::fs::remove_dir_all(f); + let _ = std::fs::remove_file(f); + } + // at: an export row, one already being stopped included (it holds its files until it ends); and a batch row of + // kind `export` (the window's own) + let rows = [s.activity.start("export", "Exporting", Cancel::Yes), s.activity.start_batch("export", "Exporting", Cancel::Yes)]; + for row in &rows { + for stopping in [false, true] { + if stopping { + s.activity.cancel(row.id()).unwrap(); + } + for (cmd, p) in [("export.runPresets", &presets), ("export.contactSheet", &contact)] { + let e = s.execute(cmd, p).expect_err(cmd).to_string(); + assert!(e.contains("already running"), "{cmd}: {e}"); + } + } + } + assert!(!out.exists() && !sheet.exists(), "nothing written while another export runs"); + assert_eq!(s.previous_export.iter().map(|p| p.0).collect::>(), ids, "a refused run leaves Previous Export alone"); + // above: once the exports end, both run + drop(rows); + for (cmd, p) in [("export.runPresets", &presets), ("export.contactSheet", &contact)] { + assert!(s.execute(cmd, p).is_ok(), "{cmd} runs once the other export has ended"); + } + assert_eq!(files_in(&out).len(), 2); + assert!(sheet.exists()); + assert!(s.activity.list().is_empty(), "their rows end with them"); +} diff --git a/crates/engine/src/tests_export_group.rs b/crates/engine/src/tests_export_group.rs new file mode 100644 index 0000000000..7c85acb20d --- /dev/null +++ b/crates/engine/src/tests_export_group.rs @@ -0,0 +1,208 @@ +//! FX-214 and FX-216: a photo's file and its sidecars are written as a group also under Overwrite (and for a sink with no +//! folder of its own), and `Exported::save` writes an export to a path as the Placer does: the same guard, the same names. + +use serde_json::json; + +use crate::Session; +use crate::export::{Conflict, Destination, ExportFormat, ExportOptions, export_batch_outcome, export_photo, write_file}; +use crate::tests_xmp::temp_dir; + +fn jpeg(level: u8) -> Vec { + let pixels = [level; 12]; + let image = lcc_codecs::EncodeImage::new(2, 2, 3, lcc_codecs::Samples::U8(&pixels)); + lcc_codecs::encode_jpeg(&image, 90, lcc_codecs::ChromaSubsampling::S444, &Default::default()).unwrap() +} + +/// `dir/src/IMG_7.jpg` imported, with an edit (so an Original export has a sidecar). +fn library(tag: &str) -> (Session, lcc_catalog::PhotoId, lcc_testkit::TempDir, std::path::PathBuf) { + let dir = temp_dir(tag); + let src = dir.join("src").join("IMG_7.jpg"); + std::fs::create_dir_all(src.parent().unwrap()).unwrap(); + std::fs::write(&src, jpeg(96)).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + s.execute("develop.set", &json!({"ids": [id.0], "control": "light.exposure", "value": 1.0})).unwrap(); + (s, id, dir, src) +} + +fn names(dir: &std::path::Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v +} + +/// The first photo's entry of an Overwrite Original export into `out`, the sink failing the file named `.fail` (the +/// extension; `None`: no failure). +fn overwrite(s: &mut Session, id: lcc_catalog::PhotoId, out: &std::path::Path, fail: Option<&str>) -> (crate::export::BatchOutcome, usize) { + let o = ExportOptions { format: ExportFormat::Original, naming: "{name}".into(), conflict: Conflict::Overwrite, ..Default::default() }; + let to = Destination::on_disk(out.to_string_lossy().into(), None); + let mut writes = 0; + let mut sink = |p: &str, b: &[u8]| { + writes += 1; + if fail.is_some_and(|x| std::path::Path::new(p).extension().is_some_and(|e| e == x)) { + return Err(format!("{p}: disk full")); + } + write_file(p, b) + }; + let outcome = export_batch_outcome(s, &[id], &o, &to, &mut sink, &|p| std::path::Path::new(p).exists()).unwrap(); + (outcome, writes) +} + +/// FX-214: an Original export under Overwrite into a folder with nothing of it: when its sidecar can't be written the +/// copy is removed again (an Original copy without its edits is not what was asked for), and the error names the sidecar +/// and says so. Before, the copy stayed, unreported. +#[test] +fn overwrite_removes_a_new_copy_whose_sidecar_failed() { + let (mut s, id, dir, _) = library("group-fresh"); + let out = dir.join("out"); + let (outcome, writes) = overwrite(&mut s, id, &out, Some("xmp")); + assert_eq!(writes, 2, "the file, then the sidecar that failed"); + let error = outcome.files[0]["error"].as_str().unwrap(); + assert!(error.contains("IMG_7.xmp: disk full"), "names the sidecar: {error}"); + assert!(error.contains("IMG_7.jpg removed again"), "says what became of the copy: {error}"); + assert!(outcome.files[0].get("kept").is_none(), "{:?}", outcome.files); + assert!(!outcome.wrote_any()); + assert!(names(&out).is_empty(), "nothing left: {:?}", names(&out)); +} + +/// FX-214: under Overwrite over a file and sidecar of an earlier run, a sidecar that can't be written leaves the new file +/// (the old one can't be put back): the photo is an error naming the sidecar and the file that stays, the file is listed +/// as `kept`, and a later photo of the batch never takes its name. The earlier sidecar is as it was. +#[test] +fn overwrite_reports_the_file_that_stays_when_its_sidecar_failed() { + let (mut s, id, dir, _) = library("group-replaced"); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + std::fs::write(out.join("IMG_7.jpg"), b"last week's copy").unwrap(); + std::fs::write(out.join("IMG_7.xmp"), b"last week's edits").unwrap(); + let (outcome, _) = overwrite(&mut s, id, &out, Some("xmp")); + let entry = &outcome.files[0]; + let error = entry["error"].as_str().unwrap(); + assert!(error.contains("IMG_7.xmp: disk full"), "{error}"); + assert!(error.contains("written and kept"), "{error}"); + let kept = entry["kept"].as_array().unwrap(); + assert_eq!(kept.len(), 1, "{entry}"); + assert!(kept[0].as_str().unwrap().ends_with("IMG_7.jpg"), "{entry}"); + assert!(!outcome.wrote_any(), "a photo with a missing sidecar is not an exported photo"); + assert_ne!(std::fs::read(out.join("IMG_7.jpg")).unwrap(), b"last week's copy", "the new copy replaced it"); + assert_eq!(std::fs::read(out.join("IMG_7.xmp")).unwrap(), b"last week's edits", "the sidecar is as it was"); + assert_eq!(names(&out), ["IMG_7.jpg", "IMG_7.xmp"], "no temp file left"); +} + +/// FX-214: a main file that can't be written leaves the earlier files as they were, and nothing is `kept`. +#[test] +fn overwrite_whose_file_failed_changes_nothing() { + let (mut s, id, dir, _) = library("group-main-fails"); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + std::fs::write(out.join("IMG_7.jpg"), b"last week's copy").unwrap(); + std::fs::write(out.join("IMG_7.xmp"), b"last week's edits").unwrap(); + let (outcome, writes) = overwrite(&mut s, id, &out, Some("jpg")); + assert_eq!(writes, 1, "the sidecar is not written after a file that failed"); + assert!(outcome.files[0]["error"].as_str().unwrap().contains("IMG_7.jpg: disk full"), "{:?}", outcome.files); + assert!(outcome.files[0].get("kept").is_none()); + assert_eq!(std::fs::read(out.join("IMG_7.jpg")).unwrap(), b"last week's copy"); + assert_eq!(std::fs::read(out.join("IMG_7.xmp")).unwrap(), b"last week's edits"); +} + +/// FX-214: the same for a destination with no folder of its own (`write_new: None`): files are never removed there (the +/// sink's names mean nothing on this disk), and the file that stays is reported. +#[test] +fn a_sink_without_a_folder_reports_the_file_that_stays() { + let (mut s, id, dir, _) = library("group-sink"); + let out = dir.join("out"); + let o = ExportOptions { format: ExportFormat::Original, naming: "{name}".into(), conflict: Conflict::Overwrite, ..Default::default() }; + let to = Destination { dir: out.to_string_lossy().into(), exact: None, ..Default::default() }; + let mut sink = |p: &str, b: &[u8]| if p.ends_with(".xmp") { Err(format!("{p}: disk full")) } else { write_file(p, b) }; + let outcome = export_batch_outcome(&mut s, &[id], &o, &to, &mut sink, &|p| std::path::Path::new(p).exists()).unwrap(); + assert!(outcome.files[0]["error"].as_str().unwrap().contains("IMG_7.xmp: disk full"), "{:?}", outcome.files); + assert_eq!(outcome.files[0]["kept"].as_array().map(Vec::len), Some(1), "{:?}", outcome.files); + assert_eq!(names(&out), ["IMG_7.jpg"]); +} + +/// FX-216: `Exported::save` names the sidecar as the Placer does (the stem rule: everything before the last dot), writes +/// the file and the sidecar, and replaces what it finds. +#[test] +fn save_writes_the_file_and_its_sidecar_as_the_placer_names_them() { + let (mut s, id, dir, _) = library("save-names"); + let e = export_photo(&mut s, id, &ExportOptions { format: ExportFormat::Original, ..Default::default() }, 1).unwrap(); + assert_eq!(e.sidecars.len(), 1); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let target = out.join("album.v1.final.jpg"); + std::fs::write(out.join("album.v1.final.xmp"), b"earlier").unwrap(); + let sidecars = e.save(&target.to_string_lossy(), &s.original_guard()).unwrap(); + assert_eq!(sidecars, [out.join("album.v1.final.xmp").to_string_lossy()]); + assert_eq!(names(&out), ["album.v1.final.jpg", "album.v1.final.xmp"]); + assert_eq!(std::fs::read(&target).unwrap(), e.bytes); + assert_eq!(std::fs::read(out.join("album.v1.final.xmp")).unwrap(), e.sidecars[0].1, "replaced"); +} + +/// FX-216: `Exported::save` never writes over a catalogued original or its sidecar, and writes nothing when one of its +/// files would: `IMG_7.tif` is free, but its sidecar `IMG_7.xmp` is the original's (once it exists), so nothing is +/// written, not even the `.tif`. Before, `save` had no guard (each caller kept its own). +#[test] +fn save_refuses_an_original_and_its_sidecar_and_writes_nothing() { + let (mut s, id, dir, src) = library("save-guard"); + let e = export_photo(&mut s, id, &ExportOptions { format: ExportFormat::Original, ..Default::default() }, 1).unwrap(); + let sidecar = src.with_extension("xmp"); + std::fs::write(&sidecar, b"the original's sidecar").unwrap(); + let before = std::fs::read(&src).unwrap(); + let guard = s.original_guard(); + // the original itself, its sidecar named as a file, and a new file whose sidecar is the original's + for target in [src.clone(), sidecar.clone(), src.with_extension("tif")] { + let err = e.save(&target.to_string_lossy(), &guard).unwrap_err(); + assert!(err.contains("original"), "{target:?}: {err}"); + } + assert_eq!(std::fs::read(&src).unwrap(), before); + assert_eq!(std::fs::read(&sidecar).unwrap(), b"the original's sidecar"); + assert!(!src.with_extension("tif").exists(), "nothing written for a group one of whose files is refused"); + drop(dir); +} + +/// FX-216 / FX-214: `Exported::save` is all or none for what it creates too: a sidecar that can't be written (its name is +/// a folder) leaves no copy of the file. +#[test] +fn save_whose_sidecar_fails_leaves_no_new_file() { + let (mut s, id, dir, _) = library("save-sidecar-fails"); + let e = export_photo(&mut s, id, &ExportOptions { format: ExportFormat::Original, ..Default::default() }, 1).unwrap(); + let out = dir.join("out"); + std::fs::create_dir_all(out.join("copy.xmp")).unwrap(); + let err = e.save(&out.join("copy.jpg").to_string_lossy(), &s.original_guard()).unwrap_err(); + assert!(err.contains("copy.xmp"), "names the sidecar: {err}"); + assert_eq!(names(&out), ["copy.xmp"], "no copy without its sidecar"); +} + +/// FX-214: a file that stays although its photo failed is taken: the next photo of the batch, with the same file name, +/// takes the next free name instead of replacing it (as it does for a file the batch wrote). +#[test] +fn the_next_photo_does_not_replace_a_file_that_stays() { + let (mut s, first, dir, _) = library("group-taken"); + let src2 = dir.join("src2").join("IMG_7.jpg"); + std::fs::create_dir_all(src2.parent().unwrap()).unwrap(); + std::fs::write(&src2, jpeg(200)).unwrap(); + s.execute("library.import", &json!({"paths": [src2.to_string_lossy()]})).unwrap(); + let second = s.catalog.photos().map(|p| p.id).find(|i| *i != first).expect("a second photo (not a duplicate)"); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + std::fs::write(out.join("IMG_7.jpg"), b"last week's copy").unwrap(); + std::fs::write(out.join("IMG_7.xmp"), b"last week's edits").unwrap(); + let o = ExportOptions { format: ExportFormat::Original, naming: "{name}".into(), conflict: Conflict::Overwrite, ..Default::default() }; + let to = Destination::on_disk(out.to_string_lossy().into(), None); + let items = crate::export::prepare_batch(&mut s, &[first, second], &o).unwrap(); + let mut failed = false; + let mut sink = |p: &str, b: &[u8]| { + if p.ends_with(".xmp") && !std::mem::replace(&mut failed, true) { + return Err(format!("{p}: disk full")); + } + write_file(p, b) + }; + let outcome = crate::export::run_batch_outcome(items, &o, &to, &mut sink, &|p| std::path::Path::new(p).exists(), false, &mut |_, _| true); + assert_eq!(outcome.files.len(), 2, "{:?}", outcome.files); + assert!(outcome.files[0]["error"].is_string() && outcome.files[0]["kept"].is_array(), "{:?}", outcome.files); + let second_path = outcome.files[1]["path"].as_str().unwrap(); + assert!(second_path.ends_with("IMG_7-2.jpg"), "{:?}", outcome.files); + assert_eq!(names(&out), ["IMG_7-2.jpg", "IMG_7-2.xmp", "IMG_7.jpg", "IMG_7.xmp"]); + assert_ne!(std::fs::read(out.join("IMG_7.jpg")).unwrap(), b"last week's copy", "the first photo's new file is still there"); +} diff --git a/crates/engine/src/tests_exported_contents.rs b/crates/engine/src/tests_exported_contents.rs index b31727206e..cb8e2dc5fc 100644 --- a/crates/engine/src/tests_exported_contents.rs +++ b/crates/engine/src/tests_exported_contents.rs @@ -1,6 +1,6 @@ //! What a rendered export's file carries: the capture time the photo states (never the import's file-date guess), the -//! watermark the user chose (or no file at all), and every metadata field its format can hold (AVIF says what it -//! can't). +//! watermark the user chose (or no file at all), and every metadata field its format can hold (AVIF and OpenEXR say +//! what they can't). use std::path::Path; @@ -80,7 +80,8 @@ fn an_unreadable_watermark_graphic_refuses_the_export() { } /// Per rendered format, what the file carries of a photo's metadata under "All": every format that can hold XMP has the -/// title and keywords; AVIF (the app writes Exif only) has the Exif part and says per file what it left out. +/// title and keywords; AVIF (the app writes Exif only) has the Exif part and says per file what it left out; a TIFF +/// has the Exif part in its own IFDs as well as the XMP (FX-188); OpenEXR holds none and says so. #[test] fn every_format_carries_the_metadata_or_says_what_it_left_out() { let mut s = Session::with_demo(); @@ -90,13 +91,28 @@ fn every_format_carries_the_metadata_or_says_what_it_left_out() { meta.keywords = vec!["contentskw".into()]; meta.copyright = "ContentsCopyright".into(); s.catalog.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); - let mut formats = vec![ExportFormat::Jpeg, ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp]; + let mut formats = vec![ExportFormat::Jpeg, ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp, ExportFormat::Psd, ExportFormat::Exr]; if cfg!(not(target_arch = "wasm32")) { formats.extend([ExportFormat::Jxl, ExportFormat::Avif]); } for format in formats { let o = ExportOptions { format, metadata: MetadataPolicy::All, resize: Some(crate::export::Resize::long_edge(64)), ..Default::default() }; let e = export_photo(&mut s, id, &o, 1).unwrap(); + if format == ExportFormat::Exr { + let w = e.warnings.join("\n"); + assert!( + ["OpenEXR", "copyright", "title", "keywords"].iter().all(|word| w.contains(word)), + "{format:?}: no word of what was left out: {w:?}" + ); + continue; + } + if format == ExportFormat::Tiff { + // the Exif part in the TIFF's own IFDs (not only in its XMP), which readers that look at Exif only see + let tiff = lcc_tiff::Tiff::parse(&e.bytes).unwrap(); + let ifd0 = &tiff.ifds[0]; + assert_eq!(ifd0.string(lcc_tiff::tags::COPYRIGHT).as_deref(), Some("ContentsCopyright"), "{format:?}: the Exif copyright"); + assert!(ifd0.exif.is_some(), "{format:?}: an Exif IFD"); + } let back = lcc_meta::extract(&e.bytes); assert_eq!(back.copyright.as_deref(), Some("ContentsCopyright"), "{format:?}: the copyright"); if format == ExportFormat::Avif { @@ -118,4 +134,75 @@ fn every_format_carries_the_metadata_or_says_what_it_left_out() { let e = export_photo(&mut s, id, &o, 1).unwrap(); assert!(e.warnings.is_empty(), "{:?}", e.warnings); } + // an OpenEXR with no metadata asked for says nothing + let o = ExportOptions { + format: ExportFormat::Exr, + metadata: MetadataPolicy::None, + resize: Some(crate::export::Resize::long_edge(64)), + ..Default::default() + }; + let e = export_photo(&mut s, id, &o, 1).unwrap(); + assert!(e.warnings.is_empty(), "{:?}", e.warnings); +} + +/// The metadata policy holds in every writer, read back from the file (FX-241): per format, per choice, with and without +/// Remove Location, the file carries exactly what the choice includes. None carries nothing; Copyright the notice and +/// creator only; Copyright & Contact adds the contact (which Copyright does not: the choices' one difference); All adds +/// the description, keywords, place and camera; No camera everything but the camera; Remove Location takes the position +/// and place names out of every choice that has them. A format without XMP (AVIF) holds the Exif part only. +#[test] +fn the_metadata_policy_holds_in_every_format() { + let mut s = Session::with_demo(); + let id = s.visible_cloned()[0]; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.title = "PolicyTitle".into(); + meta.caption = "PolicyCaption".into(); + meta.keywords = vec!["policykw".into()]; + meta.copyright = "PolicyCopyright".into(); + meta.creator = "PolicyCreator".into(); + meta.contact.email = "policy@example.com".into(); + meta.camera_make = "PolicyMaker".into(); + meta.camera_model = "PolicyModel".into(); + meta.iso = Some(400); + meta.gps = Some((48.8566, 2.3522)); + meta.city = "PolicyCity".into(); + s.catalog.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let mut formats = vec![ExportFormat::Jpeg, ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp, ExportFormat::Psd]; + if cfg!(not(target_arch = "wasm32")) { + formats.extend([ExportFormat::Jxl, ExportFormat::Avif]); + } + let policies = + [MetadataPolicy::None, MetadataPolicy::Copyright, MetadataPolicy::CopyrightContact, MetadataPolicy::All, MetadataPolicy::AllExceptCamera]; + for format in formats { + let xmp = format != ExportFormat::Avif; + for policy in policies { + for remove_location in [false, true] { + let at = format!("{format:?}, {policy:?}, remove location {remove_location}"); + let o = ExportOptions { + format, + metadata: policy, + remove_location, + resize: Some(crate::export::Resize::long_edge(64)), + ..Default::default() + }; + let b = lcc_meta::extract(&export_photo(&mut s, id, &o, 1).unwrap().bytes); + let rights = policy != MetadataPolicy::None; + let contact = matches!(policy, MetadataPolicy::CopyrightContact | MetadataPolicy::All | MetadataPolicy::AllExceptCamera); + let described = matches!(policy, MetadataPolicy::All | MetadataPolicy::AllExceptCamera); + let camera = policy == MetadataPolicy::All; + let place = described && !remove_location; + let got = |name: &str, present: bool, want: bool| assert_eq!(present, want, "{at}: {name}"); + got("copyright", b.copyright.as_deref() == Some("PolicyCopyright"), rights); + got("creator", b.artist.as_deref() == Some("PolicyCreator"), rights); + got("contact", b.contact.email == "policy@example.com", contact && xmp); + got("caption", b.caption.as_deref() == Some("PolicyCaption"), described); + got("title", b.title.as_deref() == Some("PolicyTitle"), described && xmp); + got("keywords", b.keywords == ["policykw"], described && xmp); + got("camera make and model", (b.make.as_deref(), b.model.as_deref()) == (Some("PolicyMaker"), Some("PolicyModel")), camera); + got("camera settings", b.iso == Some(400), camera); + got("position", b.gps.is_some(), place); + got("city", b.city.as_deref() == Some("PolicyCity"), place && xmp); + } + } + } } diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 4bc6ca9a79..77f73848b7 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -1435,6 +1435,37 @@ fn smart_previews_stand_in_for_offline_originals() { let _ = std::fs::remove_dir_all(&lib); } +/// Has Smart Preview follows the smart previews folder: a photo matches once its proxy is built and stops matching +/// when the proxies are discarded; a library opened again lists its folder (on a worker thread) and matches again. +#[test] +fn has_smart_preview_rule_follows_the_smart_previews_folder() { + let src = temp_dir("smartrulesrc"); + let lib = temp_dir("smartrulelib"); + write_png(&src.join("a.png"), 7); + write_png(&src.join("b.png"), 9); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let a = import_png(&mut s, &src.join("a.png")); + let b = import_png(&mut s, &src.join("b.png")); + let rule: lcc_catalog::rules::RuleSet = serde_json::from_value(json!({"rules": [{"field": "smartPreview", "op": "is", "value": true}]})).unwrap(); + let matching = |s: &Session| [a, b].map(|id| rule.matches(s.catalog.photo(id).unwrap(), &s.catalog)); + assert_eq!(matching(&s), [false, false], "none built yet"); + s.execute("library.smartPreviews", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(matching(&s), [true, false], "only the photo that has a proxy"); + // opened again: the folder is listed off the UI thread and applied by the next tick + s.open_library(&lib, false).unwrap(); + let t = std::time::Instant::now(); + while !matching(&s)[0] && t.elapsed() < std::time::Duration::from_secs(30) { + s.finishing_tick(); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(matching(&s), [true, false], "listed again at open"); + s.execute("library.smartPreviews", &json!({"ids": [a.0], "discard": true})).unwrap(); + assert_eq!(matching(&s), [false, false], "discarded"); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&lib); +} + /// The long edge the grid asks thumbnails for in the tests of missing photos below. const CELL: usize = 256; diff --git a/crates/engine/src/tests_libops.rs b/crates/engine/src/tests_libops.rs index ab132e00b9..8d2df61658 100644 --- a/crates/engine/src/tests_libops.rs +++ b/crates/engine/src/tests_libops.rs @@ -172,7 +172,7 @@ fn capture_time_reverts_to_the_files_exif() { let (w, h) = (24usize, 16usize); let img = lcc_raster::Rgba8 { width: w, height: h, data: vec![[9, 9, 9, 255]; w * h] }; let meta = lcc_meta::Metadata { capture_time: lcc_meta::DateTime::parse_iso("2024-01-16T12:34:56.250+02:00"), ..Default::default() }; - let exif = lcc_meta::write_exif(&meta); + let exif = lcc_meta::write_exif(&meta).unwrap(); let bytes = lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(&img), &lcc_codecs::EncodeMeta { exif: Some(&exif), ..Default::default() }).unwrap(); std::fs::write(src.join("dated.png"), bytes).unwrap(); diff --git a/crates/engine/src/tests_plugin_installs.rs b/crates/engine/src/tests_plugin_installs.rs index 557d29f28d..45eae4a8ca 100644 --- a/crates/engine/src/tests_plugin_installs.rs +++ b/crates/engine/src/tests_plugin_installs.rs @@ -729,7 +729,7 @@ fn the_update_commands_check_ask_and_install() { s.execute("plugin.setUpdateCheck", &json!({"id": id, "on": true})).unwrap(); let check_lines = || { let g = crate::cmd::plugins::manager(); - g.as_ref().unwrap().get(id).unwrap().log.iter().filter(|l| l.starts_with("update check:")).count() + g.as_ref().unwrap().get(id).unwrap().log.iter().filter(|l| l.text.starts_with("update check:")).count() }; let before = check_lines(); let checked = s.execute("plugin.checkUpdates", &json!({"due": true})).unwrap(); diff --git a/crates/engine/src/tests_preset_interop.rs b/crates/engine/src/tests_preset_interop.rs index a7e4f5fb9b..c3df6b920d 100644 --- a/crates/engine/src/tests_preset_interop.rs +++ b/crates/engine/src/tests_preset_interop.rs @@ -561,6 +561,293 @@ fn an_export_preset_import_adds_at_most_the_cap() { assert!(r["failed"].to_string().contains("many.zip"), "{}", r["failed"]); } +/// An `.lcexport` file of the given preset entries. +fn export_preset_file(presets: Vec) -> Vec { + json!({"format": "photo.exportPresets", "version": 1, "presets": presets}).to_string().into_bytes() +} + +/// The `failed` rows of a report as `file: reason` lines. +fn failed_lines(r: &Value) -> Vec { + r["failed"].as_array().unwrap().iter().map(|f| format!("{}: {}", f[0].as_str().unwrap_or("?"), f[1].as_str().unwrap_or("?"))).collect() +} + +/// FX-221: a preset the import leaves out is named in `failed` with its reason, in a file and in a +/// zip entry; a file whose presets were all refused is not "nothing imported, nothing failed". +#[test] +fn skipped_export_presets_are_reported_with_their_reasons() { + let dir = temp_dir("export-preset-skipped"); + let good = json!({"name": "Good", "params": {"format": "jpeg", "quality": 80}}); + let blank = json!({"name": " ", "params": {"format": "jpeg"}}); + let no_params = json!({"name": "Flat", "params": [1, 2]}); + let refused = json!({"name": "Refused", "params": {"quality": "high"}}); + // all rejected + let all_bad = dir.join("all-bad.lcexport"); + std::fs::write(&all_bad, export_preset_file(vec![blank.clone(), no_params.clone(), refused.clone()])).unwrap(); + let mut s = Session::new(); + let r = s.execute("export.importPresets", &json!({"paths": [all_bad.to_string_lossy()]})).unwrap(); + assert!(r["imported"].as_array().unwrap().is_empty() && s.export_presets.is_empty(), "{r}"); + let lines = failed_lines(&r); + assert_eq!(lines.len(), 3, "{lines:?}"); + assert!(lines[0].contains("no name"), "{lines:?}"); + assert!(lines[1].contains("`Flat`") && lines[1].contains("params"), "{lines:?}"); + assert!(lines[2].contains("`Refused`") && lines[2].contains("refuse") && lines[2].contains("quality"), "{lines:?}"); + assert!(lines.iter().all(|l| l.contains("all-bad.lcexport")), "{lines:?}"); + // the general import reports them too + let mut s = Session::new(); + let r = s.execute("preset.import", &json!({"paths": [all_bad.to_string_lossy()]})).unwrap(); + assert_eq!((r["failed"].as_array().unwrap().len(), r["exportPresets"].as_array().unwrap().len()), (3, 0), "{r}"); + // one good among them: it imports, the others are named + let mixed = dir.join("mixed.lcexport"); + std::fs::write(&mixed, export_preset_file(vec![blank.clone(), good.clone(), refused.clone()])).unwrap(); + let mut s = Session::new(); + let r = s.execute("export.importPresets", &json!({"paths": [mixed.to_string_lossy()]})).unwrap(); + assert_eq!((s.export_presets.len(), failed_lines(&r).len()), (1, 2), "{r}"); + // a file that lists no presets at all says so + let empty = dir.join("empty.lcexport"); + std::fs::write(&empty, export_preset_file(vec![])).unwrap(); + let r = Session::new().execute("export.importPresets", &json!({"paths": [empty.to_string_lossy()]})).unwrap(); + assert!(failed_lines(&r).iter().any(|l| l.contains("no export presets")), "{r}"); + // an empty file is not an export preset file (unchanged) + let nothing = dir.join("nothing.lcexport"); + std::fs::write(¬hing, b"").unwrap(); + let r = Session::new().execute("export.importPresets", &json!({"paths": [nothing.to_string_lossy()]})).unwrap(); + assert_eq!(failed_lines(&r).len(), 1, "{r}"); + + // zip: a good entry, an entry that fails, a zip inside a zip, an entry with every preset refused, + // and a file that is not a preset (not reported: bundles hold other things) + let broken = b"s = { type = \"export\" }".to_vec(); + let all_refused = export_preset_file(vec![blank, refused]); + let nested = crate::preset_import::tests::zip(&[("in.lcexport", &export_preset_file(vec![good.clone()]))], false); + let entries: &[(&str, &[u8])] = &[ + ("good.lcexport", &export_preset_file(vec![good.clone()])), + ("broken.lrtemplate", &broken), + ("inner.zip", &nested), + ("refused.lcexport", &all_refused), + ("README.txt", b"hello"), + ]; + let z = dir.join("bundle.zip"); + std::fs::write(&z, crate::preset_import::tests::zip(entries, true)).unwrap(); + let mut s = Session::new(); + let r = s.execute("export.importPresets", &json!({"paths": [z.to_string_lossy()]})).unwrap(); + assert_eq!(s.export_presets.len(), 1, "{r}"); + let lines = failed_lines(&r).join("\n"); + for want in ["bundle.zip/broken.lrtemplate", "bundle.zip/inner.zip", "bundle.zip/refused.lcexport"] { + assert!(lines.contains(want), "missing {want}: {lines}"); + } + assert!(!lines.contains("README"), "{lines}"); + // a zip where nothing imports still reports why, instead of "not an export preset" + let z2 = dir.join("allfail.zip"); + std::fs::write(&z2, crate::preset_import::tests::zip(&[("refused.lcexport", &all_refused), ("broken.lrtemplate", &broken)], true)).unwrap(); + let mut s = Session::new(); + let r = s.execute("export.importPresets", &json!({"paths": [z2.to_string_lossy()]})).unwrap(); + let lines = failed_lines(&r); + assert!(s.export_presets.is_empty() && lines.len() == 3, "{lines:?}"); + assert!(!lines.iter().any(|l| l.contains("not an export preset")), "{lines:?}"); + // a zip with no export presets in it stays "not an export preset" + let z3 = dir.join("other.zip"); + std::fs::write(&z3, crate::preset_import::tests::zip(&[("README.txt", b"hello")], true)).unwrap(); + let r = Session::new().execute("export.importPresets", &json!({"paths": [z3.to_string_lossy()]})).unwrap(); + assert_eq!(failed_lines(&r).len(), 1, "{r}"); + assert!(failed_lines(&r)[0].contains("not an export preset"), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// FX-221: the skipped presets a file lists are listed up to `MAX_SKIPPED_LISTED`; the rest are +/// counted in one line, never dropped. +#[test] +fn skipped_export_presets_are_listed_up_to_a_limit() { + let max = export_preset_files::MAX_SKIPPED_LISTED; + let dir = temp_dir("export-preset-skipped-cap"); + for (n, more) in [(max - 1, 0), (max, 0), (max + 1, 1), (max + 5, 5)] { + let f = dir.join(format!("n{n}.lcexport")); + std::fs::write(&f, export_preset_file((0..n).map(|i| json!({"name": format!("P{i}"), "params": {"quality": "high"}})).collect())).unwrap(); + let r = Session::new().execute("export.importPresets", &json!({"paths": [f.to_string_lossy()]})).unwrap(); + let lines = failed_lines(&r); + assert_eq!(lines.len(), n.min(max) + usize::from(more > 0), "{n}: {}", lines.len()); + match more { + 0 => assert!(!lines.iter().any(|l| l.contains("more export presets")), "{n}"), + m => assert!(lines.last().unwrap().contains(&format!("and {m} more")), "{n}: {:?}", lines.last()), + } + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// FX-221: one file of exactly the cap imports whole; one more is named as left out (before, the +/// extra preset was dropped without a line). +#[test] +fn a_file_at_the_export_preset_cap_reports_only_what_is_past_it() { + let max = export_preset_files::MAX_PRESETS; + let dir = temp_dir("export-preset-file-cap"); + for (n, left_out) in [(max - 1, false), (max, false), (max + 1, true)] { + let f = dir.join(format!("n{n}.lcexport")); + std::fs::write(&f, many_export_presets(n, 0, &|i| format!("P{i}"))).unwrap(); + let mut s = Session::new(); + let r = s.execute("export.importPresets", &json!({"paths": [f.to_string_lossy()]})).unwrap(); + assert_eq!(s.export_presets.len(), n.min(max), "{n}"); + assert_eq!(failed_lines(&r).iter().any(|l| l.contains(&format!("at most {max}"))), left_out, "{n}: {:?}", failed_lines(&r)); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// FX-223: a Lightroom colour space the exporter's own parser takes imports as that space (before, +/// "Adobe RGB (1998) Compatible", "ROMM RGB" and "ITU-R 2020" were reported as unknown and became +/// sRGB); Lightroom's own spellings still map, and a name nobody knows is reported and left out. +#[test] +fn lightroom_colour_space_names_map_through_the_exporters_parser() { + use crate::cmd::export_preset_files::lr_export_params; + use crate::export::OutputSpace; + let space = |name: &str| { + let lua = crate::preset_import::parse_lua(&format!("s = {{ value = {{ format = \"JPEG\", export_colorSpace = \"{name}\" }} }}")) + .unwrap() + .get("value") + .unwrap() + .clone(); + let (p, unmapped) = lr_export_params(&lua); + ( + p.get("colorSpace").and_then(Value::as_str).map(str::to_string), + unmapped.into_iter().filter(|u| u.starts_with("colour space")).collect::>(), + ) + }; + for (name, want) in [ + ("sRGB", "srgb"), + ("sRGB IEC61966-2.1", "srgb"), + ("AdobeRGB", "adobeRgb"), + ("Adobe RGB (1998)", "adobeRgb"), + ("Adobe RGB (1998) Compatible", "adobeRgb"), + ("Wide Gamut RGB", "adobeRgb"), + ("ProPhotoRGB", "proPhoto"), + ("ROMM RGB", "proPhoto"), + ("Display P3", "displayP3"), + ("P3 D65", "displayP3"), + ("Rec. 2020", "rec2020"), + ("HDR Rec2020", "rec2020"), + ("ITU-R 2020", "rec2020"), + ("BT.2020", "rec2020"), + ] { + assert_eq!(space(name), (Some(want.to_string()), vec![]), "{name}"); + // what the exporter accepts as a name, the importer takes the same way + if let Some(parsed) = OutputSpace::parse(name) { + let label = match parsed { + OutputSpace::Srgb => "srgb", + OutputSpace::DisplayP3 => "displayP3", + OutputSpace::AdobeRgb => "adobeRgb", + OutputSpace::ProPhoto => "proPhoto", + OutputSpace::Rec2020 => "rec2020", + }; + assert_eq!(label, want, "{name}"); + } + } + // not known: reported by its own spelling, and no colour space is set + let (set, unmapped) = space("Mystery RGB"); + assert_eq!(set, None); + assert!(unmapped.len() == 1 && unmapped[0].contains("Mystery RGB"), "{unmapped:?}"); + let (set, unmapped) = space(""); + assert_eq!((set, unmapped.len()), (None, 1)); +} + +/// FX-222: every setting of a Lightroom export preset that has no counterpart is named in the +/// report, the two person-name privacy settings with what they mean; settings that are mapped, or +/// that belong to a format or a switch this preset doesn't use, are not (before, anything the +/// importer didn't look up was dropped without a row). +#[test] +fn lightroom_export_settings_without_a_counterpart_are_named() { + use crate::cmd::export_preset_files::lr_export_params; + let lua = |body: &str| crate::preset_import::parse_lua(&format!("s = {{ value = {{ {body} }} }}")).unwrap().get("value").unwrap().clone(); + let rows = |body: &str| -> Vec { + lr_export_params(&lua(body)) + .1 + .into_iter() + .filter(|u| u.starts_with("setting `") || u.contains("more settings") || u.contains("unnamed")) + .collect() + }; + let has = |rows: &[String], key: &str| rows.iter().any(|r| r.starts_with(&format!("setting `{key}`"))); + + // the settings a real preset carries for formats and switches it doesn't use are not about it + let jpeg = rows( + r#"format = "JPEG", jpeg_quality = 0.8, tiff_compressionMethod = "compressionMethod_LZW", tiff_preserveTransparency = false, + dng_lossyCompression = true, dng_preview = "medium", png_foo = 1, jxl_effort = 7, avif_quality = 0.5, + renamingTokensOn = false, tokens = "{{image_name}}", tokenCustomString = "x", tokensArchivedToString2 = "x", initialSequenceNumber = 3, + export_useSubfolder = false, export_destinationPathSuffix = "x", jpeg_useLimitSize = false, jpeg_limitSize = 100, + size_doConstrain = false, size_maxWidth = 5, size_units = "inch", size_resizeType = "wh", size_megapixels = 5, size_percentage = 50, + outputSharpeningOn = false, outputSharpeningLevel = 2, outputSharpeningMedia = "screen", useWatermark = false, watermarking_id = "abc""#, + ); + assert!(jpeg.is_empty(), "{jpeg:?}"); + // …but a key of the chosen format that nothing reads is named + let dng = rows(r#"format = "DNG", dng_compressed = true, dng_preview = "medium", tiff_foo = 1"#); + assert_eq!(dng.len(), 1, "{dng:?}"); + assert!(has(&dng, "dng_preview"), "{dng:?}"); + let tokens = rows( + r#"format = "JPEG", renamingTokensOn = true, tokens = "{{image_name}}", tokenCustomString = "x", tokensArchivedToString2 = "x", initialSequenceNumber = 3"#, + ); + assert!(tokens.is_empty(), "{tokens:?}"); + + // the keys the review named; the person-name ones say what to do + let named = rows( + r#"format = "JPEG", includeFaceTagsAsKeywords = false, includeFaceTagsInIptc = true, keywordOptions = "all", LR_keywordsExport = true, + dng_conversionMethod = "preserveRaw", video_format = "H264", videoCodec = "h264", LR_watermarking_id = "x", gone = nil"#, + ); + for key in [ + "includeFaceTagsAsKeywords", + "includeFaceTagsInIptc", + "keywordOptions", + "LR_keywordsExport", + "video_format", + "videoCodec", + "LR_watermarking_id", + ] { + assert!(has(&named, key), "{key} in {named:?}"); + } + assert_eq!(named.len(), 7, "{named:?}"); + assert!(!has(&named, "dng_conversionMethod") && !has(&named, "gone"), "{named:?}"); + for key in ["includeFaceTagsAsKeywords", "includeFaceTagsInIptc"] { + let row = named.iter().find(|r| r.contains(key)).unwrap(); + assert!(row.contains("person names") && row.contains("Remove Person Info"), "{row}"); + } + assert!(named.iter().any(|r| r.contains("includeFaceTagsAsKeywords` = false")), "{named:?}"); + + // a key spelled two ways is one row; the spelling is the file's; list entries without a name + let twice = rows(r#"format = "JPEG", mystery = 1, LR_mystery = 2, export_Mystery = 3, "first", "second""#); + assert_eq!(twice.len(), 2, "{twice:?}"); + assert!(has(&twice, "mystery") && twice.iter().any(|r| r.starts_with("2 unnamed entries")), "{twice:?}"); + // a very long key is cut at a character boundary + let long = rows(&format!("format = \"JPEG\", [\"{}\"] = 1", "é".repeat(200))); + assert_eq!(long.len(), 1, "{long:?}"); + assert!(long[0].chars().count() < 120, "{}", long[0]); + // the keys the fixture presets carry are all accounted for, mapped or inert + let dir = temp_dir("export-lr-keys"); + let r = Session::new() + .execute("export.importPresets", &json!({"paths": [write(&dir.join("Client JPEG.lrtemplate"), &lr_export("/tmp/x"))]})) + .unwrap(); + let unmapped = r["imported"][0]["unmapped"].to_string(); + assert!(!unmapped.contains("setting `"), "{unmapped}"); + // …and a preset with an unmapped key says so in the import report and the stored preset + let text = lr_export("/tmp/x").replace("LR_useWatermark = true,", "LR_useWatermark = true,\n\t\tLR_includeFaceTagsAsKeywords = false,"); + let mut s = Session::new(); + let r = s.execute("export.importPresets", &json!({"paths": [write(&dir.join("Faces.lrtemplate"), &text)]})).unwrap(); + assert!(r["imported"][0]["unmapped"].to_string().contains("includeFaceTagsAsKeywords"), "{r}"); + assert!(s.export_presets[0].unmapped.iter().any(|u| u.contains("includeFaceTagsAsKeywords")), "{:?}", s.export_presets[0].unmapped); + let _ = std::fs::remove_dir_all(&dir); +} + +/// FX-222: one preset names at most `MAX_UNREAD_LISTED` settings; the rest are counted in one line. +#[test] +fn unmapped_lightroom_settings_are_listed_up_to_a_limit() { + use crate::cmd::export_preset_files::{MAX_UNREAD_LISTED, lr_export_params}; + let max = MAX_UNREAD_LISTED; + for n in [0, 1, max - 1, max, max + 1, max + 7] { + let keys: String = (0..n).map(|i| format!(", zz_unknown_{i} = {i}")).collect(); + let v = crate::preset_import::parse_lua(&format!("s = {{ value = {{ format = \"JPEG\"{keys} }} }}")).unwrap().get("value").unwrap().clone(); + let (_, unmapped) = lr_export_params(&v); + let listed = unmapped.iter().filter(|u| u.starts_with("setting `")).count(); + let more: Vec<&String> = unmapped.iter().filter(|u| u.contains("more settings")).collect(); + assert_eq!(listed, n.min(max), "{n}"); + match n.checked_sub(max).filter(|m| *m > 0) { + None => assert!(more.is_empty(), "{n}: {more:?}"), + Some(m) => assert!(more.len() == 1 && more[0].starts_with(&format!("and {m} more")), "{n}: {more:?}"), + } + } +} + /// `FreeNames::claim` gives each name `free_name` gives, one claim after another (case ignored). #[test] fn free_names_give_what_free_name_gives() { @@ -622,3 +909,25 @@ fn unreadable_privacy_options_fail_closed() { let o = read(json!({"removeLocation": false, "removePersonInfo": null})); assert!(!o.remove_location && !o.remove_person_info); } + +/// A Lightroom export preset's start number is carried over from 0 to the top of the accepted range (FX-238); one past +/// it is dropped and the Export dialog's default stays. +#[test] +fn a_lightroom_start_number_is_taken_across_the_accepted_range() { + let dir = temp_dir("export-lr-start-number"); + let template = |n: usize, name: &str, start: u32| { + let text = format!( + "s = {{\n\tid = \"3A1B0C55-0000-0000-0000-00000000020{n}\",\n\tinternalName = \"{name}\",\n\ttitle = \"{name}\",\n\ttype = \"Export\",\n\tvalue = {{\n\t\texportServiceProvider = \"com.adobe.ag.export.file\",\n\t\tformat = \"JPEG\",\n\t\tinitialSequenceNumber = {start},\n\t\trenamingTokensOn = true,\n\t\ttokens = \"{{{{naming_sequenceNumber_3Digits}}}}\",\n\t}},\n\tversion = 0,\n}}\n" + ); + write(&dir.join(format!("{name}.lrtemplate")), &text) + }; + let top = crate::export::START_NUMBER_RANGE.1; + let paths = [template(0, "Zero", 0), template(1, "Top", top), template(2, "Past", top + 1)]; + let mut s = Session::new(); + s.execute("preset.import", &json!({"paths": paths})).unwrap(); + let start = |name: &str| ExportOptions::from_params(&s.export_params(&json!({"preset": name})).unwrap()).unwrap().start_number; + assert_eq!(start("Zero"), 0, "0 is accepted"); + assert_eq!(start("Top"), top); + assert_eq!(start("Past"), 1, "past the range: the default start"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests_raw_decoder.rs b/crates/engine/src/tests_raw_decoder.rs index bb5a55e97e..17dcbcac63 100644 --- a/crates/engine/src/tests_raw_decoder.rs +++ b/crates/engine/src/tests_raw_decoder.rs @@ -47,6 +47,7 @@ fn frame() -> Frame { black: lcc_raw::BlackLevel::uniform(512.0), white: 16383.0, active_area: lcc_raw::Rect::new(2, 0, 32, 24), + crop: None, wb_multipliers: Some([2.0, 1.0, 1.5]), xyz_to_camera: Some(lcc_raw::Mat3([[0.7, -0.1, -0.05], [-0.4, 1.2, 0.2], [-0.1, 0.2, 0.6]])), } @@ -69,6 +70,8 @@ fn ids_read_as_people_type_them() { assert_eq!(Decoder::parse("lcc-raw"), Some(Decoder::Lcc)); assert_eq!(Decoder::parse("lccraw"), Some(Decoder::Lcc)); assert_eq!(Decoder::parse(" Auto "), Some(Decoder::Auto)); + assert_eq!(Decoder::parse("dnglab"), Some(Decoder::Dnglab)); + assert_eq!(Decoder::parse("Rawler"), Some(Decoder::Dnglab)); assert_eq!(Decoder::parse("dcraw"), None); for d in Decoder::ALL { assert_eq!(Decoder::parse(d.id()), Some(d)); @@ -80,7 +83,7 @@ fn auto_and_lcc_read_with_lcc_raw_and_never_ask_libraw() { let bytes = dng(); let fake = Fake::new(Ok(frame())); for choice in [Decoder::Auto, Decoder::Lcc] { - let (raw, used) = decode_as(&bytes, choice, Some(&fake)).unwrap(); + let (raw, used) = decode_as(&bytes, choice, Some(&fake), None).unwrap(); assert_eq!(used, Used::Lcc); assert_eq!(raw, lcc_raw::decode(&bytes).unwrap(), "{choice:?} reads exactly what lcc-raw reads"); } @@ -91,7 +94,7 @@ fn auto_and_lcc_read_with_lcc_raw_and_never_ask_libraw() { fn libraw_reads_when_chosen_and_lcc_raw_takes_over_when_it_fails_or_is_missing() { let bytes = dng(); let fake = Fake::new(Ok(frame())); - let (raw, used) = decode_as(&bytes, Decoder::Libraw, Some(&fake)).unwrap(); + let (raw, used) = decode_as(&bytes, Decoder::Libraw, Some(&fake), None).unwrap(); assert_eq!((used, fake.calls()), (Used::Libraw, 1)); assert_eq!((raw.width, raw.height, raw.active_area), (34, 24, lcc_raw::Rect::new(2, 0, 32, 24))); assert_eq!(raw.wb_multipliers, Some([2.0, 1.0, 1.5])); @@ -99,8 +102,8 @@ fn libraw_reads_when_chosen_and_lcc_raw_takes_over_when_it_fails_or_is_missing() assert_eq!(raw.metadata, lcc_raw::probe_info(&bytes).unwrap().metadata); // a failing LibRaw, and none at all (web, Android), leave the photo to lcc-raw let failing = Fake::new(Err("unsupported file format".into())); - assert_eq!(decode_as(&bytes, Decoder::Libraw, Some(&failing)).unwrap().1, Used::Lcc); - assert_eq!(decode_as(&bytes, Decoder::Libraw, None).unwrap().1, Used::Lcc); + assert_eq!(decode_as(&bytes, Decoder::Libraw, Some(&failing), None).unwrap().1, Used::Lcc); + assert_eq!(decode_as(&bytes, Decoder::Libraw, None, None).unwrap().1, Used::Lcc); } #[test] @@ -108,17 +111,69 @@ fn auto_hands_libraw_only_the_variants_lcc_raw_refuses() { let bytes = unsupported(); assert!(matches!(lcc_raw::decode(&bytes), Err(lcc_raw::RawError::Unsupported(_))), "the fixture is an unsupported variant"); let fake = Fake::new(Ok(frame())); - assert_eq!(decode_as(&bytes, Decoder::Auto, Some(&fake)).unwrap().1, Used::Libraw); + assert_eq!(decode_as(&bytes, Decoder::Auto, Some(&fake), None).unwrap().1, Used::Libraw); // without LibRaw (or when it can't either) the refusal stands, so the embedded preview is shown as before - assert!(matches!(decode_as(&bytes, Decoder::Auto, None), Err(lcc_raw::RawError::Unsupported(_)))); + assert!(matches!(decode_as(&bytes, Decoder::Auto, None, None), Err(lcc_raw::RawError::Unsupported(_)))); let failing = Fake::new(Err("no".into())); - assert!(matches!(decode_as(&bytes, Decoder::Auto, Some(&failing)), Err(lcc_raw::RawError::Unsupported(_)))); + assert!(matches!(decode_as(&bytes, Decoder::Auto, Some(&failing), None), Err(lcc_raw::RawError::Unsupported(_)))); // lcc-raw only: never LibRaw let before = fake.calls(); - assert!(decode_as(&bytes, Decoder::Lcc, Some(&fake)).is_err()); + assert!(decode_as(&bytes, Decoder::Lcc, Some(&fake), None).is_err()); assert_eq!(fake.calls(), before); } +#[test] +fn dnglab_reads_when_chosen_and_lcc_raw_takes_over_when_it_fails_or_is_missing() { + let bytes = dng(); + let libraw = Fake::new(Ok(frame())); + let dnglab = Fake::new(Ok(frame())); + let (raw, used) = decode_as(&bytes, Decoder::Dnglab, Some(&libraw), Some(&dnglab)).unwrap(); + assert_eq!((used, libraw.calls(), dnglab.calls()), (Used::Dnglab, 0, 1), "dnglab, never LibRaw"); + assert_eq!((raw.width, raw.height), (34, 24)); + let failing = Fake::new(Err("no".into())); + assert_eq!(decode_as(&bytes, Decoder::Dnglab, Some(&libraw), Some(&failing)).unwrap().1, Used::Lcc); + assert_eq!(decode_as(&bytes, Decoder::Dnglab, Some(&libraw), None).unwrap().1, Used::Lcc); + assert_eq!(libraw.calls(), 0); + // Auto and lcc-raw never ask dnglab for a file lcc-raw reads + for choice in [Decoder::Auto, Decoder::Lcc] { + assert_eq!(decode_as(&bytes, choice, None, Some(&dnglab)).unwrap().1, Used::Lcc); + } + assert_eq!(dnglab.calls(), 1); +} + +#[test] +fn auto_tries_libraw_then_dnglab_for_the_variants_lcc_raw_refuses() { + let bytes = unsupported(); + let (libraw, dnglab, failing) = (Fake::new(Ok(frame())), Fake::new(Ok(frame())), Fake::new(Err("no".into()))); + assert_eq!(decode_as(&bytes, Decoder::Auto, Some(&libraw), Some(&dnglab)).unwrap().1, Used::Libraw); + assert_eq!(dnglab.calls(), 0, "LibRaw read it, dnglab was not asked"); + assert_eq!(decode_as(&bytes, Decoder::Auto, Some(&failing), Some(&dnglab)).unwrap().1, Used::Dnglab); + assert_eq!(decode_as(&bytes, Decoder::Auto, None, Some(&dnglab)).unwrap().1, Used::Dnglab, "the web/Android case without LibRaw"); + assert!(matches!(decode_as(&bytes, Decoder::Auto, Some(&failing), Some(&failing)), Err(lcc_raw::RawError::Unsupported(_)))); + let before = dnglab.calls(); + assert!(decode_as(&bytes, Decoder::Lcc, Some(&libraw), Some(&dnglab)).is_err()); + assert_eq!(dnglab.calls(), before); +} + +/// The real dnglab decoder reads the app's synthetic DNG to the same mosaic as lcc-raw, and refuses hostile bytes with +/// an error (lcc-raw then reads what it can). +#[cfg(feature = "dnglab")] +#[test] +fn the_built_in_dnglab_reads_a_dng_like_lcc_raw() { + let bytes = dng(); + let ours = lcc_raw::decode(&bytes).unwrap(); + let backend = Dnglab; + let (raw, used) = decode_as(&bytes, Decoder::Dnglab, None, Some(&backend)).unwrap(); + assert_eq!(used, Used::Dnglab); + assert_eq!((raw.width, raw.height, raw.active_area), (ours.width, ours.height, ours.active_area)); + assert_eq!(raw.data, ours.data, "the same samples"); + assert_eq!(raw.cfa, ours.cfa); + assert_eq!(raw.metadata, ours.metadata); + for hostile in [vec![], b"II*\0\x08\0\0\0\xff\xff".to_vec(), unsupported()] { + assert!(backend.decode(&hostile).is_err()); + } +} + /// A 16-bit unsigned FITS colour filter array (issue #1604), 16 × 8 pixels; with `axes` more than two, a data cube. fn fits(axes: usize) -> Vec { let kw = |name: &str, value: i32| format!("{:<80}", format!("{name:<8}= {value:>20}")); @@ -139,16 +194,16 @@ fn fits(axes: usize) -> Vec { fn fits_is_read_by_lcc_raw_whatever_the_choice() { let bytes = fits(2); let fake = Fake::new(Err("unsupported file format".into())); - let (raw, used) = decode_as(&bytes, Decoder::Auto, Some(&fake)).unwrap(); + let (raw, used) = decode_as(&bytes, Decoder::Auto, Some(&fake), None).unwrap(); assert_eq!((used, fake.calls()), (Used::Lcc, 0)); assert_eq!(raw, lcc_raw::decode(&bytes).unwrap()); - let (raw, used) = decode_as(&bytes, Decoder::Libraw, Some(&fake)).unwrap(); + let (raw, used) = decode_as(&bytes, Decoder::Libraw, Some(&fake), None).unwrap(); assert_eq!((used, fake.calls()), (Used::Lcc, 1)); assert_eq!((raw.format, raw.width, raw.height), (lcc_raw::RawFormat::Fits, 16, 8)); - let (raw, used) = decode_as(&bytes, Decoder::Libraw, None).unwrap(); + let (raw, used) = decode_as(&bytes, Decoder::Libraw, None, None).unwrap(); assert_eq!((used, raw.format), (Used::Lcc, lcc_raw::RawFormat::Fits)); // a variant lcc-raw refuses is handed to LibRaw, which cannot read FITS either: the refusal names the reason - let err = decode_as(&fits(4), Decoder::Auto, Some(&fake)).unwrap_err(); + let err = decode_as(&fits(4), Decoder::Auto, Some(&fake), None).unwrap_err(); assert!(matches!(&err, lcc_raw::RawError::Unsupported(m) if m.contains("4 axes")), "{err}"); assert_eq!(fake.calls(), 2); } @@ -157,6 +212,9 @@ fn fits_is_read_by_lcc_raw_whatever_the_choice() { fn a_frame_without_app_headers_takes_libraws_matrix_and_the_whole_image_area() { let raw = frame().into_raw_image(&unsupported()).unwrap(); assert_eq!(raw.crop, lcc_raw::Rect::new(0, 0, 32, 24)); + // a decoder's own default crop stands in for the app's when the app can't read the headers + let with_crop = Frame { crop: Some(lcc_raw::Rect::new(2, 1, 28, 20)), ..frame() }; + assert_eq!(with_crop.into_raw_image(&unsupported()).unwrap().crop, lcc_raw::Rect::new(2, 1, 28, 20)); assert_eq!(raw.color.color_matrix[0], frame().xyz_to_camera); assert_eq!(raw.color.illuminant[0], 21); // and it develops like any other mosaic @@ -290,3 +348,41 @@ fn libraws_matrix_is_used_only_when_neither_the_file_nor_the_camera_table_has_on // a file that is no more than a name has no model at all assert!(!app_table_has_matrix(Some("NIKON CORPORATION"), None)); } + +/// FX-194: a DNG export reads the raw with the decoder chosen for its camera, like every other raw read; it used to +/// call `lcc-raw` directly, so a camera set to LibRaw was exported from a different mosaic than the one it shows. +#[test] +fn dng_export_reads_the_raw_with_the_cameras_chosen_decoder() { + let _turn = CHOICES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let metadata = lcc_meta::Metadata { make: Some("FX194 Maker".into()), model: Some("FX194 Model".into()), ..Default::default() }; + let bytes = crate::tests_xmp::synthetic_dng_with(None, metadata); + let dir = std::env::temp_dir().join(format!("lc-fx194-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Raw.dng"); + std::fs::write(&file, &bytes).unwrap(); + let mut s = crate::Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().find(|p| p.file_name == "Raw.dng").unwrap().id; + let opts = crate::export::ExportOptions::from_json(&json!({"format": "dng"})); + + let m = lcc_meta::extract(&bytes); + let camera = lcc_catalog::camera_label(m.make.as_deref().unwrap_or_default(), m.model.as_deref().unwrap_or_default()); + assert!(!camera.is_empty(), "the fixture names its camera"); + let fake = Arc::new(Fake::new(Ok(frame()))); + install_libraw(Some(fake.clone() as Arc)); + let choices = BTreeMap::from([(camera, Decoder::Libraw)]); + install_choices(&choices); + let exported = crate::export::export_photo(&mut s, id, &opts, 1); + let calls = fake.calls(); + // put the process-wide state back before any assertion can unwind past it + install_libraw(None); + install_choices(&BTreeMap::new()); + let _ = std::fs::remove_dir_all(&dir); + + let exported = exported.unwrap(); + assert!(calls >= 1, "the DNG export never reached the camera's chosen decoder"); + // the DNG holds LibRaw's mosaic (34 x 24 with a masked border), not the 16-px-wide file's own + let back = lcc_raw::decode(&exported.bytes).unwrap(); + assert_eq!((back.width, back.height), (34, 24), "the DNG was not written from the chosen decoder's mosaic"); +} diff --git a/crates/engine/src/tests_spots.rs b/crates/engine/src/tests_spots.rs index f48f5de342..7514e72b64 100644 --- a/crates/engine/src/tests_spots.rs +++ b/crates/engine/src/tests_spots.rs @@ -21,7 +21,7 @@ fn up_and_down_move_by_rows_and_stop_at_the_ends() { assert_eq!(s.selection.active, vis.last().copied(), "hostile counts clamp, never overflow"); } -/// F-66C0: with no photo active (none selected, or the state Cmd+D leaves), ↑ selects the first photo of the view and +/// With no photo active (none selected, or the state Cmd+D leaves), ↑ selects the first photo of the view and /// ↓ the last, each made active; with a photo active they step from it as before. #[test] fn with_no_photo_active_up_takes_the_first_and_down_the_last() { diff --git a/crates/engine/src/tests_view_undo.rs b/crates/engine/src/tests_view_undo.rs index 2d4777dcf4..75def298e0 100644 --- a/crates/engine/src/tests_view_undo.rs +++ b/crates/engine/src/tests_view_undo.rs @@ -426,3 +426,34 @@ fn undo_and_redo_save_no_version_of_the_photo_they_leave() { s.execute("edit.redo", &json!({})).unwrap(); assert_eq!(versions(&s), before, "nor does Redo"); } + +#[test] +fn navigation_set_aside_from_the_top_comes_back_in_order() { + let mut s = Session::with_demo(); + assert!(s.set_aside_navigation().is_empty(), "an empty history has nothing to set aside"); + let vis = s.visible_cloned(); + s.execute("photo.rate", &json!({"rating": 4})).unwrap(); + s.execute("library.select", &json!({"ids": [vis[1].0]})).unwrap(); + s.execute("library.select", &json!({"ids": [vis[0].0]})).unwrap(); + let before: Vec = s.undo.iter().map(|e| e.label.clone()).collect(); + let held = s.set_aside_navigation(); + assert_eq!(held.len(), 2, "the moves above the rating"); + assert!(held.iter().all(|e| e.is_navigation())); + assert!(s.undo.last().is_some_and(|e| !e.is_navigation()), "the edit is the newest step meanwhile"); + s.restore_navigation(held); + let after: Vec = s.undo.iter().map(|e| e.label.clone()).collect(); + assert_eq!(after, before, "the same steps in the same order"); +} + +#[test] +fn a_history_of_only_moves_is_all_set_aside_and_restored() { + let mut s = Session::with_demo(); + let vis = s.visible_cloned(); + s.execute("library.select", &json!({"ids": [vis[1].0]})).unwrap(); + let n = s.undo.len(); + let held = s.set_aside_navigation(); + assert_eq!(held.len(), n); + assert!(s.undo.is_empty()); + s.restore_navigation(held); + assert_eq!(s.undo.len(), n); +} diff --git a/crates/engine/src/tests_xmp.rs b/crates/engine/src/tests_xmp.rs index 400566bcff..8a165f874c 100644 --- a/crates/engine/src/tests_xmp.rs +++ b/crates/engine/src/tests_xmp.rs @@ -68,7 +68,7 @@ pub(crate) fn write_png(path: &Path, seed: u8) { } pub(crate) fn synthetic_psd_with_metadata(metadata: &lcc_meta::Metadata) -> Vec { - let exif = lcc_meta::write_exif(metadata); + let exif = lcc_meta::write_exif(metadata).unwrap(); let xmp = lcc_meta::write_xmp(metadata, None); let pixels = [40, 80, 120]; let image = lcc_codecs::EncodeImage::new(1, 1, 3, lcc_codecs::Samples::U8(&pixels)); @@ -77,7 +77,7 @@ pub(crate) fn synthetic_psd_with_metadata(metadata: &lcc_meta::Metadata) -> Vec< } pub(crate) fn synthetic_psb_with_metadata(metadata: &lcc_meta::Metadata) -> Vec { - let exif = lcc_meta::write_exif(metadata); + let exif = lcc_meta::write_exif(metadata).unwrap(); let xmp = lcc_meta::write_xmp(metadata, None); let pixels = [1024u16, 2048, 3072]; let image = lcc_codecs::EncodeImage::new(1, 1, 3, lcc_codecs::Samples::U16(&pixels)); @@ -606,7 +606,7 @@ const STORED_FRAME_REGIONS: &str = r#" /// A JPEG of 32 × 24 pixels stored sideways (Exif orientation 6, shown 24 × 32), with `packet` embedded when given. fn write_turned_jpeg(path: &Path, packet: Option<&str>) { let img = lcc_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); - let exif = lcc_meta::write_exif(&lcc_meta::Metadata { orientation: Some(lcc_meta::Orientation::Rotate90), ..Default::default() }); + let exif = lcc_meta::write_exif(&lcc_meta::Metadata { orientation: Some(lcc_meta::Orientation::Rotate90), ..Default::default() }).unwrap(); let meta = lcc_codecs::EncodeMeta { exif: Some(&exif), xmp: packet, ..Default::default() }; let bytes = lcc_codecs::encode_jpeg(&lcc_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap(); std::fs::write(path, bytes).unwrap(); @@ -1232,7 +1232,7 @@ fn all_metadata_lists_exif_and_xmp() { let dir = temp_dir("allmeta"); let path = dir.join("tagged.jpg"); let img = lcc_raster::Rgba8 { width: 16, height: 8, data: vec![[90, 120, 200, 255]; 128] }; - let exif = lcc_meta::write_exif(&lcc_meta::Metadata { make: Some("Maker".into()), iso: Some(800), ..Default::default() }); + let exif = lcc_meta::write_exif(&lcc_meta::Metadata { make: Some("Maker".into()), iso: Some(800), ..Default::default() }).unwrap(); let meta = lcc_codecs::EncodeMeta { exif: Some(&exif), ..Default::default() }; let jpg = lcc_codecs::encode_jpeg(&lcc_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap(); std::fs::write(&path, jpg).unwrap(); @@ -1555,7 +1555,7 @@ fn external_edit_copy_as_psd_round_trips() { let src = dir.join("pier.png"); let capture = lcc_meta::DateTime::parse_iso("2023-05-14T14:40:39").unwrap(); let source_meta = lcc_meta::Metadata { capture_time: Some(capture), title: Some("Dated original".into()), ..Default::default() }; - let exif = lcc_meta::write_exif(&source_meta); + let exif = lcc_meta::write_exif(&source_meta).unwrap(); let xmp = lcc_meta::write_xmp(&source_meta, None); let rgba = lcc_raster::Rgba8::from_fn(40, 24, |x, y| [(x * 6) as u8, (y * 9) as u8, 40, 255]); let png = lcc_codecs::encode_png( @@ -1701,7 +1701,7 @@ fn gps_typed_in_is_saved_to_xmp() { fn write_png_at(path: &Path, lat: f64, lon: f64) { let img = lcc_raster::Rgba8 { width: 8, height: 8, data: vec![[90, 120, 150, 255]; 64] }; let gps = lcc_meta::Metadata { gps: Some(lcc_meta::Gps { latitude: lat, longitude: lon, altitude: None }), ..Default::default() }; - let exif = lcc_meta::write_exif(&gps); + let exif = lcc_meta::write_exif(&gps).unwrap(); let meta = lcc_codecs::EncodeMeta { exif: Some(&exif), ..Default::default() }; std::fs::write(path, lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(&img), &meta).unwrap()).unwrap(); } @@ -1955,7 +1955,8 @@ fn write_jpeg(path: &Path, capture: Option<&str>) { let (w, h) = (32usize, 24usize); let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 7) as u8, (i / w * 9) as u8, 90, 255]).collect(); let img = lcc_raster::Rgba8 { width: w, height: h, data }; - let exif = capture.map(|c| lcc_meta::write_exif(&lcc_meta::Metadata { capture_time: lcc_meta::DateTime::parse_iso(c), ..Default::default() })); + let exif = + capture.map(|c| lcc_meta::write_exif(&lcc_meta::Metadata { capture_time: lcc_meta::DateTime::parse_iso(c), ..Default::default() }).unwrap()); let meta = lcc_codecs::EncodeMeta { exif: exif.as_deref(), ..Default::default() }; let bytes = lcc_codecs::encode_jpeg(&lcc_codecs::EncodeImage::rgba8(&img), 90, Default::default(), &meta).unwrap(); std::fs::write(path, bytes).unwrap(); diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index e500bba9f8..321015a690 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -415,6 +415,14 @@ pub fn filter_chips(f: &Filter, cat: &Catalog) -> Vec { (None, Some(b)) => add(format!("Captured until {b}"), json!({"dateTo": Null})), _ => {} } + // the Memories filter (a command's `library.filter`, or a smart collection from such a view) + if let Some(day) = &f.capture_month_day { + let label = match f.capture_before_year { + Some(year) => format!("Captured on {day} before {year}"), + None => format!("Captured on {day}"), + }; + add(label, json!({"captureMonthDay": Null, "captureBeforeYear": Null})); + } if let Some(rs) = f.rule_set.as_ref().filter(|r| !r.rules.is_empty()) { add(format!("Rules: {}", rs.describe_with(cat)), json!({"ruleSet": Null})); } diff --git a/crates/engine/src/view_undo.rs b/crates/engine/src/view_undo.rs index 2195e8c3a7..3db5a80e3e 100644 --- a/crates/engine/src/view_undo.rs +++ b/crates/engine/src/view_undo.rs @@ -189,6 +189,20 @@ impl Session { r } + /// Take the navigation steps off the top of the undo stack and return them, oldest first: what a + /// person did to the view after their last edit. Give them back with + /// [`Session::restore_navigation`], so a change to that edit can replace its step in place. + pub fn set_aside_navigation(&mut self) -> Vec { + let keep = self.undo.iter().rposition(|e| !e.is_navigation()).map_or(0, |i| i + 1); + self.undo.split_off(keep) + } + + /// Put the steps [`Session::set_aside_navigation`] returned back on top of the undo stack. + pub fn restore_navigation(&mut self, held: Vec) { + self.undo.extend(held); + self.trim_undo(); + } + /// Whether changes of the view are steps; returns what it was. Off, the app moves the view by itself (an /// import showing the photos it brought in), which is not the person's navigation. pub fn record_navigation(&mut self, on: bool) -> bool { @@ -306,7 +320,9 @@ impl Session { /// only the filter's text changed (typing). fn label_for(id: &str, before: &ViewState, after: &ViewState) -> (&'static str, bool) { let module_changed = before.module != after.module; + // another day of On This Day is another view of it, as another folder is let source_changed = before.source != after.source + || before.memories_day != after.memories_day || before.browse != after.browse || before.library_folder != after.library_folder || before.folder_subfolders != after.folder_subfolders; diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index cd38cac712..f9e83f6a1f 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -89,7 +89,7 @@ impl Headless { /// (see `lcc_engine::export::ExportOptions::from_json`, plus `ids`, `dir`, `path`). /// With `path` and no `format`, the format follows the path's extension. fn export(&mut self, p: &Value) -> Result { - use lcc_engine::export::{Destination, ExportFormat, ExportOptions, Resize, prepare_batch, run_batch}; + use lcc_engine::export::{BatchStop, Destination, ExportFormat, ExportOptions, Resize, prepare_batch, run_batch_outcome}; let p = &self.session.export_params_or(p, ExportFormat::Png)?; // PNG for a `path` that names no format; `bitDepth` is checked against the format written let mut opts = ExportOptions::from_params_or(p, ExportFormat::Png).map_err(|e| e.to_string())?; @@ -138,7 +138,7 @@ impl Headless { let stop_on_error = total == 1; let mut hook = self.progress.take(); let mut cancelled = false; - let files = run_batch( + let outcome = run_batch_outcome( items, &opts, &Destination::on_disk(dir.to_string(), exact.map(str::to_string)), @@ -149,18 +149,25 @@ impl Headless { cancelled = hook.as_mut().is_some_and(|h| !h(done, total, name)); !cancelled }, - )?; + ); + // a single photo that failed is an error (it wrote nothing); a batch stopped by a cancel still reports, marks + // and hands on the files it wrote, saying it stopped (FX-187) + if let Some(BatchStop::Failed(e)) = &outcome.stopped + && !outcome.wrote_any() + { + return Err(e.clone()); + } if !cancelled && let Some(hook) = hook.as_mut() { cancelled = !hook(total, total, ""); } - if cancelled { - return Err("cancelled".into()); - } + let stopped = outcome.stopped.as_ref().map(BatchStop::name); + let files = outcome.files; lcc_engine::export::mark_exported(&mut self.session, &files); // Single-photo exports also report path/width/height at the top level (back-compat); a // per-file error is never promoted to the top level. let mut out = files.first().filter(|file| file.get("error").is_none()).cloned().unwrap_or_else(|| json!({})); - if let Some(photos) = after.run(&files, false) { + // (a cancelled export adds nothing to Photos, as in the app) + if let Some(photos) = after.run(&files, cancelled) { out["applePhotos"] = photos; } // plug-in export hooks, then the plug-in destination the export named (if any) @@ -169,6 +176,9 @@ impl Headless { out["plugins"] = json!(r); } out["files"] = json!(files); + if let Some(stopped) = stopped { + out["stopped"] = json!(stopped); + } Ok(out) } } @@ -400,6 +410,33 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// FX-187: a headless batch cancelled part-way (the client's cancel) still reports the files it wrote, marks + /// their photos exported and says it stopped, rather than ending in an error that drops them. A cancel that + /// comes only once every photo is written leaves the batch complete. + #[test] + fn a_cancelled_headless_batch_reports_and_marks_what_it_wrote() { + for cancel_at in [1, 2, 3] { + let out = std::env::temp_dir().join(format!("lc-mcp-cancel-export-{}-{cancel_at}", std::process::id())); + let _ = std::fs::remove_dir_all(&out); + let mut h = Headless::demo(); + let ids: Vec = h.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + // (the hook is called before each photo with the photos done, then once with the total) + h.set_progress(Some(Box::new(move |done, _, _| done < cancel_at))); + let r = h.call("app.export", json!({"ids": ids, "dir": out.to_string_lossy(), "longEdge": 32, "format": "png"})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), cancel_at, "{cancel_at}: {r}"); + assert_eq!(r.get("stopped").and_then(Value::as_str), (cancel_at < ids.len()).then_some("cancelled"), "{cancel_at}: {r}"); + for (i, id) in ids.iter().enumerate() { + let exported = h.session.catalog.photo(PhotoId(*id)).unwrap().exported.is_some(); + assert_eq!(exported, i < cancel_at, "{cancel_at}: photo {i} marked exported only when written: {r}"); + } + for f in files { + assert!(Path::new(f["path"].as_str().unwrap()).is_file(), "{cancel_at}: {r}"); + } + let _ = std::fs::remove_dir_all(&out); + } + } + /// Upstream #4737 (issue #4714): a missing original in a headless export is reported per file, and later photos still export. #[test] fn a_missing_original_does_not_stop_a_headless_batch_export() { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index e1f3ee24f0..33980ad8bb 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -200,6 +200,25 @@ fn a_preset_depth_is_judged_against_the_format_written() { let _ = std::fs::remove_dir_all(&base); } +/// FX-191: a preset's format against the extension of the caller's exact path. JPEG bytes were +/// written to `a.png`; now the call is refused and nothing is written, while a path that agrees +/// (or names no format) exports as before. +#[test] +fn a_preset_format_never_writes_a_file_named_for_another() { + let mut b = Headless::demo(); + let base = std::env::temp_dir().join(format!("lc-mcp-preset-path-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let e = b.call("app.export", json!({"preset": "JPEG (Small)", "path": base.join("a.png").to_string_lossy(), "longEdge": 32})).unwrap_err(); + assert!(e.contains("preset `JPEG (Small)`") && e.contains("ends in `.png`") && e.contains("`.jpg`"), "{e}"); + let r = call_tool(&mut b, "export", &json!({"preset": "JPEG (Small)", "path": base.join("b.png").to_string_lossy(), "longEdge": 32})); + assert!(r.is_error, "{r:?}"); + assert_eq!(std::fs::read_dir(&base).unwrap().count(), 0, "nothing written"); + b.call("app.export", json!({"preset": "JPEG (Small)", "path": base.join("a.jpg").to_string_lossy(), "longEdge": 32})).unwrap(); + assert!(std::fs::read(base.join("a.jpg")).unwrap().starts_with(&[0xFF, 0xD8]), "a JPEG"); + let _ = std::fs::remove_dir_all(&base); +} + /// Every option the `export` tool advertises reaches `app.export` (they were accepted, then dropped). #[test] fn export_tool_forwards_its_advertised_options() { diff --git a/crates/meta/src/container.rs b/crates/meta/src/container.rs index a974661e30..2e1225a51e 100644 --- a/crates/meta/src/container.rs +++ b/crates/meta/src/container.rs @@ -545,7 +545,7 @@ mod tests { let mut jpeg = vec![0xff, 0xd8]; if let Some(orientation) = exif_orientation { let mut exif = b"Exif\0\0".to_vec(); - exif.extend(crate::exif::write_exif(&crate::Metadata { orientation: Some(orientation), ..Default::default() })); + exif.extend(crate::exif::write_exif(&crate::Metadata { orientation: Some(orientation), ..Default::default() }).unwrap()); jpeg.extend(seg(0xe1, &exif)); } let packet = format!( diff --git a/crates/meta/src/datetime.rs b/crates/meta/src/datetime.rs index 3fe5c0399a..b899b1809c 100644 --- a/crates/meta/src/datetime.rs +++ b/crates/meta/src/datetime.rs @@ -301,7 +301,7 @@ mod tests { let xmp = crate::write_xmp(&meta, None); assert!(!xmp.contains("DateTimeOriginal"), "{xmp}"); assert_eq!(crate::parse_xmp(&xmp).unwrap().metadata.capture_time, Some(d), "{xmp}"); - assert_eq!(crate::read_exif(&crate::write_exif(&meta)).capture_time, None, "Exif can't say {iso}"); + assert_eq!(crate::read_exif(&crate::write_exif(&meta).unwrap()).capture_time, None, "Exif can't say {iso}"); } for not in ["0000", "1983-00", "1983-13", "1983-04T10:00:00", "1983T10:00"] { assert_eq!(DateTime::parse_iso(not), None, "{not}"); diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index 15f29d54cb..e7b965c461 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -808,9 +808,22 @@ fn reciprocal(v: Option) -> Option { /// Serialise the interchange subset of `meta` as a TIFF-structured Exif block (little-endian, no /// `Exif\0\0` prefix): IFD0 (make, model, software, artist, copyright, description, orientation, /// date), the Exif IFD (capture settings, lens) and, when present, the GPS IFD. -pub fn write_exif(meta: &Metadata) -> Vec { +/// +/// A block that can't be serialised (a text field past what a classic TIFF holds) is an error the caller reports, +/// never an empty block embedded in its place (FX-189). +pub fn write_exif(meta: &Metadata) -> Result, TiffError> { + serialise(exif_ifd0(meta)) +} + +/// The TIFF stream of an Exif block whose IFD0 is `ifd0` (its Exif and GPS IFDs are its children). +fn serialise(ifd0: lcc_tiff::IfdBuilder) -> Result, TiffError> { + lcc_tiff::TiffWriter::new(lcc_tiff::ByteOrder::Little, false).write(&[ifd0]) +} + +/// IFD0 of [`write_exif`]'s block, with the Exif IFD and (when `meta` has a position) the GPS IFD as children. +fn exif_ifd0(meta: &Metadata) -> lcc_tiff::IfdBuilder { use lcc_tiff::writer::{rational, srational}; - use lcc_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + use lcc_tiff::{IfdBuilder, Value}; let ascii = |s: &Option| s.as_ref().filter(|v| !v.is_empty()).map(|v| Value::Ascii(v.clone())); let mut ifd0 = IfdBuilder::new(); for (tag, v) in [ @@ -880,7 +893,7 @@ pub fn write_exif(meta: &Metadata) -> Vec { } ifd0.set_child(t::GPS_IFD, gps); } - TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap_or_default() + ifd0 } #[cfg(test)] @@ -888,11 +901,33 @@ pub fn write_exif(meta: &Metadata) -> Vec { mod write_tests { use super::*; + /// A block the writer can't serialise is an error the caller sees, never an empty block in its place (FX-189). An IFD + /// chain nested past the writer's depth limit stands in for a field too large for a classic TIFF. + #[test] + fn a_block_that_cannot_be_serialised_is_an_error_not_an_empty_block() { + let leaf = || { + let mut b = lcc_tiff::IfdBuilder::new(); + b.set(t::MAKE, lcc_tiff::Value::Ascii("x".into())); + b + }; + let mut deep = leaf(); + for _ in 0..20 { + let mut parent = leaf(); + parent.set_child(t::EXIF_IFD, deep); + deep = parent; + } + assert!(serialise(deep).is_err(), "an unwritable block came back as Ok"); + // an ordinary block serialises and reads back + let m = Metadata { copyright: Some("C".into()), ..Default::default() }; + let ok = write_exif(&m).unwrap(); + assert_eq!(read_exif(&ok).copyright.as_deref(), Some("C")); + } + #[test] fn capture_time_offset_and_subsec_round_trip() { for iso in ["2026-09-20T05:40:00.250+02:00", "2026-09-20T05:40:00.005-03:30", "2026-09-20T05:40:00"] { let m = Metadata { capture_time: DateTime::parse_iso(iso), ..Default::default() }; - assert_eq!(read_exif(&write_exif(&m)).capture_time, m.capture_time, "{iso}"); + assert_eq!(read_exif(&write_exif(&m).unwrap()).capture_time, m.capture_time, "{iso}"); } } @@ -912,7 +947,7 @@ mod write_tests { gps: Some(Gps { latitude: 43.7904, longitude: -110.6818, altitude: Some(2000.0) }), ..Default::default() }; - let back = read_exif(&write_exif(&m)); + let back = read_exif(&write_exif(&m).unwrap()); assert_eq!(back.make, m.make); assert_eq!(back.model, m.model); assert_eq!(back.copyright, m.copyright); @@ -929,7 +964,7 @@ mod write_tests { #[test] fn iso_above_65534_round_trips() { for iso in [65_534, 65_535, 102_400, 409_600] { - let back = read_exif(&write_exif(&Metadata { iso: Some(iso), ..Default::default() })); + let back = read_exif(&write_exif(&Metadata { iso: Some(iso), ..Default::default() }).unwrap()); assert_eq!(back.iso, Some(iso)); } } @@ -937,7 +972,7 @@ mod write_tests { #[test] fn fast_shutter_speeds_round_trip_exactly() { for den in [8000.0, 12_800.0, 16_000.0, 32_000.0] { - let back = read_exif(&write_exif(&Metadata { exposure_time: Some(1.0 / den), ..Default::default() })); + let back = read_exif(&write_exif(&Metadata { exposure_time: Some(1.0 / den), ..Default::default() }).unwrap()); let got = back.exposure_time.unwrap(); assert!((1.0 / got - den).abs() < 0.5, "1/{den} s came back as 1/{}", 1.0 / got); } @@ -947,7 +982,7 @@ mod write_tests { fn written_shutter_speeds_show_as_the_same_text() { // #1619: the exact time is what export writes, and it reads back as the text shown for (t, want) in [(1.0 / 3.0, "1/3"), (1.0 / 250.0, "1/250"), (1.0 / 12_800.0, "1/12800"), (0.3, "0.3"), (1.0 / 2.8, "0.3571")] { - let back = read_exif(&write_exif(&Metadata { exposure_time: Some(t), ..Default::default() })); + let back = read_exif(&write_exif(&Metadata { exposure_time: Some(t), ..Default::default() }).unwrap()); let got = back.exposure_time.unwrap(); assert_eq!(crate::format_exposure_time(got).as_deref(), Some(want), "{t} came back as {got}"); } diff --git a/crates/meta/src/exif_carry.rs b/crates/meta/src/exif_carry.rs index a2203ef5d0..6c41d6d61e 100644 --- a/crates/meta/src/exif_carry.rs +++ b/crates/meta/src/exif_carry.rs @@ -96,6 +96,36 @@ pub fn exif_leaves_out(m: &Metadata) -> Vec<&'static str> { found.into_iter().filter(|(_, set)| *set).map(|(name, _)| name).collect() } +/// Every set field of `m` that an export's Exif block or XMP packet carries, as short names (each once, the Exif +/// block's first, then [`exif_leaves_out`]'s): what a file that holds no metadata at all (OpenEXR) leaves out. The +/// program's name in Software and the orientation (an export's pixels are upright) are not counted (FX-188). +pub fn metadata_fields(m: &Metadata) -> Vec<&'static str> { + let text = |s: &Option| s.as_deref().is_some_and(|s| !s.trim().is_empty()); + let exif: [(&'static str, bool); 6] = [ + ("caption", text(&m.caption)), + ("creator", text(&m.artist)), + ("copyright", text(&m.copyright)), + ("capture time", m.capture_time.is_some()), + ("location", m.gps.is_some()), + ( + "camera details", + [&m.make, &m.model, &m.lens_make, &m.lens_model].into_iter().any(text) + || m.exposure_time.is_some() + || m.f_number.is_some() + || m.iso.is_some() + || m.focal_length.is_some() + || m.exposure_bias.is_some(), + ), + ]; + let mut out: Vec<&'static str> = exif.into_iter().filter(|(_, set)| *set).map(|(name, _)| name).collect(); + for name in exif_leaves_out(m) { + if !out.contains(&name) { + out.push(name); + } + } + out +} + #[cfg(test)] mod tests { use super::*; @@ -152,6 +182,28 @@ mod tests { assert!(exif_leaves_out(&blank).is_empty()); } + /// A file with no metadata at all names every field it was given, each once: the Exif block's, then the rest. + #[test] + fn metadata_fields_names_the_exif_part_and_the_rest() { + assert!(metadata_fields(&Metadata::default()).is_empty()); + // the program's name and the orientation are not the photo's metadata + let app = Metadata { software: Some("App".into()), orientation: Some(crate::Orientation::Normal), ..Default::default() }; + assert!(metadata_fields(&app).is_empty(), "{:?}", metadata_fields(&app)); + let m = Metadata { + copyright: Some("© Me".into()), + artist: Some("Me".into()), + iso: Some(100), + gps: Some(crate::Gps { latitude: 1.0, longitude: 2.0, altitude: None }), + city: Some("Porto".into()), + serial_number: Some("123".into()), + title: Some("T".into()), + ..Default::default() + }; + assert_eq!(metadata_fields(&m), ["creator", "copyright", "location", "camera details", "title"]); + // blank text is not set + assert!(metadata_fields(&Metadata { copyright: Some(" ".into()), ..Default::default() }).is_empty()); + } + /// The Exif side of the list is true: each field said to be in the Exif block reads back from it. #[test] fn what_is_said_to_be_in_exif_reads_back_from_it() { @@ -166,7 +218,7 @@ mod tests { iso: Some(200), ..Default::default() }; - let back = crate::read_exif(&crate::write_exif(&m)); + let back = crate::read_exif(&crate::write_exif(&m).unwrap()); assert_eq!((back.make, back.model, back.artist, back.copyright), (m.make, m.model, m.artist, m.copyright)); assert_eq!((back.caption, back.software, back.lens_model, back.iso), (m.caption, m.software, m.lens_model, m.iso)); } diff --git a/crates/meta/src/heif.rs b/crates/meta/src/heif.rs index 1fd8d007a5..567a23e1a5 100644 --- a/crates/meta/src/heif.rs +++ b/crates/meta/src/heif.rs @@ -627,7 +627,7 @@ mod tests { } fn tiff_with(model: &str) -> Vec { - crate::write_exif(&crate::Metadata { model: Some(model.into()), ..Default::default() }) + crate::write_exif(&crate::Metadata { model: Some(model.into()), ..Default::default() }).unwrap() } #[derive(Clone, Copy, PartialEq)] @@ -832,7 +832,7 @@ mod tests { #[test] fn a_heic_location_is_seen() { let gps = crate::Gps { latitude: 38.7, longitude: -9.1, altitude: None }; - let tiff = crate::write_exif(&crate::Metadata { gps: Some(gps), ..Default::default() }); + let tiff = crate::write_exif(&crate::Metadata { gps: Some(gps), ..Default::default() }).unwrap(); let f = Heif::new().item(2, b"Exif", exif_item(b"Exif\0\0", &tiff), Store::File, 1).cdsc(2, &[1]).build(); let back = crate::extract(&f).gps.expect("the location"); assert!((back.latitude - 38.7).abs() < 1e-6 && (back.longitude + 9.1).abs() < 1e-6, "{back:?}"); @@ -1083,7 +1083,7 @@ mod tests { } fn tiff_at(latitude: f64) -> Vec { - crate::write_exif(&crate::Metadata { gps: Some(crate::Gps { latitude, longitude: 2.0, altitude: None }), ..Default::default() }) + crate::write_exif(&crate::Metadata { gps: Some(crate::Gps { latitude, longitude: 2.0, altitude: None }), ..Default::default() }).unwrap() } /// Export's "remove location" check sees GPS anywhere in a HEIF's metadata, not only in the diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index dea4141dae..48f3f631fd 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -50,7 +50,7 @@ pub use xmp::{ pub use xmp_merge::{MergeRules, merge_xmp}; mod exif_carry; -pub use exif_carry::exif_leaves_out; +pub use exif_carry::{exif_leaves_out, metadata_fields}; use serde::{Deserialize, Serialize}; diff --git a/crates/meta/src/psd.rs b/crates/meta/src/psd.rs index 53a7f54a94..4fb85d3051 100644 --- a/crates/meta/src/psd.rs +++ b/crates/meta/src/psd.rs @@ -123,7 +123,7 @@ mod tests { } fn dated_image(version: u16) -> Vec { - let exif = crate::write_exif(&dated_metadata()); + let exif = crate::write_exif(&dated_metadata()).unwrap(); image(version, &[], &resource(1058, b"", &exif)) } @@ -161,7 +161,7 @@ mod tests { #[test] fn psd_normalizes_the_optional_exif_resource_prefix() { let mut exif = b"Exif\0\0".to_vec(); - exif.extend(crate::write_exif(&dated_metadata())); + exif.extend(crate::write_exif(&dated_metadata()).unwrap()); let file = image(1, &[], &resource(1058, b"", &exif)); assert_eq!(crate::extract(&file).capture_time, dated_metadata().capture_time); } @@ -246,8 +246,8 @@ mod tests { fn try_extract_rejects_duplicate_psd_exif_and_xmp_resources() { let gps = dated_metadata(); let no_gps = Metadata::default(); - let gps_exif = crate::write_exif(&gps); - let no_gps_exif = crate::write_exif(&no_gps); + let gps_exif = crate::write_exif(&gps).unwrap(); + let no_gps_exif = crate::write_exif(&no_gps).unwrap(); let gps_xmp = crate::write_xmp(&gps, None); let no_gps_xmp = crate::write_xmp(&no_gps, None); @@ -262,7 +262,7 @@ mod tests { #[test] fn psd_skips_unknown_resources_with_pascal_name_and_payload_padding() { - let exif = crate::write_exif(&dated_metadata()); + let exif = crate::write_exif(&dated_metadata()).unwrap(); let mut resources = resource(4000, b"xy", &[1, 2, 3]); resources.extend(resource(1058, b"", &exif)); let file = image(1, &[8, 7, 6], &resources); diff --git a/crates/meta/src/tags.rs b/crates/meta/src/tags.rs index 8c135967dd..3f350c9834 100644 --- a/crates/meta/src/tags.rs +++ b/crates/meta/src/tags.rs @@ -444,7 +444,7 @@ mod tests { gps: Some(crate::Gps { latitude: 51.5, longitude: -0.12, altitude: Some(20.0) }), ..Default::default() }; - let exif = crate::write_exif(&m); + let exif = crate::write_exif(&m).unwrap(); let t = Tiff::parse(crate::strip_exif_header(&exif)).unwrap(); let rows = tag_rows(&t); let get = |n: &str| rows.iter().find(|r| r.name == n).map(|r| r.value.clone()); diff --git a/crates/peer/src/service/tests.rs b/crates/peer/src/service/tests.rs index e5e048e737..78d15c5238 100644 --- a/crates/peer/src/service/tests.rs +++ b/crates/peer/src/service/tests.rs @@ -113,10 +113,7 @@ fn paired_entry(s: &Service, device_id: &str) -> Option { /// other as paired, and a third party's attempt is refused while they aren't looking. #[test] fn two_devices_find_each_other_and_pair() { - // macOS LAN pairing check: discovery times out on the macOS CI runner; checked in person on - // real Macs instead (see "Checked in person, not on CI" in docs/ci.md) - if cfg!(target_os = "macos") && std::env::var_os("CI").is_some() { - lcc_testkit::skip!(System, "LAN discovery on the macOS CI runner (macOS LAN pairing check, tested in person)"); + if !lcc_testkit::lan_tests(true) { return; } let dir = temp_dir("svc"); @@ -150,6 +147,9 @@ fn two_devices_find_each_other_and_pair() { #[test] fn a_refused_code_pairs_nobody() { + if !lcc_testkit::lan_tests(false) { + return; + } let dir = temp_dir("no"); let a = start(&dir, "Desk", 1); let b = start(&dir, "Tablet", 1); @@ -167,6 +167,9 @@ fn a_refused_code_pairs_nobody() { /// the stored name is the one the device gave over the authenticated channel, not the advert's. #[test] fn a_pairing_stores_the_authenticated_name_on_both_sides() { + if !lcc_testkit::lan_tests(false) { + return; + } let dir = temp_dir("names"); let a = start(&dir, "Desk", 2); let b = start(&dir, "Tablet", 2); @@ -195,6 +198,9 @@ fn a_pairing_stores_the_authenticated_name_on_both_sides() { /// a known device answers with another key, the pairing fails before any code is shown. #[test] fn pairing_checks_who_answered() { + if !lcc_testkit::lan_tests(false) { + return; + } let dir = temp_dir("who"); let a = start(&dir, "Desk", 3); let b = start(&dir, "Tablet", 3); @@ -234,6 +240,9 @@ fn pairing_checks_who_answered() { /// side is still looking at the code: not when it answers, and not after the two-minute wait. #[test] fn a_declined_or_cancelled_pairing_is_seen_at_once() { + if !lcc_testkit::lan_tests(false) { + return; + } let dir = temp_dir("abort"); let a = start(&dir, "Desk", 4); let b = start(&dir, "Tablet", 4); @@ -284,6 +293,9 @@ fn a_declined_or_cancelled_pairing_is_seen_at_once() { /// turn, isn't replaced by a request. #[test] fn the_persons_choice_replaces_an_unanswered_request() { + if !lcc_testkit::lan_tests(false) { + return; + } let dir = temp_dir("slot"); let a = start(&dir, "Desk", 5); let b = start(&dir, "Tablet", 5); @@ -319,6 +331,9 @@ fn the_persons_choice_replaces_an_unanswered_request() { /// found devices again, so either side can pair anew. #[test] fn an_unpair_on_one_side_is_noticed_and_can_be_repaired() { + if !lcc_testkit::lan_tests(false) { + return; + } let (a, b, dir) = paired("unpair", 6); let (a_id, b_id) = (a.device_id(), b.device_id()); assert!(b.connect(&a_id).is_ok()); @@ -361,6 +376,9 @@ fn an_unpair_on_one_side_is_noticed_and_can_be_repaired() { /// on the other side shows up without anyone starting a sync. #[test] fn an_unpair_on_the_other_side_shows_up_by_itself() { + if !lcc_testkit::lan_tests(false) { + return; + } let (a, b, dir) = paired("selfcheck", 7); let (a_id, b_id) = (a.device_id(), b.device_id()); assert!(a.unpair(&b_id).unwrap()); @@ -374,6 +392,9 @@ fn an_unpair_on_the_other_side_shows_up_by_itself() { /// both directions, and is saved; a name in an advert changes nothing by itself. #[test] fn a_paired_devices_new_name_is_stored_once_authenticated() { + if !lcc_testkit::lan_tests(false) { + return; + } let (a, b, dir) = paired("rename", 8); let (a_id, b_id) = (a.device_id(), b.device_id()); assert_eq!(a.rename("Studio").unwrap(), "Studio"); @@ -411,6 +432,9 @@ fn a_paired_devices_new_name_is_stored_once_authenticated() { /// that says what to do. #[test] fn a_device_on_another_protocol_version_is_refused_up_front() { + if !lcc_testkit::lan_tests(false) { + return; + } let (a, b, dir) = paired("version", 9); let b_id = b.device_id(); let mut old = my_beacon(&b.inner).unwrap(); @@ -429,6 +453,9 @@ fn a_device_on_another_protocol_version_is_refused_up_front() { #[test] fn a_shared_device_name_is_reported() { + if !lcc_testkit::lan_tests(false) { + return; + } let dir = temp_dir("collide"); let a = start(&dir, "Desk", 10); let b = start(&dir, "Tablet", 10); @@ -445,6 +472,9 @@ fn a_shared_device_name_is_reported() { /// A damaged store doesn't keep the service from starting: it is set aside and reported. #[test] fn a_damaged_store_is_set_aside_at_start() { + if !lcc_testkit::lan_tests(false) { + return; + } let dir = temp_dir("lost"); let path = dir.join("peers.json"); std::fs::write(&path, b"{\"identity\": 7").unwrap(); @@ -464,6 +494,9 @@ fn a_damaged_store_is_set_aside_at_start() { /// service, takes the pairing slot for longer than it stays, or is answered as if it were paired. #[test] fn hostile_openings_are_refused() { + if !lcc_testkit::lan_tests(false) { + return; + } let dir = temp_dir("openings"); let s = start(&dir, "Desk", 12); let connect = || { @@ -541,6 +574,9 @@ fn hostile_openings_are_refused() { /// like from the device being guessed at) gets pairing requests refused for a while. #[test] fn many_unfinished_handshakes_get_pairing_requests_refused() { + if !lcc_testkit::lan_tests(false) { + return; + } use std::io::Write as _; let dir = temp_dir("abandoned"); let a = start(&dir, "Desk", 13); @@ -718,6 +754,9 @@ fn the_group_is_joined_again_on_a_schedule_and_soon_after_a_failure() { /// also when the membership was lost in between (the interface went away and came back). #[test] fn joining_the_group_again_keeps_it_audible() { + if !lcc_testkit::lan_tests(false) { + return; + } let port = test_port(14); let audible = multicast_loops_back(port); let rx = mdns_socket(port).unwrap(); @@ -845,3 +884,24 @@ fn idle_strangers_cant_hold_every_connection_slot() { t.join().unwrap(); let _ = std::fs::remove_file(&inner.store_path); } + +/// A test that starts the service opens sockets on every interface, which macOS asks about for each +/// rebuilt test binary: it must open with `lcc_testkit::lan_tests`, so one setting skips all of them. +#[test] +fn every_test_that_starts_the_service_checks_the_lan_opt_out() { + // a test and the helpers it calls: a helper that starts the service is itself listed, so a test that only + // calls it needs the check too + const STARTS: [&str; 4] = ["start(", "paired(", "multicast_loops_back(", "mdns_socket("]; + let source = include_str!("tests.rs"); + // each test: from its attribute to the closing brace at the start of a line, whatever sits between (doc + // comments, more attributes, `pub`/`async`) + let unchecked: Vec<&str> = source + .split(concat!("#[", "test]")) + .skip(1) + .map(|t| t.split("\n}\n").next().unwrap_or(t)) + .filter(|t| !t.contains("fn every_test_that_starts_the_service_checks_the_lan_opt_out")) + .filter(|t| STARTS.iter().any(|s| t.contains(s)) && !t.contains("lan_tests(")) + .filter_map(|t| t.split("fn ").nth(1)?.split('(').next()) + .collect(); + assert!(unchecked.is_empty(), "these tests start the service without `if !lcc_testkit::lan_tests(..) {{ return; }}`: {unchecked:?}"); +} diff --git a/crates/pipeline/src/lut.rs b/crates/pipeline/src/lut.rs index c5dd34f1da..07064ddae5 100644 --- a/crates/pipeline/src/lut.rs +++ b/crates/pipeline/src/lut.rs @@ -63,8 +63,9 @@ impl Lut3d { /// The LUT as a `.cube` file ([`Self::parse_cube`] reads it back). pub fn to_cube(&self) -> String { let mut s = String::with_capacity(self.data.len() * 28 + 128); - if let Some(t) = self.title.as_deref().filter(|t| !t.trim().is_empty()) { - s.push_str(&format!("TITLE \"{}\"\n", t.replace('"', "'"))); + // a title with a line break would write the rest of itself as lines of the file (FX-196) + if let Some(t) = self.title.as_deref().and_then(lcc_color::cube::title_text) { + s.push_str(&format!("TITLE \"{t}\"\n")); } s.push_str(&format!("LUT_3D_SIZE {}\n", self.size)); if self.domain_min != [0.0; 3] || self.domain_max != [1.0; 3] { @@ -174,6 +175,32 @@ mod tests { assert!(back.data.iter().zip(&l.data).all(|(a, b)| (0..3).all(|k| (a[k] - b[k]).abs() < 1e-5))); } + /// FX-196: a title with line breaks can't write lines of its own into the file. + #[test] + fn a_title_with_line_breaks_cannot_inject_lines() { + let l = |title: &str| { + Lut3d::parse_cube(&cube(|c| c, 2)).map(|mut l| { + l.title = Some(title.into()); + l + }) + }; + for title in ["a\nDOMAIN_MAX 8 8 8\nLUT_3D_SIZE 3", "a\rDOMAIN_MAX 8 8 8", "a\r\nDOMAIN_MAX 8 8 8", "a\"\nDOMAIN_MAX 8 8 8"] { + let text = l(title).unwrap().to_cube(); + assert!(text.starts_with("TITLE \"a"), "{text:?}"); + assert_eq!(text.matches("TITLE").count(), 1, "{text:?}"); + assert_eq!(text.lines().filter(|x| x.starts_with("DOMAIN") || x.starts_with("LUT_3D_SIZE")).count(), 1, "{text:?}"); + let back = Lut3d::parse_cube(&text).unwrap(); + assert_eq!((back.size, back.domain_min, back.domain_max), (2, [0.0; 3], [1.0; 3]), "{title:?}"); + assert_eq!(back.data.len(), 8); + assert!(back.title.as_deref().is_some_and(|t| t.starts_with('a') && !t.contains(['\n', '\r'])), "{:?}", back.title); + } + // a title of nothing but such characters writes no TITLE line + for title in ["\n", "\r\n", "\"", " \t\r\n\"", ""] { + let text = l(title).unwrap().to_cube(); + assert!(text.starts_with("LUT_3D_SIZE 2\n"), "{title:?}: {text:?}"); + } + } + #[test] fn garbage_token_is_rejected() { let mut s = String::from( diff --git a/crates/plugins/src/context.rs b/crates/plugins/src/context.rs index 96fa50a356..c5e5ce22f0 100644 --- a/crates/plugins/src/context.rs +++ b/crates/plugins/src/context.rs @@ -21,8 +21,9 @@ //! | `program.start` | the program in `programs` | [`HostApi::start_program`] (native only; not in a job) | //! | `job.progress`, `job.detail`, `job.itemDone`, `job.itemFailed`, `job.cancelled` | a job only | [`JobReporter`] | //! -//! In a job, writes to the catalog (`metadata.setStandard`, `library.add`) are refused, and once -//! the job is cancelled every call but `job.cancelled` fails with "cancelled". +//! In a job, `library.remove`, `develop.setCrop` and `photo.virtualCopy` are refused (its host holds +//! `metadata.setStandard` and `library.add` until the job ends), and once the job is cancelled +//! every call but `job.cancelled` fails with "cancelled". use std::path::PathBuf; use std::sync::{Mutex, PoisonError}; @@ -304,7 +305,7 @@ impl CallContext<'_> { if job.cancelled() { return Err("cancelled".into()); } - if matches!(method, "metadata.setStandard" | "library.add" | "library.remove" | "develop.setCrop" | "photo.virtualCopy") { + if matches!(method, "library.remove" | "develop.setCrop" | "photo.virtualCopy") { return Err(format!("{method}: writes to the catalog aren't available in a job yet")); } if method == "program.start" { diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index c1c31fe850..bee8a5f8b7 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -55,7 +55,7 @@ pub use manifest::{ }; pub use permissions::{FsRoot, Group, Permissions, Request, refused_root}; pub use programs::{EndStatus, Exit, Found, ProgramDecl, Reservation, RunDir, Running, StartRequest}; -pub use runtime::{ABI_VERSION, Inspection, Limits, MANIFEST_SECTION, ManifestSource, Outcome, Plugin}; +pub use runtime::{ABI_VERSION, Inspection, Limits, LogLine, LogSource, MANIFEST_SECTION, ManifestSource, Outcome, Plugin}; pub use settings::SettingsStore; pub use signature::{MAX_SIGNATURE_BYTES, SIGNATURE_SECTION, Signature, Signer}; pub use store::NamespaceStore; diff --git a/crates/plugins/src/manager.rs b/crates/plugins/src/manager.rs index f56fc441b7..8c59f35227 100644 --- a/crates/plugins/src/manager.rs +++ b/crates/plugins/src/manager.rs @@ -20,7 +20,7 @@ use serde_json::{Value, json}; use crate::context::{CallContext, HostApi, JobReporter, Unwatched}; use crate::manifest::{Field, dialog_args, parse_version, version_order}; use crate::permissions::{Permissions, Request, refused_root}; -use crate::runtime::{Limits, ManifestSource, Plugin}; +use crate::runtime::{Limits, LogLine, ManifestSource, Plugin}; use crate::settings::{MAX_SETTINGS_BYTES, SettingsStore, command_scope, destination_scope}; use crate::signature::{Signature, Signer}; use crate::store::{NamespaceStore, write_atomic}; @@ -49,7 +49,7 @@ pub struct Installed { pub denied: Vec, /// Folders the manifest asks for that can't be granted, with why ([`refused_root`]). refused: Vec<(String, String)>, - pub log: VecDeque, + pub log: VecDeque, store: Option, /// Its settings and remembered dialog values (shared with a call running off the lock). settings: Arc>, @@ -212,7 +212,12 @@ impl Installed { *self.live.lock().unwrap_or_else(PoisonError::into_inner) = perms; } + /// A note of the host's. fn push_log(&mut self, line: String) { + self.push_line(LogLine::host(line)); + } + + fn push_line(&mut self, line: LogLine) { if self.log.len() >= MAX_LOG { self.log.pop_front(); } @@ -532,7 +537,7 @@ impl PendingCall { if self.job.is_none() { return self.call_once(host, None); } - let mut logs: Vec = Vec::new(); + let mut logs: Vec = Vec::new(); loop { let outcome = self.call_once(host, Some(job)); logs.extend(outcome.logs); @@ -599,7 +604,7 @@ impl PendingCall { let mut outcome = plugin.invoke(&self.request, &mut ctx); // what the host did on the plug-in's behalf that the user should see in its log let notes = std::mem::take(&mut ctx.notes); - outcome.logs.extend(notes); + outcome.logs.extend(notes.into_iter().map(LogLine::host)); outcome } } @@ -804,10 +809,10 @@ impl Manager { let (check_updates, last_check) = state.plugins.get(&id).map_or((false, None), |e| (e.check_updates, e.last_check.clone())); let mut log = VecDeque::new(); if let Err(e) = p.manifest().semver() { - log.push_back(format!("loaded without a valid version ({e}); installing a new version will need one")); + log.push_back(LogLine::host(format!("loaded without a valid version ({e}); installing a new version will need one"))); } let (settings, damaged) = m.open_settings(&id); - log.extend(damaged); + log.extend(damaged.into_iter().map(LogLine::host)); let live = Arc::new(Mutex::new(Permissions::default())); let refused = m.refused_roots(&p.manifest().permissions); let installed = Installed { @@ -1002,6 +1007,21 @@ impl Manager { self.install_plugin(plugin, bytes, grant, allow_downgrade, by_user, false, &SignerAnswer::None) } + /// `path` is where plug-in `id` is written: refuses when a module with another id is there. A + /// file that can't be read as a module is no one's, and is replaced as before. + fn check_file_free(&self, path: &Path, id: &str) -> Result<()> { + let Ok(bytes) = read_module(path, &self.limits) else { return Ok(()) }; + let Ok(found) = Plugin::inspect(&bytes, self.limits.clone(), false) else { return Ok(()) }; + let other = found.manifest.id; + if other != id { + return Err(Error::Io(format!( + "{} holds the plug-in {other:?}, not {id:?}; installing would replace it. Remove that module first (plugin.uninstall {{file}}) or rename it", + path.display() + ))); + } + Ok(()) + } + /// `rollback`: going back to the version kept ([`Manager::rollback`]): it keeps no version to /// go back to, logs the rollback, and pins that version's signer (the user had installed it). #[allow(clippy::too_many_arguments)] @@ -1029,6 +1049,11 @@ impl Manager { return Err(Error::Downgrade { installed: installed.clone(), new }); } let id = plugin.id().to_string(); + // before anything is written: a module copied in under this file name holds another id, and + // the write would replace it while it is loaded + if let Some(dir) = &self.dir { + self.check_file_free(&dir.join(format!("{id}.wasm")), &id)?; + } // before anything is written: a file not signed by the pinned key needs the user's yes let old_pin = self.pin(&id); let pin = decide_pin(&plugin.manifest().name, old_pin.as_ref(), plugin.signature(), signer, rollback)?; @@ -1150,15 +1175,15 @@ impl Manager { self.unloaded.remove(&id); let old = self.plugins.remove(&id); let mut log = old.as_ref().map(|i| i.log.clone()).unwrap_or_default(); - log.extend(stale_error); - log.extend(kept_error); + log.extend(stale_error.into_iter().map(LogLine::host)); + log.extend(kept_error.into_iter().map(LogLine::host)); // a call still running keeps the cell, and gets the new version's grant on its next call let live = old.as_ref().map_or_else(|| Arc::new(Mutex::new(Permissions::default())), |i| i.live.clone()); let settings = match old.map(|i| i.settings) { Some(s) => s, None => { let (s, damaged) = self.open_settings(&id); - log.extend(damaged); + log.extend(damaged.into_iter().map(LogLine::host)); s } }; @@ -1169,7 +1194,7 @@ impl Manager { s.save() }; if let Err(e) = pruned { - log.push_back(format!("settings: {e}")); + log.push_back(LogLine::host(format!("settings: {e}"))); } let refused = self.refused_roots(&plugin.manifest().permissions); let installed = Installed { @@ -1666,6 +1691,14 @@ impl Manager { requested.fs.iter().filter_map(|f| refused_root(&f.path, &protected, self.dir.as_deref()).map(|why| (f.path.clone(), why))).collect() } + /// A note of the host's in plug-in `id`'s log (what the Plug-in Manager tells the user about it: a refused click, a + /// failed update). False when nothing is installed under `id`. + pub fn note(&mut self, id: &str, text: impl Into) -> bool { + let Some(p) = self.plugins.get_mut(id) else { return false }; + p.push_log(text.into()); + true + } + pub fn get(&self, id: &str) -> Option<&Installed> { self.plugins.get(id) } @@ -1804,7 +1837,7 @@ impl Manager { }; let what = request.get("hook").and_then(Value::as_str).unwrap_or("call"); for l in outcome.logs { - p.push_log(l); + p.push_line(l); } match &outcome.value { Err(Error::Cancelled) => p.push_log(format!("{what} cancelled")), diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 99ebe7a7f4..4fb8a23237 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -139,11 +139,63 @@ impl Inspection { } } +/// Who wrote a log line: the host (its own notes on a plug-in) or the plug-in (`host.log`). The host sets it; a +/// plug-in can't choose it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LogSource { + Host, + Plugin, +} + +impl LogSource { + /// The name in `plugin.log` and the prefix of a copied line. + pub fn name(self) -> &'static str { + match self { + LogSource::Host => "host", + LogSource::Plugin => "plugin", + } + } +} + +/// One line of a plug-in's log, on one line of text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LogLine { + pub source: LogSource, + pub text: String, +} + +impl LogLine { + pub fn host(text: impl Into) -> Self { + Self { source: LogSource::Host, text: text.into() } + } + + /// A line the plug-in wrote: each line break (also Unicode's separators) becomes a space, so it stays one line. + pub fn plugin(text: impl AsRef) -> Self { + let text = text.as_ref().replace(['\r', '\n', '\u{b}', '\u{c}', '\u{85}', '\u{2028}', '\u{2029}'], " "); + Self { source: LogSource::Plugin, text } + } + + /// Whether the plug-in wrote it. + pub fn by_plugin(&self) -> bool { + self.source == LogSource::Plugin + } + + /// `host: text` or `plugin: text`, as the Log tab shows and copies it. + pub fn prefixed(&self) -> String { + format!("{}: {}", self.source.name(), self.text) + } + + /// The line in `plugin.log`. + pub fn json(&self) -> Value { + serde_json::json!({"source": self.source.name(), "text": self.text}) + } +} + /// What one call returned, and what it logged (also when it failed). #[derive(Clone, Debug, PartialEq)] pub struct Outcome { pub value: Result, - pub logs: Vec, + pub logs: Vec, } struct Deadline { @@ -434,7 +486,7 @@ impl Plugin { pub(crate) fn invoke(&self, request: &Value, ctx: &mut CallContext<'_>) -> Outcome { let mut logs = Vec::new(); let value = self.invoke_inner(request, ctx, &mut logs); - Outcome { value, logs } + Outcome { value, logs: logs.iter().map(LogLine::plugin).collect() } } fn invoke_inner(&self, request: &Value, ctx: &mut CallContext<'_>, logs: &mut Vec) -> Result { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 521d73e9de..54111aa05b 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -4,7 +4,7 @@ use std::time::{Duration, Instant}; -use lcc_plugins::{Error, Limits, Manager, NoHost, Permissions, Plugin}; +use lcc_plugins::{Error, Limits, LogLine, LogSource, Manager, NoHost, Permissions, Plugin}; use serde_json::{Value, json}; /// A module implementing the ABI. `handle` is the body of `lcc_handle(ptr, len) -> i64`; @@ -388,7 +388,7 @@ fn program_start_refuses_bad_requests_and_starts_nothing() { let e = start(&mut m, &mut host, params.clone()).unwrap_err().to_string(); assert!(e.contains(needle), "{params}: {e}"); assert!(host.started.is_empty(), "{params} started something"); - let logged = m.get("test.plugin").unwrap().log.iter().any(|l| l.contains("program.start failed") && l.contains(needle)); + let logged = m.get("test.plugin").unwrap().log.iter().any(|l| l.text.contains("program.start failed") && l.text.contains(needle)); assert!(logged, "{params}: the error is in the log"); } // not installed on this system @@ -426,7 +426,7 @@ fn program_end_reads_the_run_folder_and_a_failing_hook_is_logged() { let mut call = m.program_end_call("test.plugin", "run-2", "conv", lcc_plugins::EndStatus::Cancelled, None, &dir).unwrap(); let outcome = call.run(&mut NoHost); assert!(m.end(call, Some(outcome)).is_err()); - assert!(m.get("test.plugin").unwrap().log.iter().any(|l| l.contains("program.end failed"))); + assert!(m.get("test.plugin").unwrap().log.iter().any(|l| l.text.contains("program.end failed"))); assert!(m.program_end_call("test.plugin", "run-3", "conv", lcc_plugins::EndStatus::Exited, None, &dir).is_ok(), "not left busy"); let _ = std::fs::remove_dir_all(&dir); } @@ -444,7 +444,7 @@ fn a_program_end_hook_out_of_budget_is_stopped_and_logged() { let outcome = call.run(&mut NoHost); assert!(m.end(call, Some(outcome)).is_err(), "a hook that never returns is stopped"); assert!(t.elapsed() < Duration::from_secs(10), "within its budget: {:?}", t.elapsed()); - assert!(m.get("test.plugin").unwrap().log.iter().any(|l| l.contains("program.end failed")), "and the log says so"); + assert!(m.get("test.plugin").unwrap().log.iter().any(|l| l.text.contains("program.end failed")), "and the log says so"); assert!(m.program_end_call("test.plugin", "run-2", "conv", lcc_plugins::EndStatus::Exited, None, &dir).is_ok(), "not left busy"); let _ = std::fs::remove_dir_all(&dir); } @@ -462,7 +462,7 @@ fn a_run_folder_that_cant_be_made_starts_nothing() { let e = start(&mut m, &mut host, json!({"program": "conv"})).unwrap_err().to_string(); assert!(e.contains("run folder"), "{e}"); assert!(host.started.is_empty(), "nothing started"); - assert!(m.get("test.plugin").unwrap().log.iter().any(|l| l.contains("program.start failed"))); + assert!(m.get("test.plugin").unwrap().log.iter().any(|l| l.text.contains("program.start failed"))); // the failed start held nothing: with a usable folder it starts m.set_runs_root(Some(base.join("runs"))); start(&mut m, &mut host, json!({"program": "conv"})).unwrap(); @@ -486,9 +486,9 @@ fn a_plugin_failing_in_a_loop_cant_flood_its_log() { m.install_bytes(&module(PROGRAMS, 1, &handle, "", &req), None, false).unwrap(); let _ = m.run_command("test.plugin", "go", &json!({}), &[], &mut NoHost); let log = &m.get("test.plugin").unwrap().log; - let failures = log.iter().filter(|l| l.contains("program.start failed")).count(); + let failures = log.iter().filter(|l| l.text.contains("program.start failed")).count(); assert!((1..50).contains(&failures), "a few failures are logged, not 200: {failures}"); - assert!(log.iter().any(|l| l.contains("left out")), "and the log says the rest were left out"); + assert!(log.iter().any(|l| l.text.contains("left out")), "and the log says the rest were left out"); } #[test] @@ -507,7 +507,7 @@ fn an_update_from_a_command_keeps_programs_only_for_the_same_code() { m.install_bytes(&version("(nop) (i64.const 0)"), None, false).unwrap(); assert_eq!(granted(&m), 0, "different code keeps no programs"); let log = &m.get("test.plugin").unwrap().log; - assert_eq!(log.iter().filter(|l| l.contains("code is different")).count(), 2, "one line per program: {log:?}"); + assert_eq!(log.iter().filter(|l| l.text.contains("code is different")).count(), 2, "one line per program: {log:?}"); assert_eq!(m.get("test.plugin").unwrap().effective().catalog, kept.catalog, "the other permissions stay"); // and a command can't name them again for other code let mut m = Manager::in_memory(); @@ -525,7 +525,7 @@ fn an_update_from_a_command_keeps_programs_only_for_the_same_code() { fn an_update_keeps_a_narrowed_program_grant_and_unticks_a_widened_one() { let version = |manifest: &str| module(manifest, 1, "(i64.const 0)", "", ""); let granted = |m: &Manager| m.get("test.plugin").unwrap().effective().programs.iter().map(|p| p.id.clone()).collect::>(); - let widened_logged = |m: &Manager| m.get("test.plugin").unwrap().log.iter().filter(|l| l.contains("more places than you allowed")).count(); + let widened_logged = |m: &Manager| m.get("test.plugin").unwrap().log.iter().filter(|l| l.text.contains("more places than you allowed")).count(); let mut m = Manager::in_memory(); m.install_bytes_by_user(&version(PROGRAMS), Some(programs_grant(&["conv", "other"])), false).unwrap(); assert_eq!(granted(&m), ["conv", "other"]); @@ -735,3 +735,53 @@ fn virtual_copy_requests_are_checked_before_the_host_sees_them() { assert!(r.unwrap_err().to_string().contains("virtualCopy")); assert!(seen.is_empty()); } + +/// Logs `text` (a WAT string literal) with `host.log`, then replies `{"ok":1}`. +fn logging(text: &str) -> Vec { + let extra = format!(r#"(data (i32.const 12000) "{{\"ok\":1}}") (data (i32.const 12100) "{text}")"#); + let len = text.replace(r"\0a", "\n").len(); + let handle = format!("(call $log (i32.const 12100) (i32.const {len})) (i64.or (i64.shl (i64.const 8) (i64.const 32)) (i64.const 12000))"); + module(MANIFEST, 1, &handle, &extra, "") +} + +#[test] +fn the_log_says_who_wrote_each_line() { + let mut m = Manager::in_memory(); + m.install_bytes_by_user(&logging("hello"), Some(all()), false).unwrap(); + m.run_command("test.plugin", "go", &json!({}), &[], &mut NoHost).unwrap(); + let log = &m.get("test.plugin").unwrap().log; + let by = |source| log.iter().filter(|l| l.source == source).map(|l| l.text.as_str()).collect::>(); + assert_eq!(by(LogSource::Plugin), ["hello"], "the plug-in's own line: {log:?}"); + assert!(by(LogSource::Host).contains(&"installed version 1.0.0"), "the manager's note: {log:?}"); + assert_eq!(log.iter().last().map(LogLine::prefixed).as_deref(), Some("plugin: hello"), "copied text keeps the source"); +} + +#[test] +fn a_plugin_cant_pass_a_line_off_as_the_hosts() { + let mut m = Manager::in_memory(); + // `host: enabled`, a line break, then `host: revoked everything` + m.install_bytes_by_user(&logging(r"host: enabled\0ahost: revoked everything"), Some(all()), false).unwrap(); + m.run_command("test.plugin", "go", &json!({}), &[], &mut NoHost).unwrap(); + let mine: Vec<_> = m.get("test.plugin").unwrap().log.iter().filter(|l| l.source == LogSource::Plugin).collect(); + assert_eq!(mine.len(), 1, "one line, whatever its breaks: {mine:?}"); + assert_eq!(mine[0].text, "host: enabled host: revoked everything"); + assert_eq!(mine[0].prefixed(), "plugin: host: enabled host: revoked everything", "it still reads as the plug-in's"); + assert_eq!(LogLine::plugin("a\u{2028}b\u{85}c\rd").text, "a b c d", "Unicode's separators too"); +} + +#[test] +fn both_sources_share_one_capped_log() { + let mut m = Manager::in_memory(); + m.install_bytes_by_user(&logging("again"), Some(all()), false).unwrap(); + for _ in 0..300 { + m.run_command("test.plugin", "go", &json!({}), &[], &mut NoHost).unwrap(); + m.note("test.plugin", "a note"); + } + let log = &m.get("test.plugin").unwrap().log; + assert_eq!(log.len(), 500, "the cap holds with both sources in the list"); + assert_eq!( + (log.iter().filter(|l| l.source == LogSource::Host).count(), log.iter().filter(|l| l.source == LogSource::Plugin).count()), + (250, 250) + ); + assert!(!m.note("nobody.here", "x"), "a plug-in that isn't installed takes no note"); +} diff --git a/crates/plugins/tests/compat.rs b/crates/plugins/tests/compat.rs index 2a928c3eb8..352a8d474f 100644 --- a/crates/plugins/tests/compat.rs +++ b/crates/plugins/tests/compat.rs @@ -188,7 +188,7 @@ fn a_module_already_installed_without_a_valid_version_still_loads() { for id in ["t.old", "t.none"] { let p = m.get(id).unwrap_or_else(|| panic!("{id} loads: {:?}", m.failed)); assert!(p.enabled); - assert!(p.log.iter().any(|l| l.contains("without a valid version")), "{id}: {:?}", p.log); + assert!(p.log.iter().any(|l| l.text.contains("without a valid version")), "{id}: {:?}", p.log); } // a new version replaces it without a downgrade check (there's nothing to compare with) m.install_bytes(&module(&json!({"id": "t.old", "name": "Old", "version": "0.1.0"})), None, false).unwrap(); @@ -215,7 +215,7 @@ fn a_downgrade_needs_confirming() { let p = m.install_bytes(&older, None, true).unwrap(); assert_eq!(p.plugin.manifest().version, "1.3.0"); assert_eq!(p.effective(), Permissions { catalog: true, ..Default::default() }, "grant kept, cut back to the request"); - assert!(p.log.iter().any(|l| l == "downgraded from 1.4.0 to 1.3.0"), "{:?}", p.log); + assert!(p.log.iter().any(|l| l.text == "downgraded from 1.4.0 to 1.3.0"), "{:?}", p.log); // the same version again is a repair; a higher one an update m.install_bytes(&older, None, false).unwrap(); @@ -451,7 +451,9 @@ fn unknown_manifest_fields_are_named_and_the_install_goes_ahead() { let mut m = Manager::in_memory(); let p = m.install_bytes(&module(&manifest), None, false).unwrap(); assert!( - p.log.iter().any(|l| l.starts_with("unknown manifest fields: ") && l.contains("descripton") && l.contains("commands[0].lable")), + p.log + .iter() + .any(|l| l.text.starts_with("unknown manifest fields: ") && l.text.contains("descripton") && l.text.contains("commands[0].lable")), "{:?}", p.log ); diff --git a/crates/plugins/tests/example.rs b/crates/plugins/tests/example.rs index 609217d200..734015806f 100644 --- a/crates/plugins/tests/example.rs +++ b/crates/plugins/tests/example.rs @@ -86,7 +86,7 @@ fn example_plugin_end_to_end() { assert_eq!(host.calls, vec!["catalog.stats"]); let r = m.run_command(id, "count", &json!({"label": "All"}), &[], &mut host).unwrap(); assert_eq!(r["message"], "All: 42"); - assert!(m.get(id).unwrap().log.iter().any(|l| l.contains("counted photos for All")), "{:?}", m.get(id).unwrap().log); + assert!(m.get(id).unwrap().log.iter().any(|l| l.text.contains("counted photos for All")), "{:?}", m.get(id).unwrap().log); // own namespace let r = m.run_command(id, "mark", &json!({}), &["p1".into(), "p2".into()], &mut host).unwrap(); @@ -424,7 +424,7 @@ fn program_tools_example_starts_its_program_and_reads_what_it_made() { let mut call = m.program_end_call(id, again.run(), "converter", lcc_plugins::EndStatus::Exited, Some(2), again.dir.path()).unwrap(); let outcome = call.run(&mut host); assert_eq!(m.end(call, Some(outcome)).unwrap()["converted"], json!([]), "a failed run converts nothing"); - assert!(m.get(id).unwrap().log.iter().any(|l| l.contains("exit code 2")), "the plug-in sees the exit code"); + assert!(m.get(id).unwrap().log.iter().any(|l| l.text.contains("exit code 2")), "the plug-in sees the exit code"); again.dir.remove(); let _ = std::fs::remove_dir_all(&dir); } @@ -712,7 +712,7 @@ fn import_tools_example_end_to_end() { m.set_settings(id, &json!({"transcodeExt": "jxl", "skipExt": ".CR2"}), &mut host).unwrap(); assert_eq!(ask(&mut m, "/x/IMG_0001.CR2", 100, &mut host), json!({"skip": true})); assert_eq!(ask(&mut m, "/x/IMG_0002.NEF", 200, &mut host), json!({"replace": "/x/IMG_0002.jxl"})); - assert!(m.get(id).unwrap().log.iter().any(|l| l.contains("IMG_0002.NEF"))); + assert!(m.get(id).unwrap().log.iter().any(|l| l.text.contains("IMG_0002.NEF"))); // a bad rule (not an extension) is ignored; junk replies are the host's to refuse m.set_settings(id, &json!({"transcodeExt": "not an ext!", "skipExt": ""}), &mut host).unwrap(); assert_eq!(ask(&mut m, "/x/IMG_0003.CR2", 0, &mut host), json!({})); diff --git a/crates/plugins/tests/id_clash.rs b/crates/plugins/tests/id_clash.rs new file mode 100644 index 0000000000..b182419f64 --- /dev/null +++ b/crates/plugins/tests/id_clash.rs @@ -0,0 +1,67 @@ +//! Installing a plug-in never writes over a module that holds another plug-in's id: a module copied +//! into the folder under the name `.wasm` stays as it was, and the install says which file. + +use std::path::PathBuf; + +use lcc_plugins::{Error, Manager}; +use serde_json::{Value, json}; + +/// A module whose manifest is `manifest`; it answers every call with `{}`. +fn module(manifest: &Value) -> Vec { + let manifest = manifest.to_string(); + let esc = |s: &str| s.bytes().map(|b| format!("\\{b:02x}")).collect::(); + let src = format!( + r#"(module + (memory (export "memory") 2) + (data (i32.const 16) "{m}") + (data (i32.const 32768) "{{}}") + (func (export "lcc_abi_version") (result i32) (i32.const 1)) + (func (export "lcc_manifest") (result i64) (i64.or (i64.shl (i64.const {ml}) (i64.const 32)) (i64.const 16))) + (func (export "lcc_alloc") (param i32) (result i32) (i32.const 65536)) + (func (export "lcc_handle") (param i32 i32) (result i64) (i64.or (i64.shl (i64.const 2) (i64.const 32)) (i64.const 32768))))"#, + m = esc(&manifest), + ml = manifest.len() + ); + wat::parse_str(&src).unwrap() +} + +fn plugin(id: &str, version: &str) -> Vec { + module(&json!({"id": id, "name": id, "version": version, "commands": [{"id": "go", "label": "Go"}]})) +} + +fn folder(name: &str) -> PathBuf { + let d = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("plugin-id-clash-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +#[test] +fn an_install_never_replaces_a_module_with_another_id() { + let dir = folder("other"); + let other = plugin("test.other", "1.0.0"); + // copied in by hand under the name the new plug-in would be written to + std::fs::write(dir.join("test.mine.wasm"), &other).unwrap(); + let mut m = Manager::open(&dir).unwrap(); + assert!(m.get("test.other").is_some(), "the copied-in module loads under its own id"); + + let e = m.install_bytes(&plugin("test.mine", "1.0.0"), None, false).unwrap_err(); + let text = e.to_string(); + assert!(matches!(e, Error::Io(_)), "{text}"); + assert!(text.contains("test.mine.wasm") && text.contains("test.other"), "names the file and the other id: {text}"); + assert_eq!(std::fs::read(dir.join("test.mine.wasm")).unwrap(), other, "the other module is left as it was"); + assert!(m.get("test.other").is_some() && m.get("test.mine").is_none()); +} + +#[test] +fn the_same_id_in_its_own_file_still_installs_and_updates() { + let dir = folder("same"); + let mut m = Manager::open(&dir).unwrap(); + m.install_bytes(&plugin("test.mine", "1.0.0"), None, false).unwrap(); + m.install_bytes(&plugin("test.mine", "1.1.0"), None, false).unwrap(); + assert_eq!(m.get("test.mine").unwrap().plugin.manifest().version, "1.1.0"); + // a file that isn't a module is replaced, as before: it is no one's + std::fs::write(dir.join("test.junk.wasm"), b"not a module").unwrap(); + m.install_bytes(&plugin("test.junk", "1.0.0"), None, false).unwrap(); + assert!(m.get("test.junk").is_some()); +} diff --git a/crates/plugins/tests/jobs.rs b/crates/plugins/tests/jobs.rs index ab09bce75c..541ee51151 100644 --- a/crates/plugins/tests/jobs.rs +++ b/crates/plugins/tests/jobs.rs @@ -250,7 +250,7 @@ fn a_cancel_stops_the_job_between_calls() { let e = run_job(&mut m, &mut NoHost, &rep).unwrap_err(); assert_eq!(e, Error::Cancelled); assert_eq!(rep.items.get(), 1, "no call after the cancel, though the reply asked to continue"); - assert!(m.get("test.job").unwrap().log.iter().any(|l| l == "command cancelled"), "{:?}", m.get("test.job").unwrap().log); + assert!(m.get("test.job").unwrap().log.iter().any(|l| l.text == "command cancelled"), "{:?}", m.get("test.job").unwrap().log); } #[test] @@ -273,13 +273,22 @@ fn after_a_cancel_only_job_cancelled_answers() { } #[test] -fn a_job_reads_the_catalog_but_never_writes_it() { +fn a_job_reads_the_catalog_hands_its_two_held_writes_to_its_host_and_refuses_the_other_writes() { let mut m = installed(&sequence(true, &[r#"{"method":"catalog.stats","params":{}}"#], None), Limits::default()); let mut host = Host::default(); assert_eq!(run_job(&mut m, &mut host, &Rec::default()).unwrap(), json!({"photos": 3})); + // `metadata.setStandard` and `library.add` reach the host, which holds them until the job ends for req in [ r#"{"method":"metadata.setStandard","params":{"ids":["1"],"title":"x"}}"#, r#"{"method":"library.add","params":{"path":"/x/a.tif","from":"1"}}"#, + ] { + let mut m = installed(&sequence(true, &[req], None), Limits::default()); + let mut host = Host::default(); + run_job(&mut m, &mut host, &Rec::default()).unwrap_or_else(|e| panic!("{req}: {e}")); + assert_eq!(host.calls, 1, "{req}: reached the host"); + } + for req in [ + r#"{"method":"library.remove","params":{"ids":["1"]}}"#, r#"{"method":"develop.setCrop","params":{"photo":"1","rect":[0.1,0.1,0.9,0.9]}}"#, r#"{"method":"photo.virtualCopy","params":{"photo":"1"}}"#, r#"{"method":"program.start","params":{"program":"p"}}"#, diff --git a/crates/plugins/tests/rollback.rs b/crates/plugins/tests/rollback.rs index d36635aa52..99a4c9cc9c 100644 --- a/crates/plugins/tests/rollback.rs +++ b/crates/plugins/tests/rollback.rs @@ -96,7 +96,7 @@ fn an_update_keeps_the_version_it_replaces_and_going_back_restores_it() { let back = m.rollback(ID).unwrap(); assert_eq!(back.plugin.manifest().version, "1.0.0"); - assert_eq!(back.log.back().map(String::as_str), Some("rolled back from 1.1.0 to 1.0.0"), "{:?}", back.log); + assert_eq!(back.log.back().map(|l| l.text.as_str()), Some("rolled back from 1.1.0 to 1.0.0"), "{:?}", back.log); assert_eq!(back.effective(), Permissions { catalog: true, ..Default::default() }, "the grant as it was, never more"); assert_eq!(values(&mut m), json!({"a": "A", "b": "B"}), "its settings as they were before the update"); let saved: Value = serde_json::from_slice(&std::fs::read(dir.join("settings").join(format!("{ID}.json"))).unwrap()).unwrap(); @@ -163,7 +163,7 @@ fn going_back_keeps_programs_only_from_the_plugins_page() { assert_eq!(programs_of(&m), 1, "from the page: kept"); } else { assert_eq!(programs_of(&m), 0, "from a command: dropped"); - assert!(m.get(ID).unwrap().log.iter().any(|l| l.contains("code is different")), "and the log says why"); + assert!(m.get(ID).unwrap().log.iter().any(|l| l.text.contains("code is different")), "and the log says why"); } assert!(m.get(ID).unwrap().effective().catalog, "the other permissions stay"); } diff --git a/crates/plugins/tests/settings.rs b/crates/plugins/tests/settings.rs index 6979f4098b..ed8d2d3b8c 100644 --- a/crates/plugins/tests/settings.rs +++ b/crates/plugins/tests/settings.rs @@ -187,7 +187,11 @@ fn a_damaged_settings_file_gives_defaults_and_a_log_line() { std::fs::write(dir.join("settings").join(format!("{id}.json")), b"\xff\xfe not json").unwrap(); let mut m = Manager::open(&dir).unwrap(); assert_eq!(values(&mut m, id), json!({"b": true})); - assert!(m.get(id).unwrap().log.iter().any(|l| l.contains("settings") && l.contains("using the defaults")), "{:?}", m.get(id).unwrap().log); + assert!( + m.get(id).unwrap().log.iter().any(|l| l.text.contains("settings") && l.text.contains("using the defaults")), + "{:?}", + m.get(id).unwrap().log + ); m.set_settings(id, &json!({"b": false}), &mut NoHost).unwrap(); assert!(dir.join("settings").join(format!("{id}.json.bad")).exists(), "the damaged file is kept aside"); } @@ -331,7 +335,7 @@ fn failing_prepare_steps_never_run_the_command_on_a_bad_answer() { panic!("{what}: the declared dialog") }; assert_eq!(serde_json::to_value(&fields[0]).unwrap()["options"], json!(["2.0"]), "{what}"); - assert!(m.get(id).unwrap().log.iter().any(|l| l.contains("prepare")), "{what}: logged: {e}"); + assert!(m.get(id).unwrap().log.iter().any(|l| l.text.contains("prepare")), "{what}: logged: {e}"); assert_eq!( ran_with(m.run_command(id, "go", &json!({"version": "2.0"}), &sel, &mut NoHost)), json!({"version": "2.0", "stack": false}), diff --git a/crates/plugins/tests/signing.rs b/crates/plugins/tests/signing.rs index b1d908dfcc..6cf5f47877 100644 --- a/crates/plugins/tests/signing.rs +++ b/crates/plugins/tests/signing.rs @@ -164,7 +164,7 @@ fn the_first_signed_install_pins_its_key_and_the_same_signer_keeps_it() { let key = Signer::from_base64(plugins_json(&dir)["plugins"][ID]["signer"].as_str().expect("kept in plugins.json")).unwrap(); assert_eq!(key.fingerprint(), fp(1)); assert_eq!(m.get(ID).unwrap().info()["signer"], fp(1), "plugin.list shows it"); - assert!(m.get(ID).unwrap().log.iter().any(|l| l.contains(&fp(1))), "the log says so"); + assert!(m.get(ID).unwrap().log.iter().any(|l| l.text.contains(&fp(1))), "the log says so"); // an update and a rollback by the same signer keep it, without asking install(&mut m, &signed("1.1.0", 1), &SignerAnswer::None).unwrap(); assert_eq!(pinned(&m), Some(fp(1))); @@ -206,7 +206,7 @@ fn another_signer_or_an_unsigned_file_installs_only_on_the_users_yes() { let typed = fp(2).replace(' ', "").to_uppercase(); install(&mut m, &signed("2.1.0", 2), &SignerAnswer::Signer(typed)).unwrap(); assert_eq!(pinned(&m), Some(fp(2)), "the new signer is pinned"); - assert!(m.get(ID).unwrap().log.iter().any(|l| l.contains("signer changed") && l.contains(&fp(2)))); + assert!(m.get(ID).unwrap().log.iter().any(|l| l.text.contains("signer changed") && l.text.contains(&fp(2)))); // an unsigned file over a signed one let e = install(&mut m, &stamped("3.0.0"), &SignerAnswer::None).unwrap_err().to_string(); assert!(e.contains("isn't signed") && e.contains("acceptUnsigned"), "{e}"); @@ -338,7 +338,7 @@ fn going_back_checks_the_kept_file_against_the_signer_recorded_with_it() { assert!(matches!(m.rollback_as(ID, false, &SignerAnswer::Signer(fp(3))), Err(Error::Signer(_))), "a yes to another key"); m.rollback_as(ID, false, &SignerAnswer::Signer(fp(2))).unwrap(); assert_eq!((m.get(ID).unwrap().plugin.manifest().version.as_str(), pinned(&m)), ("1.0.0", Some(fp(2)))); - assert!(m.get(ID).unwrap().log.iter().any(|l| l.contains("went back") && l.contains(&fp(2))), "{:?}", m.get(ID).unwrap().log); + assert!(m.get(ID).unwrap().log.iter().any(|l| l.text.contains("went back") && l.text.contains(&fp(2))), "{:?}", m.get(ID).unwrap().log); // swapped for an unsigned file let (d, mut m) = setup("rollback-unsigned"); diff --git a/crates/plugins/tests/updates.rs b/crates/plugins/tests/updates.rs index 33d8578807..fd360b4c66 100644 --- a/crates/plugins/tests/updates.rs +++ b/crates/plugins/tests/updates.rs @@ -225,7 +225,7 @@ fn a_check_stands_for_a_day_and_is_kept_across_a_restart() { run_checks(&mut m, Some(ID), None, now + DAY); let info = updates(&m); assert!(info["error"].as_str().unwrap().contains("isn't JSON") && info["offer"].is_null(), "{info}"); - assert!(m.get(ID).unwrap().log.iter().any(|l| l.starts_with("update check failed"))); + assert!(m.get(ID).unwrap().log.iter().any(|l| l.text.starts_with("update check failed"))); } /// AC-6, AC-4: an update installs through the install path once its SHA-256, manifest and signer @@ -366,7 +366,8 @@ fn each_check_that_runs_logs_one_line() { m.set_fetcher(served.clone()); install(&mut m, &signed("1.0.0", 1)); m.set_update_check(ID, true).unwrap(); - let checks = |m: &Manager| m.get(ID).unwrap().log.iter().filter(|l| l.starts_with("update check")).cloned().collect::>(); + let checks = + |m: &Manager| m.get(ID).unwrap().log.iter().filter(|l| l.text.starts_with("update check")).map(|l| l.text.clone()).collect::>(); let before = checks(&m); let same = signed("1.0.0", 1); diff --git a/crates/publish/src/hard_drive.rs b/crates/publish/src/hard_drive.rs index c239d7521e..1d7b0d041b 100644 --- a/crates/publish/src/hard_drive.rs +++ b/crates/publish/src/hard_drive.rs @@ -98,9 +98,17 @@ impl HardDrive { /// A file of the wanted name holding exactly these bytes is taken as this photo's too: a run stopped before it /// recorded what it sent (a crash, a power cut, the app closed) left it, and the next run would otherwise send the /// photo again as `a-2.jpg` beside it (issue #1376). Its sidecars go with it. - fn free_name(&self, wanted: &str, up: &Upload<'_>) -> String { + /// + /// `Err` when every numbered name is taken ([`lcc_catalog::safe_file::NUMBERED_NAME_TRIES`]): the photo is not + /// published under a name another photo's file has (FX-235). + fn free_name(&self, wanted: &str, up: &Upload<'_>) -> Result { + self.free_name_below(wanted, up, lcc_catalog::safe_file::NUMBERED_NAME_TRIES) + } + + /// [`Self::free_name`] trying the numbers below `below` only. + pub(crate) fn free_name_below(&self, wanted: &str, up: &Upload<'_>, below: u32) -> Result { if up.previous.is_none() && self.holds(wanted, up.bytes) { - return wanted.to_string(); + return Ok(wanted.to_string()); } // the previous publication's file and the sidecars recorded with it. One with no record (published before // sidecars were recorded) keeps the old rule, its sidecar named like it: replacing it is checked against the @@ -114,19 +122,11 @@ impl HardDrive { let taken = |n: &str| !own(n) && self.folder.join(n).exists(); let free = |n: &str| !taken(n) && !up.sidecars.iter().any(|(ext, _)| taken(&with_ext(n, ext))); if free(wanted) { - return wanted.to_string(); + return Ok(wanted.to_string()); } - let (stem, ext) = match wanted.rsplit_once('.') { - Some((s, e)) if !s.is_empty() => (s, Some(e)), - _ => (wanted, None), - }; - (2u32..) - .map(|i| match ext { - Some(e) => format!("{stem}-{i}.{e}"), - None => format!("{stem}-{i}"), - }) - .find(|n| free(n)) - .unwrap_or_else(|| wanted.to_string()) + let (stem, ext) = lcc_catalog::safe_file::split_extension(wanted); + lcc_catalog::safe_file::first_free_numbered_below(stem, ext, 2, below, free) + .ok_or_else(|| PublishError::Io(format!("{wanted}: no free file name in {}", self.folder.display()))) } } @@ -167,7 +167,7 @@ impl PublishService for HardDrive { fn publish(&mut self, up: &Upload<'_>) -> Result { let wanted = safe_name(up.file_name).ok_or_else(|| PublishError::Config(format!("`{}` can't be a file name", up.file_name)))?; std::fs::create_dir_all(&self.folder).map_err(|e| PublishError::Io(format!("{}: {e}", self.folder.display())))?; - let name = self.free_name(&wanted, up); + let name = self.free_name(&wanted, up)?; let path = self.folder.join(&name); let sidecars: Vec = up.sidecars.iter().map(|(ext, _)| with_ext(&name, ext)).collect(); // never over an original or its sidecar, whatever name the folder left free diff --git a/crates/publish/src/tests.rs b/crates/publish/src/tests.rs index c11f7de806..9fbb88f75a 100644 --- a/crates/publish/src/tests.rs +++ b/crates/publish/src/tests.rs @@ -261,3 +261,31 @@ fn hard_drive_adopts_a_file_an_interrupted_run_left() { assert_eq!(other.remote_id, "a-2.jpg"); assert_eq!(std::fs::read(d.join("Web/a.jpg")).unwrap(), b"one"); } + +#[test] +fn the_catalogs_publish_service_name_is_ours() { + assert_eq!(lcc_catalog::remote::PUBLISH_SERVICE, crate::SERVICE); +} + +/// A name no other photo's file has: the first free number, and an error rather than another photo's name when every +/// number below the bound is taken (FX-235). +#[test] +fn hard_drive_free_name_steps_over_taken_numbers_and_fails_when_none_is_left() { + let d = tmp("hd-free-name"); + let (s, coll) = svc(&d); + let hd = HardDrive::open(&s, &coll).unwrap(); + let up = Upload { photo: PhotoId(9), file_name: "a.jpg", bytes: b"new", sidecars: &[], previous: None }; + let web = d.join("Web"); + std::fs::create_dir_all(&web).unwrap(); + let taken = |n: &str| std::fs::write(web.join(n), b"other photo").unwrap(); + assert_eq!(hd.free_name_below("a.jpg", &up, 6).unwrap(), "a.jpg"); + taken("a.jpg"); + assert_eq!(hd.free_name_below("a.jpg", &up, 6).unwrap(), "a-2.jpg"); + taken("a-2.jpg"); + taken("a-3.jpg"); + taken("a-4.jpg"); + assert_eq!(hd.free_name_below("a.jpg", &up, 6).unwrap(), "a-5.jpg", "below the bound: a number is left"); + taken("a-5.jpg"); + assert!(hd.free_name_below("a.jpg", &up, 6).unwrap_err().to_string().contains("no free file name"), "at the bound"); + assert!(hd.free_name_below("a.jpg", &up, 2).is_err(), "no number to try"); +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 4a1066fe1d..0292745e5f 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -244,6 +244,33 @@ pub fn probe(what: &str) -> bool { on } +/// Whether a test that starts the device-sync service (a TCP listener on every interface and the mDNS +/// multicast group) should run: false, with a `System` skip, when `_SKIP_LAN_TESTS` is set to a +/// non-empty value other than `0` (macOS asks "accept incoming network connections?" for each rebuilt test +/// binary, and the run waits for the answer). `discovery` is for a test that needs devices to find each +/// other over mDNS: that also skips on the macOS CI runner, where discovery times out (checked in person on +/// real Macs, see "Checked in person, not on CI" in `docs/ci.md`). Put it first in every such test. +#[track_caller] +pub fn lan_tests(discovery: bool) -> bool { + let var = lcc_brand::env("SKIP_LAN_TESTS"); + let mac_ci = cfg!(target_os = "macos") && std::env::var_os("CI").is_some(); + let Some(why) = lan_skip_reason(var.as_deref(), discovery, mac_ci, &lcc_brand::env_var("SKIP_LAN_TESTS")) else { return true }; + let at = std::panic::Location::caller(); + record(Need::System, &why, at.file(), at.line()); + false +} + +/// Why [`lan_tests`] skips, if it does: `var` is the opt-out variable's value, `name` its full name. +fn lan_skip_reason(var: Option<&str>, discovery: bool, mac_ci: bool, name: &str) -> Option { + if var.is_some_and(|v| !v.is_empty() && v != "0") { + Some(format!("opens sockets on every interface, unset {name} to run it")) + } else if discovery && mac_ci { + Some("LAN discovery on the macOS CI runner (tested in person)".to_owned()) + } else { + None + } +} + /// What [`skip!`] calls: print the note and append it to the skip log, if one is set. Never fails /// the test: a log that can't be written loses the entry, not the run. pub fn record(need: Need, reason: &str, file: &str, line: u32) { @@ -362,6 +389,26 @@ pub fn tiff16(w: u32, h: u32, spp: u16, software: &str, extra_samples: Option Result { Ok(status()) } -/// A file name in `dir` for `name` that doesn't overwrite anything. -fn free_name(dir: &Path, name: &str) -> PathBuf { +/// A file name in `dir` for `name` that doesn't overwrite anything: `name`, or the first of `a-1.jpg`, `a-2.jpg`, … +/// that is free. An `Err` when they are all taken, never a taken name (the download renames over its target) (FX-235). +/// +/// (Numbering as the other places do, `-N` before the extension and 1 000 000 tries, but not through +/// `lcc_catalog::safe_file`: this crate, below the catalog, has no dependency on it. It starts at `-1`, where they +/// start at `-2`; kept, so a download is named as it was.) +fn free_name(dir: &Path, name: &str) -> Result { + free_name_below(dir, name, FREE_NAME_TRIES) +} + +/// How many numbered names [`free_name`] tries: `a-1` … `a-999999`. +const FREE_NAME_TRIES: u32 = 1_000_000; + +/// [`free_name`] trying the numbers below `below` only. +fn free_name_below(dir: &Path, name: &str, below: u32) -> Result { let clean: String = name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '\0') || c.is_control() { '_' } else { c }).collect(); let clean = clean.trim().trim_start_matches('.').to_string(); let clean = if clean.is_empty() { "shot".to_string() } else { clean }; let p = dir.join(&clean); if !p.exists() { - return p; + return Ok(p); } let (stem, ext) = match clean.rsplit_once('.') { Some((s, e)) => (s.to_string(), format!(".{e}")), None => (clean.clone(), String::new()), }; - (1..10_000).map(|i| dir.join(format!("{stem}-{i}{ext}"))).find(|p| !p.exists()).unwrap_or_else(|| dir.join(format!("{stem}-x{ext}"))) + (1..below) + .map(|i| dir.join(format!("{stem}-{i}{ext}"))) + .find(|p| !p.exists()) + .ok_or_else(|| PtpError::Io(format!("{}: no free file name for {clean}", dir.display()))) } /// Write `bytes` to `tmp`, flush it to disk, rename it to `path` and flush the folder entry. @@ -189,7 +205,7 @@ fn download_into(l: &mut Link, handles: &[u32], dir: &Path) -> Result