From abb70f631c595e2c79a8e611052abf7a97643662 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 27 Oct 2026 03:26:44 -0500 Subject: [PATCH 01/16] Issue #3114: Lightroom import archive works on volumes without hard links The recovery archive was published with fs::hard_link and no fallback, so a library on exFAT/FAT (or an SMB share without hard links) failed every Lightroom import with "invalid parameters ...: cannot atomically publish archive: Operation not supported". - safe_file::publish_new is public; the archive uses it (hard link, else an exclusive create + rename over our own placeholder), so it still never replaces an existing archive. Its error names the archive path. A doc(hidden) thread-local hook, without_hard_links(), forces the fallback in tests. - stage_archive makes an archive failure a warning naming the folder, as docs/lightroom-catalog-import.md already promised: nothing reads the archive back (re-import mapping is lightroom-index.json). - A failed index write is EngineError::Other naming the file, not BadParams. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/safe_file.rs | 31 ++++++++++-- crates/engine/src/lightroom_archive.rs | 53 +++++++++++++++++--- crates/engine/src/lightroom_catalog/tests.rs | 51 +++++++++++++++++++ crates/engine/src/lightroom_job.rs | 45 +++++++++++++++-- docs/lightroom-catalog-import.md | 5 +- docs/whats-new.md | 10 +++- 6 files changed, 179 insertions(+), 16 deletions(-) diff --git a/crates/catalog/src/safe_file.rs b/crates/catalog/src/safe_file.rs index 2ed0acb5e19..594b5476675 100644 --- a/crates/catalog/src/safe_file.rs +++ b/crates/catalog/src/safe_file.rs @@ -22,6 +22,8 @@ //! and sync, plus a read-back check, and the file then appears under its final name **without //! replacing anything** (a hard link, which fails on a taken name; where the volume has no hard //! links, an exclusive create that claims the name, then a rename over that placeholder). +//! [`publish_new`] is that last step on its own, for a writer with its own temp file (the +//! Lightroom recovery archive). //! - [`same_file`] tells whether two paths name the same file on disk (device + inode on Unix, //! volume serial number + file index on Windows, //! resolved paths elsewhere), for "is this target an original?" checks. @@ -35,6 +37,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; thread_local! { static FAIL_AFTER: Cell> = const { Cell::new(None) }; static SYNCS: Cell = const { Cell::new(0) }; + static NO_HARD_LINKS: Cell = const { Cell::new(false) }; } /// How many file and folder syncs this module made **on the calling thread** (for tests: a @@ -68,6 +71,25 @@ impl Drop for FaultGuard { } } +/// Fault injection for tests (in any crate): while the returned guard lives, [`publish_new`] +/// **on the calling thread** acts as on a volume without hard links (FAT/exFAT, some shares), so +/// it takes the exclusive-create + rename fallback. Product code never calls it. +#[doc(hidden)] +pub fn without_hard_links() -> NoHardLinksGuard { + NO_HARD_LINKS.with(|c| c.set(true)); + NoHardLinksGuard(()) +} + +/// Ends a [`without_hard_links`] when dropped. +#[doc(hidden)] +pub struct NoHardLinksGuard(()); + +impl Drop for NoHardLinksGuard { + fn drop(&mut self) { + NO_HARD_LINKS.with(|c| c.set(false)); + } +} + /// Counts what is written; fails past an injected limit. struct Limited { inner: W, @@ -222,9 +244,12 @@ pub fn write_new_unique(candidates: &mut dyn Iterator, data: &[u r } -/// Give the complete temp file `tmp` the name `path`, unless that is taken. -fn publish_new(tmp: &Path, path: &Path) -> io::Result<()> { - match fs::hard_link(tmp, path) { +/// Give the complete temp file `tmp` (in the same folder) the name `path`, unless that is taken +/// (`AlreadyExists`): a hard link, or where the volume has none, [`publish_new_by_rename`]. After +/// a hard link `tmp` is a second name of the file; after the fallback it is gone. +pub fn publish_new(tmp: &Path, path: &Path) -> io::Result<()> { + let linked = if NO_HARD_LINKS.with(Cell::get) { Err(io::Error::from(io::ErrorKind::Unsupported)) } else { fs::hard_link(tmp, path) }; + match linked { Ok(()) => Ok(()), Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Err(e), // no hard links on this volume (FAT/exFAT, some shares) diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 9c9979d9701..5b5148f2ffc 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -115,8 +115,12 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result let _ = remove_managed_file(&temporary); return Err(error.to_string()); } - if let Err(error) = remove_managed_file(&temporary) { - return Err(format!("archive published but temporary cleanup failed: {error}")); + // after a hard link the temporary is a second name of the archive; after the rename fallback it is gone + match remove_managed_file(&temporary) { + Err(error) if error.kind() != io::ErrorKind::NotFound => { + return Err(format!("archive published but temporary cleanup failed: {error}")); + } + _ => {} } for (old, held) in quarantined { if let Err(error) = remove_managed_file(&held) { @@ -420,11 +424,10 @@ fn rollback_quarantine(moved: &[(PathBuf, PathBuf)]) { } } +/// Never replaces an existing archive (`AlreadyExists`), also on a volume without hard links. fn publish_new(temporary: &Path, destination: &Path) -> io::Result<()> { - match fs::hard_link(temporary, destination) { - Ok(()) => Ok(()), - Err(error) => Err(io::Error::new(error.kind(), format!("cannot atomically publish archive: {error}"))), - } + lightcraft_catalog::safe_file::publish_new(temporary, destination) + .map_err(|error| io::Error::new(error.kind(), format!("cannot publish archive {}: {error}", destination.display()))) } fn remove_managed_file(path: &Path) -> io::Result<()> { @@ -686,4 +689,42 @@ mod tests { assert_eq!(fs::read(&old).unwrap(), b"old archive"); fs::remove_dir_all(path).unwrap(); } + + /// Issue #3114: a library on exFAT (no hard links) aborted every Lightroom import here. + #[test] + fn publishes_on_a_volume_without_hard_links() { + let path = tempdir(); + let _no_links = lightcraft_catalog::safe_file::without_hard_links(); + let first = store(&path, &rich_data()).unwrap(); + assert!(fs::read(&first).unwrap().starts_with(HEADER)); + // retention and dedup still work: a new archive gets the next name, the same data reuses it + let second = store(&path, &data("other.lrcat".into())).unwrap(); + assert_ne!(first, second); + assert_eq!(store(&path, &rich_data()).unwrap(), first); + let mut names: Vec<_> = fs::read_dir(&path).unwrap().map(|entry| entry.unwrap().file_name()).collect(); + names.sort(); + assert_eq!(names, ["lightroom-import-0.lca", "lightroom-import-1.lca"], "no temporary left behind"); + fs::remove_dir_all(path).unwrap(); + } + + #[test] + fn publishing_without_hard_links_never_replaces_an_existing_archive() { + let path = tempdir(); + let existing = path.join("lightroom-import-0.lca"); + let temporary = path.join(".lightroom-import-new.tmp"); + fs::write(&existing, b"old archive").unwrap(); + fs::write(&temporary, b"new archive").unwrap(); + let _no_links = lightcraft_catalog::safe_file::without_hard_links(); + let error = publish_new(&temporary, &existing).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::AlreadyExists); + assert!(error.to_string().contains("lightroom-import-0.lca"), "{error}"); + assert_eq!(fs::read(&existing).unwrap(), b"old archive"); + assert_eq!(fs::read(&temporary).unwrap(), b"new archive", "the temporary is kept for the caller to remove"); + // a free name takes the fallback: the temporary is renamed (a hard link would leave it in place) + let fresh = path.join("lightroom-import-1.lca"); + publish_new(&temporary, &fresh).unwrap(); + assert_eq!(fs::read(&fresh).unwrap(), b"new archive"); + assert!(!temporary.exists(), "published by rename, not by a hard link"); + fs::remove_dir_all(path).unwrap(); + } } diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 654b40458cf..97bcd9c92f1 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -442,6 +442,57 @@ fn persistent_reimport_keeps_copy_and_collection_ids_and_capture_time() { std::fs::remove_dir_all(dir).unwrap(); } +/// Issue #3114: a library on exFAT (no hard links) aborted every import when saving the archive. +#[test] +fn imports_into_a_library_on_a_volume_without_hard_links() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-no-hard-links-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let source = dir.join("source.lrcat"); + std::fs::write(&source, native_catalog(&photo_tables((dir.join("offline").to_str().unwrap(), "")))).unwrap(); + let library = dir.join("library"); + let mut s = crate::Session::new(); + s.open_library(&library, false).unwrap(); + let _no_links = lightcraft_catalog::safe_file::without_hard_links(); + let report = import(&mut s, &source, false).unwrap(); + assert_eq!(report["imported"], 1); + assert_eq!(report["warnings"], json!([])); + let archive = Path::new(report["archive"].as_str().unwrap()); + assert_eq!(archive, library.join("Interop").join("lightroom-import-0.lca")); + assert!(std::fs::read(archive).unwrap().starts_with(b"LC-LRARCH")); + assert!(library.join("Interop").join("lightroom-index.json").is_file()); + s.close_library().unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// The recovery archive is best-effort: when it can't be saved (here `Interop` is a symlink, which +/// the archive refuses) the import still goes on, with a warning naming the folder. +#[cfg(unix)] +#[test] +fn an_archive_that_cannot_be_saved_warns_and_the_import_proceeds() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-archive-refused-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("elsewhere")).unwrap(); + let source = dir.join("source.lrcat"); + std::fs::write(&source, native_catalog(&photo_tables((dir.join("offline").to_str().unwrap(), "")))).unwrap(); + let library = dir.join("library"); + let mut s = crate::Session::new(); + s.open_library(&library, false).unwrap(); + let interop = library.join("Interop"); + std::os::unix::fs::symlink(dir.join("elsewhere"), &interop).unwrap(); + let report = import(&mut s, &source, false).unwrap(); + assert_eq!(report["imported"], 1); + assert_eq!(report["archive"], Value::Null); + let warnings = report["warnings"].as_array().unwrap(); + assert!( + warnings.iter().any(|w| w.as_str().unwrap().starts_with(&format!("Lightroom source archive not saved in {}", interop.display()))), + "{warnings:?}" + ); + assert!(dir.join("elsewhere").join("lightroom-index.json").is_file(), "re-import mapping is still saved"); + s.close_library().unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + // Construct a small SQLite fixture from public file-format records, never private media. fn varint(mut n: u64) -> Vec { let mut out = vec![(n & 127) as u8]; diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 762c8588df3..0f42e3b8686 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -30,12 +30,21 @@ fn cancelled() -> crate::EngineError { crate::EngineError::Cancelled(error("Lightroom import cancelled").to_string()) } +/// Save the recovery archive. It is best-effort: nothing reads it back during import, so a folder +/// it can't be written to costs the archive (with a warning naming the folder), not the import. fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result> { - let archive_path = archive_dir.map(|dir| crate::lightroom_archive::store_best_effort(dir, data).map_err(error)).transpose()?.flatten(); - if archive_dir.is_some() && archive_path.is_none() { - data.warnings.push("Lightroom source archive exceeded 32 MiB; archive skipped".into()); + let Some(dir) = archive_dir else { return Ok(None) }; + match crate::lightroom_archive::store_best_effort(dir, data) { + Ok(Some(path)) => Ok(Some(path)), + Ok(None) => { + data.warnings.push("Lightroom source archive exceeded 32 MiB; archive skipped".into()); + Ok(None) + } + Err(e) => { + data.warnings.push(format!("Lightroom source archive not saved in {}: {e}; archive skipped", dir.display())); + Ok(None) + } } - Ok(archive_path) } /// Memory identity of the library which owns a prepared completion. @@ -117,7 +126,8 @@ impl LightroomArchiveFinalization { if bytes.len() > MAX_INDEX_BYTES { return Err(error("Lightroom import index exceeds 16 MiB")); } - lightcraft_catalog::safe_file::write_atomic(&path, &bytes).map_err(|e| error(e.to_string())) + lightcraft_catalog::safe_file::write_atomic(&path, &bytes) + .map_err(|e| crate::EngineError::Other(format!("could not write the Lightroom import index {}: {e}", path.display()))) } pub fn path(&self) -> Option<&Path> { @@ -564,6 +574,31 @@ mod tests { std::fs::remove_dir_all(archive_dir).unwrap(); } + /// The archive is best-effort: a folder it can't be written to costs the archive, not the import. + #[test] + fn an_archive_that_cannot_be_written_is_a_warning_naming_its_folder() { + let dir = std::env::temp_dir().join(format!("lightcraft-lr-archive-unwritable-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let interop = dir.join("Interop"); + std::fs::write(&interop, b"a file where the folder belongs").unwrap(); + let mut data = empty_data(); + assert_eq!(stage_archive(Some(&interop), &mut data).unwrap(), None); + assert_eq!(data.warnings.len(), 1); + assert!(data.warnings[0].starts_with("Lightroom source archive not saved in "), "{}", data.warnings[0]); + assert!(data.warnings[0].contains(&*interop.to_string_lossy()), "{}", data.warnings[0]); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A failed index write is an I/O error naming the file, not "invalid parameters". + #[test] + fn an_index_write_failure_names_the_index_file() { + let path = std::env::temp_dir().join(format!("lightcraft-lr-index-missing-{}", std::process::id())).join("lightroom-index.json"); + let e = LightroomArchiveFinalization { path: Some(path.clone()), bytes: Some(b"{}".to_vec()) }.finish().unwrap_err(); + assert!(matches!(e, crate::EngineError::Other(_)), "{e:?}"); + assert!(e.to_string().starts_with(&format!("could not write the Lightroom import index {}", path.display())), "{e}"); + } + #[test] fn execute_fn_import_does_not_rewrite_source_sidecar() { let dir = std::env::temp_dir().join(format!("lightcraft-lr-job-sidecar-{}", std::process::id())); diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index cd5df6b85d2..93cafb998da 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -76,7 +76,10 @@ catalog changes; any saved recovery archives remain available. Before changing records, the importer attempts to save source image records, decoded XMP, verbatim develop settings, history, snapshots and collection content to compressed `Interop/lightroom-import-N.lca` recovery archives in the LightCraft library. Archiving is -best-effort: a size limit or write failure produces a warning and does not prevent photo import. +best-effort: a size limit or write failure produces a warning (naming the `Interop` folder) and +does not prevent photo import. On a volume without hard links (exFAT, FAT, some network shares) an +archive is published by claiming its name with an exclusive create and renaming over it, so it +still never replaces an existing archive. Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. Each archive is capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. diff --git a/docs/whats-new.md b/docs/whats-new.md index a0213da8287..a77cdf62e2b 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -5,6 +5,15 @@ ### The Edit menu groups Select Only Active Photo and Paste Settings from Previous with their kin - Select Only Active Photo now sits under Deselect All, and Paste Settings from Previous under Paste Selected Settings…, instead of both after Settings…, near the end of the Edit menu. On macOS, where Settings… lives in the application menu, the Edit menu no longer shows two separator lines in a row. +## 2026-10-26 + +### Lightroom catalogs import into libraries on exFAT drives +- Importing a Lightroom catalog into a library on an exFAT or FAT drive (or a network share without hard links) no + longer fails with "cannot atomically publish archive: Operation not supported": the recovery archive in the + library's `Interop` folder is saved another way that still never replaces an existing archive. When the archive + can't be saved at all, the import goes on and warns, naming the folder, as documented; a failed import-index write + now names the file instead of reporting "invalid parameters". + ## 2026-10-25 ### `>=` and `<=` work in the search box @@ -112,7 +121,6 @@ - Photo Grid and Square Grid now show the grid-cycle shortcut (G by default) in the View menu. The hints follow shortcut changes; clicking a menu row still selects that grid (issue #2500). - ## 2026-10-21 ### Settings window From 0c71ab7f61c73d546a1c27e933fa7c83e6284192 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 27 Oct 2026 03:59:36 -0500 Subject: [PATCH 02/16] Issue #3114: the archive warning comes first; the no-hard-links test guard nests Review follow-up: - stage_archive puts its warning first: the result window lists only the first eight, and a catalog with many unreadable records would have hidden that recovery data wasn't saved. - without_hard_links() restores the previous value when its guard drops (nested guards work) and the guard is not Send, so it can't clear another thread's flag. - publish_new_by_rename documents what its no-replacement guarantee assumes. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/safe_file.rs | 17 ++++++++++++----- crates/engine/src/lightroom_job.rs | 10 +++++++--- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/crates/catalog/src/safe_file.rs b/crates/catalog/src/safe_file.rs index 594b5476675..b73ecaf1709 100644 --- a/crates/catalog/src/safe_file.rs +++ b/crates/catalog/src/safe_file.rs @@ -76,17 +76,20 @@ impl Drop for FaultGuard { /// it takes the exclusive-create + rename fallback. Product code never calls it. #[doc(hidden)] pub fn without_hard_links() -> NoHardLinksGuard { - NO_HARD_LINKS.with(|c| c.set(true)); - NoHardLinksGuard(()) + NoHardLinksGuard { previous: NO_HARD_LINKS.with(|c| c.replace(true)), _same_thread: std::marker::PhantomData } } -/// Ends a [`without_hard_links`] when dropped. +/// Ends a [`without_hard_links`] when dropped, putting back what was set before (so nested guards +/// work). It stays on the thread whose flag it set (not `Send`). #[doc(hidden)] -pub struct NoHardLinksGuard(()); +pub struct NoHardLinksGuard { + previous: bool, + _same_thread: std::marker::PhantomData<*const ()>, +} impl Drop for NoHardLinksGuard { fn drop(&mut self) { - NO_HARD_LINKS.with(|c| c.set(false)); + NO_HARD_LINKS.with(|c| c.set(self.previous)); } } @@ -260,6 +263,10 @@ pub fn publish_new(tmp: &Path, path: &Path) -> io::Result<()> { /// Fallback of [`publish_new`]: reserve the name with an exclusive create (atomic, so a file that /// appears at the same time is never replaced), then rename the complete temp file over our own /// empty placeholder. `before_claim` runs just before the name is claimed (a test hook). +/// +/// That guarantee holds against other writers that also create names exclusively (as everything in +/// a library folder does). A process that deletes or replaces our placeholder between the claim and +/// the rename would have its file replaced, and a failed rename removes whatever then has the name. fn publish_new_by_rename(tmp: &Path, path: &Path, before_claim: &dyn Fn()) -> io::Result<()> { before_claim(); OpenOptions::new().write(true).create_new(true).open(path)?; diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 0f42e3b8686..e830def4b0a 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -32,16 +32,18 @@ fn cancelled() -> crate::EngineError { /// Save the recovery archive. It is best-effort: nothing reads it back during import, so a folder /// it can't be written to costs the archive (with a warning naming the folder), not the import. +/// That warning goes first: the result window lists only the first few, and catalog warnings +/// (one per unreadable record) can be many. fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result> { let Some(dir) = archive_dir else { return Ok(None) }; match crate::lightroom_archive::store_best_effort(dir, data) { Ok(Some(path)) => Ok(Some(path)), Ok(None) => { - data.warnings.push("Lightroom source archive exceeded 32 MiB; archive skipped".into()); + data.warnings.insert(0, "Lightroom source archive exceeded 32 MiB; archive skipped".into()); Ok(None) } Err(e) => { - data.warnings.push(format!("Lightroom source archive not saved in {}: {e}; archive skipped", dir.display())); + data.warnings.insert(0, format!("Lightroom source archive not saved in {}: {e}; archive skipped", dir.display())); Ok(None) } } @@ -583,8 +585,10 @@ mod tests { let interop = dir.join("Interop"); std::fs::write(&interop, b"a file where the folder belongs").unwrap(); let mut data = empty_data(); + // more catalog warnings than the result window lists: the archive's must still be seen + data.warnings = (0..10).map(|i| format!("record {i}: unreadable XMP")).collect(); assert_eq!(stage_archive(Some(&interop), &mut data).unwrap(), None); - assert_eq!(data.warnings.len(), 1); + assert_eq!(data.warnings.len(), 11); assert!(data.warnings[0].starts_with("Lightroom source archive not saved in "), "{}", data.warnings[0]); assert!(data.warnings[0].contains(&*interop.to_string_lossy()), "{}", data.warnings[0]); std::fs::remove_dir_all(dir).unwrap(); From d0b54346e5150b180a017fb3d4ae426653b248a9 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 27 Oct 2026 10:09:30 -0500 Subject: [PATCH 03/16] fix(lightroom): the import index refuses a linked Interop folder (#3114) The recovery archive refuses an `Interop` folder that is a symlink or a file. Before #3114 that refusal stopped the import, so the import index was never written. Now that an archive failure is only a warning, the import went on and `LightroomArchiveFinalization::finish` wrote `lightroom-index.json` through the link, outside the library, replacing any file of that name there. `finish` now checks the index folder with the archive's own check (`lightroom_archive::require_real_directory`, split out of `prepare_directory`) and fails with an error naming the folder. The photos are still imported; the desktop result shows it as the index warning. The archive-failure test now makes the archive fail with a real folder (more entries than it scans), and a new test covers the linked folder. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_archive.rs | 25 +++++++------ crates/engine/src/lightroom_catalog/tests.rs | 38 ++++++++++++++++---- crates/engine/src/lightroom_job.rs | 33 +++++++++++++++-- docs/lightroom-catalog-import.md | 6 ++-- 4 files changed, 79 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 5b5148f2ffc..97ab9894709 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -149,19 +149,18 @@ struct Managed { fn prepare_directory(directory: &Path) -> Result<(), String> { match fs::symlink_metadata(directory) { - Ok(meta) => { - if meta.file_type().is_symlink() || !meta.is_dir() { - return Err(format!("archive directory is not a real directory: {}", directory.display())); - } - } - Err(error) if error.kind() == io::ErrorKind::NotFound => { - fs::create_dir_all(directory).map_err(|e| e.to_string())?; - let meta = fs::symlink_metadata(directory).map_err(|e| e.to_string())?; - if meta.file_type().is_symlink() || !meta.is_dir() { - return Err(format!("archive directory is not a real directory: {}", directory.display())); - } - } - Err(error) => return Err(error.to_string()), + Err(error) if error.kind() == io::ErrorKind::NotFound => fs::create_dir_all(directory).map_err(|e| e.to_string())?, + _ => {} + } + require_real_directory(directory) +} + +/// Refuse `directory` when it is a symlink or not a folder, so nothing written below it lands +/// outside the library. The archive and the import index (`lightroom_job`) both check it. +pub(crate) fn require_real_directory(directory: &Path) -> Result<(), String> { + let meta = fs::symlink_metadata(directory).map_err(|e| e.to_string())?; + if meta.file_type().is_symlink() || !meta.is_dir() { + return Err(format!("{} is a link or a file, not a folder", directory.display())); } Ok(()) } diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 97bcd9c92f1..432103f5bb2 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -465,21 +465,24 @@ fn imports_into_a_library_on_a_volume_without_hard_links() { std::fs::remove_dir_all(dir).unwrap(); } -/// The recovery archive is best-effort: when it can't be saved (here `Interop` is a symlink, which -/// the archive refuses) the import still goes on, with a warning naming the folder. -#[cfg(unix)] +/// The recovery archive is best-effort: when it can't be saved (here `Interop` holds more entries +/// than the archive scans) the import still goes on, with a warning naming the folder. #[test] fn an_archive_that_cannot_be_saved_warns_and_the_import_proceeds() { let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-archive-refused-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(dir.join("elsewhere")).unwrap(); + std::fs::create_dir_all(&dir).unwrap(); let source = dir.join("source.lrcat"); std::fs::write(&source, native_catalog(&photo_tables((dir.join("offline").to_str().unwrap(), "")))).unwrap(); let library = dir.join("library"); let mut s = crate::Session::new(); s.open_library(&library, false).unwrap(); let interop = library.join("Interop"); - std::os::unix::fs::symlink(dir.join("elsewhere"), &interop).unwrap(); + std::fs::create_dir_all(&interop).unwrap(); + // one more entry than the archive scans (`MAX_SCAN`) + for i in 0..=1024 { + std::fs::write(interop.join(format!("other-{i}")), b"").unwrap(); + } let report = import(&mut s, &source, false).unwrap(); assert_eq!(report["imported"], 1); assert_eq!(report["archive"], Value::Null); @@ -488,7 +491,30 @@ fn an_archive_that_cannot_be_saved_warns_and_the_import_proceeds() { warnings.iter().any(|w| w.as_str().unwrap().starts_with(&format!("Lightroom source archive not saved in {}", interop.display()))), "{warnings:?}" ); - assert!(dir.join("elsewhere").join("lightroom-index.json").is_file(), "re-import mapping is still saved"); + assert!(interop.join("lightroom-index.json").is_file(), "re-import mapping is still saved"); + s.close_library().unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// A linked `Interop` folder gets neither the archive nor the import index: both would land +/// outside the library. The photos are still imported; the index write says why it failed. +#[cfg(unix)] +#[test] +fn a_linked_interop_folder_gets_neither_the_archive_nor_the_index() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-interop-linked-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("elsewhere")).unwrap(); + let source = dir.join("source.lrcat"); + std::fs::write(&source, native_catalog(&photo_tables((dir.join("offline").to_str().unwrap(), "")))).unwrap(); + let library = dir.join("library"); + let mut s = crate::Session::new(); + s.open_library(&library, false).unwrap(); + let interop = library.join("Interop"); + std::os::unix::fs::symlink(dir.join("elsewhere"), &interop).unwrap(); + let e = import(&mut s, &source, false).unwrap_err(); + assert!(e.to_string().contains(&format!("{} is a link or a file, not a folder", interop.display())), "{e}"); + assert_eq!(s.catalog.photos().count(), 1, "the photos are imported before the index is written"); + assert_eq!(std::fs::read_dir(dir.join("elsewhere")).unwrap().count(), 0, "nothing is written through the link"); s.close_library().unwrap(); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index e830def4b0a..d7a13de47bf 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -128,8 +128,14 @@ impl LightroomArchiveFinalization { if bytes.len() > MAX_INDEX_BYTES { return Err(error("Lightroom import index exceeds 16 MiB")); } - lightcraft_catalog::safe_file::write_atomic(&path, &bytes) - .map_err(|e| crate::EngineError::Other(format!("could not write the Lightroom import index {}: {e}", path.display()))) + let failed = + |e: &dyn std::fmt::Display| crate::EngineError::Other(format!("could not write the Lightroom import index {}: {e}", path.display())); + // the archive refuses a linked `Interop` folder; now that its failure no longer stops the + // import, the index must refuse it too, or it would be written outside the library + if let Some(dir) = path.parent() { + crate::lightroom_archive::require_real_directory(dir).map_err(|e| failed(&e))?; + } + lightcraft_catalog::safe_file::write_atomic(&path, &bytes).map_err(|e| failed(&e)) } pub fn path(&self) -> Option<&Path> { @@ -603,6 +609,29 @@ mod tests { assert!(e.to_string().starts_with(&format!("could not write the Lightroom import index {}", path.display())), "{e}"); } + /// A linked `Interop` folder (which the archive already refuses) must not receive the index: + /// it would land outside the library and could replace a file there. + #[cfg(unix)] + #[test] + fn an_index_write_refuses_a_linked_interop_folder() { + let root = std::env::temp_dir().join(format!("lightcraft-lr-index-linked-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (library, outside) = (root.join("library"), root.join("outside")); + std::fs::create_dir_all(&library).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("lightroom-index.json"), b"not ours").unwrap(); + std::os::unix::fs::symlink(&outside, library.join("Interop")).unwrap(); + let path = library.join("Interop/lightroom-index.json"); + let e = LightroomArchiveFinalization { path: Some(path), bytes: Some(b"{}".to_vec()) }.finish().unwrap_err(); + assert!(e.to_string().contains("is a link or a file, not a folder"), "{e}"); + assert_eq!(std::fs::read(outside.join("lightroom-index.json")).unwrap(), b"not ours"); + // the archive gives way with a warning, so the import goes on to this write: both refuse the link + let mut data = empty_data(); + assert_eq!(stage_archive(Some(&library.join("Interop")), &mut data).unwrap(), None); + assert!(data.warnings[0].contains("is a link or a file, not a folder"), "{}", data.warnings[0]); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn execute_fn_import_does_not_rewrite_source_sidecar() { let dir = std::env::temp_dir().join(format!("lightcraft-lr-job-sidecar-{}", std::process::id())); diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 93cafb998da..b4818250a6b 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -83,8 +83,10 @@ still never replaces an existing archive. Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. Each archive is capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. -`Interop/lightroom-index.json` records imported identities. Source catalogs and originals are -never overwritten. +`Interop/lightroom-index.json` records imported identities. When `Interop` is a link or a file +rather than a folder, neither the archive nor the index is written there (the archive is skipped +with a warning; the index write reports an error after the photos are imported), so nothing lands +outside the library. Source catalogs and originals are never overwritten. Native import reads referenced database pages on demand (at most 64 KiB per page), rather than loading the whole `.lrcat`. Database files are capped at 16 GiB and 16,777,216 pages; the WAL From 0a1b05b405e06c0736ba3d1e842467fdd2de5b1f Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 27 Oct 2026 10:30:12 -0500 Subject: [PATCH 04/16] fix(lightroom): refuse a linked Interop folder before importing (#3114) The index write already refused a linked `Interop` folder, but only after the photos were committed, so `library.importLightroom` returned an error for an import that had happened and a retry could duplicate virtual copies. Preparation now refuses an `Interop` that is a link or a file, before any change, as it did before the archive became best-effort. The index write keeps its own check. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_catalog/tests.rs | 2 +- crates/engine/src/lightroom_job.rs | 18 ++++++++++++++---- docs/lightroom-catalog-import.md | 5 ++--- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 432103f5bb2..02c88afe425 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -513,7 +513,7 @@ fn a_linked_interop_folder_gets_neither_the_archive_nor_the_index() { std::os::unix::fs::symlink(dir.join("elsewhere"), &interop).unwrap(); let e = import(&mut s, &source, false).unwrap_err(); assert!(e.to_string().contains(&format!("{} is a link or a file, not a folder", interop.display())), "{e}"); - assert_eq!(s.catalog.photos().count(), 1, "the photos are imported before the index is written"); + assert_eq!(s.catalog.photos().count(), 0, "refused before anything is imported, so a retry can't duplicate"); assert_eq!(std::fs::read_dir(dir.join("elsewhere")).unwrap().count(), 0, "nothing is written through the link"); s.close_library().unwrap(); std::fs::remove_dir_all(dir).unwrap(); diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index d7a13de47bf..9020f6d0f00 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -36,6 +36,12 @@ fn cancelled() -> crate::EngineError { /// (one per unreadable record) can be many. fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result> { let Some(dir) = archive_dir else { return Ok(None) }; + // A linked `Interop` folder would take the import index outside the library. Refuse it here, + // before anything is imported, rather than import the photos and then fail at the index. + if dir.symlink_metadata().is_ok() { + crate::lightroom_archive::require_real_directory(dir) + .map_err(|e| crate::EngineError::Other(format!("cannot import into this library: {e}")))?; + } match crate::lightroom_archive::store_best_effort(dir, data) { Ok(Some(path)) => Ok(Some(path)), Ok(None) => { @@ -589,7 +595,11 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let interop = dir.join("Interop"); - std::fs::write(&interop, b"a file where the folder belongs").unwrap(); + std::fs::create_dir_all(&interop).unwrap(); + // one more entry than the archive scans (`MAX_SCAN`) + for i in 0..=1024 { + std::fs::write(interop.join(format!("other-{i}")), b"").unwrap(); + } let mut data = empty_data(); // more catalog warnings than the result window lists: the archive's must still be seen data.warnings = (0..10).map(|i| format!("record {i}: unreadable XMP")).collect(); @@ -625,10 +635,10 @@ mod tests { let e = LightroomArchiveFinalization { path: Some(path), bytes: Some(b"{}".to_vec()) }.finish().unwrap_err(); assert!(e.to_string().contains("is a link or a file, not a folder"), "{e}"); assert_eq!(std::fs::read(outside.join("lightroom-index.json")).unwrap(), b"not ours"); - // the archive gives way with a warning, so the import goes on to this write: both refuse the link + // preparation refuses the link before anything is imported let mut data = empty_data(); - assert_eq!(stage_archive(Some(&library.join("Interop")), &mut data).unwrap(), None); - assert!(data.warnings[0].contains("is a link or a file, not a folder"), "{}", data.warnings[0]); + let e = stage_archive(Some(&library.join("Interop")), &mut data).unwrap_err(); + assert!(e.to_string().contains("is a link or a file, not a folder"), "{e}"); std::fs::remove_dir_all(root).unwrap(); } diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index b4818250a6b..42296a778c2 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -84,9 +84,8 @@ Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. `Interop/lightroom-index.json` records imported identities. When `Interop` is a link or a file -rather than a folder, neither the archive nor the index is written there (the archive is skipped -with a warning; the index write reports an error after the photos are imported), so nothing lands -outside the library. Source catalogs and originals are never overwritten. +rather than a folder, the import is refused before anything changes, so nothing lands outside the +library (the index write checks the folder again). Source catalogs and originals are never overwritten. Native import reads referenced database pages on demand (at most 64 KiB per page), rather than loading the whole `.lrcat`. Database files are capped at 16 GiB and 16,777,216 pages; the WAL From 54a3712f49ef32e084ea1e3abab00271555d4e2d Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 27 Oct 2026 14:44:53 -0500 Subject: [PATCH 05/16] fix(lightroom): refuse an unwritable Interop folder before importing (#3114) Since the recovery archive became best-effort, an `Interop` folder that exists but can't be written to cost only the archive: preparation went on, `commit_prepared` applied the import to the session, it was saved, and only then did `LightroomArchiveFinalization::finish` fail to write `lightroom-index.json`. `library.importLightroom` returned an error for an import that had happened, and a retry could duplicate virtual copies. Before #3114 the archive failure stopped the import first. `stage_archive` now checks the index folder before anything changes (`require_index_folder`): it creates `Interop` when absent, as the archive would, refuses a link or a file as before, and creates and removes a probe file there (an exclusive create, never a hard link, so exFAT still passes). A failure is an error naming the folder. An archive that can't be saved in a writable folder stays a warning, and `finish` keeps its own checks. In-memory libraries have no index and no probe. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_catalog/tests.rs | 40 +++++++++++++++++- crates/engine/src/lightroom_job.rs | 43 ++++++++++++++++---- docs/lightroom-catalog-import.md | 9 ++-- docs/whats-new.md | 5 ++- 4 files changed, 83 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 02c88afe425..86640c49dee 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -461,6 +461,9 @@ fn imports_into_a_library_on_a_volume_without_hard_links() { assert_eq!(archive, library.join("Interop").join("lightroom-import-0.lca")); assert!(std::fs::read(archive).unwrap().starts_with(b"LC-LRARCH")); assert!(library.join("Interop").join("lightroom-index.json").is_file()); + let mut names: Vec<_> = std::fs::read_dir(library.join("Interop")).unwrap().map(|entry| entry.unwrap().file_name()).collect(); + names.sort(); + assert_eq!(names, ["lightroom-import-0.lca", "lightroom-index.json"], "the writability probe leaves nothing behind"); s.close_library().unwrap(); std::fs::remove_dir_all(dir).unwrap(); } @@ -497,7 +500,7 @@ fn an_archive_that_cannot_be_saved_warns_and_the_import_proceeds() { } /// A linked `Interop` folder gets neither the archive nor the import index: both would land -/// outside the library. The photos are still imported; the index write says why it failed. +/// outside the library. The import is refused before any photo is imported. #[cfg(unix)] #[test] fn a_linked_interop_folder_gets_neither_the_archive_nor_the_index() { @@ -519,6 +522,41 @@ fn a_linked_interop_folder_gets_neither_the_archive_nor_the_index() { std::fs::remove_dir_all(dir).unwrap(); } +/// An `Interop` folder that can't be written to would let the photos be imported and then fail +/// at the import index, after the import was saved (a retry could duplicate virtual copies). It is +/// refused before any photo is imported, with an error naming the folder. +#[cfg(unix)] +#[test] +fn an_unwritable_interop_folder_is_refused_before_anything_is_imported() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-interop-readonly-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let source = dir.join("source.lrcat"); + std::fs::write(&source, native_catalog(&photo_tables((dir.join("offline").to_str().unwrap(), "")))).unwrap(); + let library = dir.join("library"); + let mut s = crate::Session::new(); + s.open_library(&library, false).unwrap(); + let interop = library.join("Interop"); + std::fs::create_dir_all(&interop).unwrap(); + std::fs::set_permissions(&interop, std::fs::Permissions::from_mode(0o555)).unwrap(); + // root (some containers) ignores folder permissions: there is nothing to refuse + if std::fs::write(interop.join("root-check"), b"").is_ok() { + std::fs::set_permissions(&interop, std::fs::Permissions::from_mode(0o755)).unwrap(); + s.close_library().unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + lightcraft_testkit::skip!(System, "folder permissions are not enforced for this user (root)"); + return; + } + let e = import(&mut s, &source, false).unwrap_err(); + std::fs::set_permissions(&interop, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(e.to_string().contains(&format!("the Lightroom import index can't be written in {}", interop.display())), "{e}"); + assert_eq!(s.catalog.photos().count(), 0, "refused before anything is imported, so a retry can't duplicate"); + assert_eq!(std::fs::read_dir(&interop).unwrap().count(), 0, "nothing was written"); + s.close_library().unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + // Construct a small SQLite fixture from public file-format records, never private media. fn varint(mut n: u64) -> Vec { let mut out = vec![(n & 127) as u8]; diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 9020f6d0f00..6bfef028334 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -30,18 +30,18 @@ fn cancelled() -> crate::EngineError { crate::EngineError::Cancelled(error("Lightroom import cancelled").to_string()) } -/// Save the recovery archive. It is best-effort: nothing reads it back during import, so a folder -/// it can't be written to costs the archive (with a warning naming the folder), not the import. +/// Save the recovery archive. It is best-effort: nothing reads it back during import, so an archive +/// that can't be saved costs the archive (with a warning naming the folder), not the import. A +/// folder that can't be written to at all is refused first, for the import index's sake. /// That warning goes first: the result window lists only the first few, and catalog warnings /// (one per unreadable record) can be many. fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result> { let Some(dir) = archive_dir else { return Ok(None) }; - // A linked `Interop` folder would take the import index outside the library. Refuse it here, - // before anything is imported, rather than import the photos and then fail at the index. - if dir.symlink_metadata().is_ok() { - crate::lightroom_archive::require_real_directory(dir) - .map_err(|e| crate::EngineError::Other(format!("cannot import into this library: {e}")))?; - } + // The import index, unlike the archive, is required, and it is written only after the photos + // are imported. Refuse here, before anything changes, a folder it can't be written to (a link + // would take it outside the library), rather than import and then fail, where a retry could + // duplicate virtual copies. + require_index_folder(dir).map_err(|e| crate::EngineError::Other(format!("cannot import into this library: {e}")))?; match crate::lightroom_archive::store_best_effort(dir, data) { Ok(Some(path)) => Ok(Some(path)), Ok(None) => { @@ -55,6 +55,33 @@ fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate: } } +/// Check that `lightroom-index.json` can be written in `dir` (creating the folder, as the archive +/// would): a real folder, not a link or a file, in which a file can be created and removed. The +/// probe is a plain exclusive create, never a hard link, so volumes without them (exFAT, #3114) pass. +fn require_index_folder(dir: &Path) -> Result<(), String> { + if let Err(e) = std::fs::symlink_metadata(dir) { + if e.kind() != std::io::ErrorKind::NotFound { + return Err(format!("cannot read {}: {e}", dir.display())); + } + std::fs::create_dir_all(dir).map_err(|e| format!("cannot create the folder {}: {e}", dir.display()))?; + } + crate::lightroom_archive::require_real_directory(dir)?; + let unwritable = |e: std::io::Error| format!("the Lightroom import index can't be written in {} ({e}); make the folder writable", dir.display()); + let pid = std::process::id(); + for slot in 0..64 { + let probe = dir.join(format!(".lightroom-index-probe-{pid}-{slot}.tmp")); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { + Ok(file) => { + drop(file); + return std::fs::remove_file(&probe).map_err(unwritable); + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(unwritable(e)), + } + } + Err(format!("no free name to check that {} is writable", dir.display())) +} + /// Memory identity of the library which owns a prepared completion. /// /// Each successful open/close refreshes session identity, including reopening the same path. diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 42296a778c2..f46198fe1d2 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -83,9 +83,12 @@ still never replaces an existing archive. Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. Each archive is capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. -`Interop/lightroom-index.json` records imported identities. When `Interop` is a link or a file -rather than a folder, the import is refused before anything changes, so nothing lands outside the -library (the index write checks the folder again). Source catalogs and originals are never overwritten. +`Interop/lightroom-index.json` records imported identities. Unlike the archive it is required, and +it is written after the photos are imported, so the importer checks its folder first: when +`Interop` is a link or a file rather than a folder, or a folder in which a file can't be created +(read-only, no permission), the import is refused before anything changes, with an error naming +the folder. Nothing lands outside the library, and a retry can't duplicate virtual copies (the index +write checks the folder again). Source catalogs and originals are never overwritten. Native import reads referenced database pages on demand (at most 64 KiB per page), rather than loading the whole `.lrcat`. Database files are capped at 16 GiB and 16,777,216 pages; the WAL diff --git a/docs/whats-new.md b/docs/whats-new.md index a77cdf62e2b..1a995606251 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -11,8 +11,9 @@ - Importing a Lightroom catalog into a library on an exFAT or FAT drive (or a network share without hard links) no longer fails with "cannot atomically publish archive: Operation not supported": the recovery archive in the library's `Interop` folder is saved another way that still never replaces an existing archive. When the archive - can't be saved at all, the import goes on and warns, naming the folder, as documented; a failed import-index write - now names the file instead of reporting "invalid parameters". + can't be saved at all, the import goes on and warns, naming the folder, as documented. An `Interop` folder that can't + be written to at all (or is a link) is refused before any photo is imported, naming it, since the import index must + be saved there; a failed import-index write now names the file instead of reporting "invalid parameters". ## 2026-10-25 From e148eff2434327e536dc3183a6106bb4296c4c09 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 27 Oct 2026 14:48:18 -0500 Subject: [PATCH 06/16] fix(lightroom): a saved archive is reported even when its cleanup fails (#3114) `lightroom_archive::store` published the archive and then returned an error when removing the temporary or retiring an old archive failed (and, on the reuse path, when pruning failed). `stage_archive` turned that into "archive not saved" and `"archive": null`, though the archive existed. `store` now returns `Stored { path, cleanup_failed }`: once the archive is published (or a matching one is reused), cleanup failures are collected by `clean_up_after_publish`, which tries every removal instead of stopping at the first, and `stage_archive` reports the archive's path plus a warning naming what was left behind. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_archive.rs | 88 ++++++++++++++++++++------ crates/engine/src/lightroom_catalog.rs | 3 +- crates/engine/src/lightroom_job.rs | 39 +++++++++++- docs/lightroom-catalog-import.md | 4 +- 4 files changed, 112 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 97ab9894709..a6e55bb832e 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -36,6 +36,22 @@ const NAME_SUFFIX: &str = ".lca"; const MAX_SCAN: usize = 1024; const IO_BUFFER: usize = 16 * 1024; +/// A saved archive. Once it is published it is complete, so cleanup that fails afterwards (a +/// temporary left behind, an old archive that could not be retired) is reported beside it, not +/// as a failure to save it. +#[derive(Debug, PartialEq, Eq)] +pub struct Stored { + pub path: PathBuf, + /// What could not be cleaned up after the archive was published, if anything. + pub cleanup_failed: Option, +} + +impl Stored { + fn new(path: PathBuf, problems: Vec) -> Self { + Self { path, cleanup_failed: (!problems.is_empty()).then(|| problems.join("; ")) } + } +} + /// Store compact source data below `directory` and return its managed archive. /// /// The operation is safe to call before catalog mutation. It rejects a @@ -44,7 +60,7 @@ const IO_BUFFER: usize = 16 * 1024; /// most [`MAX_MANAGED_ARCHIVES`] and [`MAX_TOTAL_ARCHIVE_BYTES`]. Legacy /// `lightroom-import-*.json` files are deliberately ignored and preserved for /// an explicit caller warning. -pub fn store(directory: &Path, data: &CatalogImport) -> Result { +pub fn store(directory: &Path, data: &CatalogImport) -> Result { prepare_directory(directory)?; let mut managed = managed_files(directory)?; managed.sort_by_key(|entry| entry.index); @@ -64,11 +80,17 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result } }; if same { - remove_managed_file(&temporary).map_err(|e| e.to_string())?; + // the matching archive already exists: what is left is cleanup + let mut problems = Vec::new(); + if let Err(error) = remove_managed_file(&temporary) { + problems.push(format!("could not remove the temporary {}: {error}", temporary.display())); + } let matched = entry.path.clone(); let mut all = managed.clone(); - prune_existing(directory, &mut all, Some(&matched))?; - return Ok(matched); + if let Err(error) = prune_existing(directory, &mut all, Some(&matched)) { + problems.push(error); + } + return Ok(Stored::new(matched, problems)); } } @@ -115,26 +137,33 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result let _ = remove_managed_file(&temporary); return Err(error.to_string()); } + Ok(Stored::new(destination, clean_up_after_publish(&temporary, &quarantined))) +} + +/// Remove the temporary and the quarantined old archives once the new archive is published, and +/// say what could not be removed. Every removal is tried; none of them can unpublish the archive. +fn clean_up_after_publish(temporary: &Path, quarantined: &[(PathBuf, PathBuf)]) -> Vec { + let mut problems = Vec::new(); // after a hard link the temporary is a second name of the archive; after the rename fallback it is gone - match remove_managed_file(&temporary) { + match remove_managed_file(temporary) { Err(error) if error.kind() != io::ErrorKind::NotFound => { - return Err(format!("archive published but temporary cleanup failed: {error}")); + problems.push(format!("could not remove the temporary {}: {error}", temporary.display())); } _ => {} } for (old, held) in quarantined { - if let Err(error) = remove_managed_file(&held) { - return Err(format!("archive published but could not retire {}: {error}", old.display())); + if let Err(error) = remove_managed_file(held) { + problems.push(format!("could not retire {} (left as {}): {error}", old.display(), held.display())); } } - Ok(destination) + problems } /// Store source data when possible. An archive that reaches its bounded size is /// omitted with a warning so catalog import can still complete. -pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result, String> { +pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result, String> { match store(directory, data) { - Ok(path) => Ok(Some(path)), + Ok(stored) => Ok(Some(stored)), Err(error) if error.contains("Lightroom archive exceeds 32 MiB") => Ok(None), Err(error) => Err(error), } @@ -562,8 +591,8 @@ mod tests { fn deduplicates_identical_deterministic_archives() { let path = tempdir(); let input = data("catalog.lrcat".into()); - let first = store(&path, &input).unwrap(); - let second = store(&path, &input).unwrap(); + let first = store(&path, &input).unwrap().path; + let second = store(&path, &input).unwrap().path; assert_eq!(first, second); assert_eq!(managed_count(&path), 1); fs::remove_dir_all(path).unwrap(); @@ -573,12 +602,12 @@ mod tests { fn dedup_returns_archive_that_retention_keeps() { let path = tempdir(); let input = data("catalog.lrcat".into()); - let first = store(&path, &input).unwrap(); + let first = store(&path, &input).unwrap().path; for index in 1..MAX_MANAGED_ARCHIVES { let filler = path.join(format!("lightroom-import-{index}.lca")); File::create(filler).unwrap().set_len(19 * 1024 * 1024).unwrap(); } - let reused = store(&path, &input).unwrap(); + let reused = store(&path, &input).unwrap().path; assert_eq!(reused, first); assert!(reused.is_file()); assert!(managed_count(&path) <= MAX_MANAGED_ARCHIVES); @@ -637,7 +666,7 @@ mod tests { #[test] fn archive_roundtrips_zlib_payload_and_preserves_numeric_arrays() { let path = tempdir(); - let archive = store(&path, &rich_data()).unwrap(); + let archive = store(&path, &rich_data()).unwrap().path; let bytes = fs::read(archive).unwrap(); assert!(bytes.starts_with(HEADER)); let json = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&bytes[HEADER.len()..], MAX_ARCHIVE_BYTES as usize).unwrap(); @@ -689,17 +718,38 @@ mod tests { fs::remove_dir_all(path).unwrap(); } + /// Cleanup after publishing tries every removal and reports each failure; it never fails the + /// archive, which is already published. + #[test] + fn cleanup_after_publish_reports_what_it_could_not_remove_and_removes_the_rest() { + let path = tempdir(); + let temporary = path.join(".lightroom-import-new.tmp"); + fs::write(&temporary, b"second name").unwrap(); + // a held name that is no longer a regular file can't be removed; the next one still is + let (stuck, held_stuck) = (path.join("lightroom-import-0.lca"), path.join(".lightroom-retire-test-0.tmp")); + let (gone, held_gone) = (path.join("lightroom-import-1.lca"), path.join(".lightroom-retire-test-1.tmp")); + fs::create_dir(&held_stuck).unwrap(); + fs::write(&held_gone, b"old").unwrap(); + let problems = clean_up_after_publish(&temporary, &[(stuck.clone(), held_stuck.clone()), (gone, held_gone.clone())]); + assert_eq!(problems.len(), 1, "{problems:?}"); + assert!(problems[0].starts_with(&format!("could not retire {} (left as {})", stuck.display(), held_stuck.display())), "{problems:?}"); + assert!(!temporary.exists() && !held_gone.exists()); + let stored = Stored::new(path.join("lightroom-import-2.lca"), problems); + assert!(stored.cleanup_failed.is_some_and(|note| note.contains("could not retire"))); + fs::remove_dir_all(path).unwrap(); + } + /// Issue #3114: a library on exFAT (no hard links) aborted every Lightroom import here. #[test] fn publishes_on_a_volume_without_hard_links() { let path = tempdir(); let _no_links = lightcraft_catalog::safe_file::without_hard_links(); - let first = store(&path, &rich_data()).unwrap(); + let first = store(&path, &rich_data()).unwrap().path; assert!(fs::read(&first).unwrap().starts_with(HEADER)); // retention and dedup still work: a new archive gets the next name, the same data reuses it - let second = store(&path, &data("other.lrcat".into())).unwrap(); + let second = store(&path, &data("other.lrcat".into())).unwrap().path; assert_ne!(first, second); - assert_eq!(store(&path, &rich_data()).unwrap(), first); + assert_eq!(store(&path, &rich_data()).unwrap().path, first); let mut names: Vec<_> = fs::read_dir(&path).unwrap().map(|entry| entry.unwrap().file_name()).collect(); names.sort(); assert_eq!(names, ["lightroom-import-0.lca", "lightroom-import-1.lca"], "no temporary left behind"); diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 3066187ce36..1c9631b9b9a 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -824,7 +824,8 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) -> let archive_dir = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop")); let index_path = archive_dir.as_ref().map(|p| p.join("lightroom-index.json")); let mut index = load_index(index_path.as_deref())?; - let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(error)).transpose()?; + let archive_path = + archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map(|stored| stored.path).map_err(error)).transpose()?; let undo0 = s.undo.len(); let existing: HashMap<_, _> = s.catalog.photos().filter(|p| p.copy_of.is_none()).filter_map(|p| source_path(p).map(|path| (key(path), p.id))).collect(); diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 6bfef028334..882b76eb28b 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -43,7 +43,16 @@ fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate: // duplicate virtual copies. require_index_folder(dir).map_err(|e| crate::EngineError::Other(format!("cannot import into this library: {e}")))?; match crate::lightroom_archive::store_best_effort(dir, data) { - Ok(Some(path)) => Ok(Some(path)), + Ok(Some(stored)) => { + // the archive is saved: the report names it, and the leftover is a warning of its own + if let Some(problem) = stored.cleanup_failed { + data.warnings.insert( + 0, + format!("Lightroom source archive saved as {}, but cleaning up {} failed: {problem}", stored.path.display(), dir.display()), + ); + } + Ok(Some(stored.path)) + } Ok(None) => { data.warnings.insert(0, "Lightroom source archive exceeded 32 MiB; archive skipped".into()); Ok(None) @@ -637,6 +646,34 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// An archive that is saved but whose cleanup fails afterwards (here an old archive can't be + /// retired) is still the import's archive: the report names it, and the cleanup is a warning. + #[test] + fn a_saved_archive_whose_cleanup_fails_is_reported_with_a_warning() { + let dir = std::env::temp_dir().join(format!("lightcraft-lr-archive-cleanup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let interop = dir.join("Interop"); + std::fs::create_dir_all(&interop).unwrap(); + let mut data = empty_data(); + // an older archive, then this catalog's, then enough others to retire the older one + std::fs::write(interop.join("lightroom-import-0.lca"), b"older").unwrap(); + let saved = crate::lightroom_archive::store(&interop, &data).unwrap().path; + assert_eq!(saved, interop.join("lightroom-import-1.lca")); + for i in 2..=crate::lightroom_archive::MAX_MANAGED_ARCHIVES { + std::fs::write(interop.join(format!("lightroom-import-{i}.lca")), format!("other {i}")).unwrap(); + } + // retiring the older archive needs this name, which is taken + std::fs::write(interop.join(format!(".lightroom-retire-{}-0.tmp", std::process::id())), b"taken").unwrap(); + assert_eq!(stage_archive(Some(&interop), &mut data).unwrap(), Some(saved.clone())); + assert!(saved.is_file()); + assert_eq!(data.warnings.len(), 1, "{:?}", data.warnings); + let warning = &data.warnings[0]; + assert!(warning.starts_with(&format!("Lightroom source archive saved as {}, but cleaning up", saved.display())), "{warning}"); + assert!(warning.contains("retention temporary path already exists"), "{warning}"); + assert_eq!(std::fs::read(interop.join("lightroom-import-0.lca")).unwrap(), b"older", "the older archive is kept"); + std::fs::remove_dir_all(dir).unwrap(); + } + /// A failed index write is an I/O error naming the file, not "invalid parameters". #[test] fn an_index_write_failure_names_the_index_file() { diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index f46198fe1d2..93004c5ae08 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -82,7 +82,9 @@ archive is published by claiming its name with an exclusive create and renaming still never replaces an existing archive. Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. Each archive is capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total -retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. +retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. When an +archive is saved but cleanup afterwards fails (a temporary file or an old archive that can't be +removed), the report still names the archive and a separate warning names what was left behind. `Interop/lightroom-index.json` records imported identities. Unlike the archive it is required, and it is written after the photos are imported, so the importer checks its folder first: when `Interop` is a link or a file rather than a folder, or a folder in which a file can't be created From e0197b6045e40d41342f2e31bbaa6318d8ebd704 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Thu, 29 Oct 2026 23:55:56 -0500 Subject: [PATCH 07/16] fix(lightroom): reusing an archive tries to retire every old one (#3114) When a matching archive was reused, `prune_existing` stopped at the first old archive it could not remove, so the rest stayed in quarantine and the warning named only the first. It now goes through `retire`, the loop `clean_up_after_publish` already used: every removal is tried and each failure is named with the file it left behind. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_archive.rs | 57 ++++++++++++++++++-------- 1 file changed, 40 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index a6e55bb832e..dcb62cdbade 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -86,10 +86,7 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result { problems.push(format!("could not remove the temporary {}: {error}", temporary.display())); } let matched = entry.path.clone(); - let mut all = managed.clone(); - if let Err(error) = prune_existing(directory, &mut all, Some(&matched)) { - problems.push(error); - } + problems.extend(prune_existing(&managed, Some(&matched))); return Ok(Stored::new(matched, problems)); } } @@ -151,14 +148,22 @@ fn clean_up_after_publish(temporary: &Path, quarantined: &[(PathBuf, PathBuf)]) } _ => {} } - for (old, held) in quarantined { - if let Err(error) = remove_managed_file(held) { - problems.push(format!("could not retire {} (left as {}): {error}", old.display(), held.display())); - } - } + problems.extend(retire(quarantined)); problems } +/// Remove quarantined old archives and say which could not be removed. Every removal is tried, so +/// one stuck archive does not keep the rest. +fn retire(quarantined: &[(PathBuf, PathBuf)]) -> Vec { + quarantined + .iter() + .filter_map(|(old, held)| { + let error = remove_managed_file(held).err()?; + Some(format!("could not retire {} (left as {}): {error}", old.display(), held.display())) + }) + .collect() +} + /// Store source data when possible. An archive that reaches its bounded size is /// omitted with a warning so catalog import can still complete. pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result, String> { @@ -402,15 +407,13 @@ fn retirement_set_protected(entries: &[Managed], protected: Option<&Path>) -> Re Ok(retirees) } -fn prune_existing(directory: &Path, entries: &mut [Managed], protected: Option<&Path>) -> Result<(), String> { - let retirees = retirement_set_protected(entries, protected)?; - let quarantined = quarantine(&retirees)?; - for (old, held) in quarantined { - if let Err(error) = remove_managed_file(&held) { - return Err(format!("could not retire {} from {}: {error}", old.display(), directory.display())); - } +/// Retire what the retention limits no longer allow, keeping `protected`, and say what could not be +/// retired. +fn prune_existing(entries: &[Managed], protected: Option<&Path>) -> Vec { + match retirement_set_protected(entries, protected).and_then(|retirees| quarantine(&retirees)) { + Ok(quarantined) => retire(&quarantined), + Err(error) => vec![error], } - Ok(()) } fn quarantine(entries: &[Managed]) -> Result, String> { @@ -739,6 +742,26 @@ mod tests { fs::remove_dir_all(path).unwrap(); } + /// Reusing a matching archive retires the old ones the same way: one that can't be removed is + /// named, and the ones after it are still removed and named when they fail too. + #[test] + fn retire_tries_every_archive_and_names_each_one_it_could_not_remove() { + let path = tempdir(); + let held = |slot: usize| path.join(format!(".lightroom-retire-test-{slot}.tmp")); + let old = |slot: usize| path.join(format!("lightroom-import-{slot}.lca")); + fs::create_dir(held(0)).unwrap(); + fs::write(held(1), b"old").unwrap(); + fs::create_dir(held(2)).unwrap(); + let quarantined: Vec<_> = (0..3).map(|slot| (old(slot), held(slot))).collect(); + let problems = retire(&quarantined); + assert_eq!(problems.len(), 2, "{problems:?}"); + for (problem, slot) in problems.iter().zip([0, 2]) { + assert!(problem.starts_with(&format!("could not retire {} (left as {})", old(slot).display(), held(slot).display())), "{problems:?}"); + } + assert!(!held(1).exists()); + fs::remove_dir_all(path).unwrap(); + } + /// Issue #3114: a library on exFAT (no hard links) aborted every Lightroom import here. #[test] fn publishes_on_a_volume_without_hard_links() { From f84818da5cd4098ad91127cc5f8237bccc1fb66c Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Fri, 30 Oct 2026 02:25:27 -0500 Subject: [PATCH 08/16] fix(lightroom): sync the archive folder once the archive is saved (#3114) `store` gave the archive its final name (a hard link, or a rename on a volume without hard links) and retired old archives without syncing the folder, so a power loss or an unplugged drive could leave the archive the import reports without its name. The folder is now synced after the last change on both the publishing and the reuse paths. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_archive.rs | 29 +++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index dcb62cdbade..45ac3f41b17 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -87,6 +87,7 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result { } let matched = entry.path.clone(); problems.extend(prune_existing(&managed, Some(&matched))); + lightcraft_catalog::safe_file::sync_dir(directory); return Ok(Stored::new(matched, problems)); } } @@ -134,7 +135,10 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result { let _ = remove_managed_file(&temporary); return Err(error.to_string()); } - Ok(Stored::new(destination, clean_up_after_publish(&temporary, &quarantined))) + let problems = clean_up_after_publish(&temporary, &quarantined); + // the archive's name (and the retired ones' removal) survives a power loss or an unplugged drive + lightcraft_catalog::safe_file::sync_dir(directory); + Ok(Stored::new(destination, problems)) } /// Remove the temporary and the quarantined old archives once the new archive is published, and @@ -762,6 +766,29 @@ mod tests { fs::remove_dir_all(path).unwrap(); } + /// The folder is synced once the archive has its name (and old ones are retired), so a power + /// loss can't leave the archive the import reports without that name; also when a matching + /// archive is reused and old ones are retired. + #[test] + fn the_archive_folder_is_synced_after_publishing_and_after_reuse() { + let path = tempdir(); + let _no_links = lightcraft_catalog::safe_file::without_hard_links(); + let syncs = lightcraft_catalog::safe_file::syncs_on_this_thread; + // what writing the temporary alone syncs (the file and its folder) + let scratch = path.join(".scratch.tmp"); + let before = syncs(); + write_archive(&scratch, &rich_data()).unwrap(); + let writing = syncs() - before; + fs::remove_file(scratch).unwrap(); + let before = syncs(); + let first = store(&path, &rich_data()).unwrap().path; + assert_eq!(syncs() - before, writing + 1, "published: the folder is synced after the name is given"); + let before = syncs(); + assert_eq!(store(&path, &rich_data()).unwrap().path, first); + assert_eq!(syncs() - before, writing + 1, "reused: the folder is synced after the cleanup"); + fs::remove_dir_all(path).unwrap(); + } + /// Issue #3114: a library on exFAT (no hard links) aborted every Lightroom import here. #[test] fn publishes_on_a_volume_without_hard_links() { From 51a78205aefedcfe5e9cc6856030e26e50689b32 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Fri, 30 Oct 2026 02:49:49 -0500 Subject: [PATCH 09/16] docs(lightroom): a failed index write can let a retry duplicate virtual copies (#3114) The import doc said a retry can't duplicate virtual copies. The folder check before the import prevents the known folder and link failures, but the index is written after the photos are imported: if that write fails (a full disk, an index over 16 MiB), the index doesn't list the new photos and a retry can import their virtual copies again. Say so. Co-Authored-By: Claude Opus 5.5 --- docs/lightroom-catalog-import.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 93004c5ae08..68868080ccd 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -89,8 +89,10 @@ removed), the report still names the archive and a separate warning names what w it is written after the photos are imported, so the importer checks its folder first: when `Interop` is a link or a file rather than a folder, or a folder in which a file can't be created (read-only, no permission), the import is refused before anything changes, with an error naming -the folder. Nothing lands outside the library, and a retry can't duplicate virtual copies (the index -write checks the folder again). Source catalogs and originals are never overwritten. +the folder. Nothing lands outside the library. The check can't catch everything: when the index +write itself fails after the photos are imported (the disk fills up, or the index would exceed 16 MiB), +the import reports the error, the photos stay, and a retry may import their virtual copies again, +because the index doesn't list them. Source catalogs and originals are never overwritten. Native import reads referenced database pages on demand (at most 64 KiB per page), rather than loading the whole `.lrcat`. Database files are capped at 16 GiB and 16,777,216 pages; the WAL From 4245e7fc80125a546ec2ebd68e8a40497d7fd0e9 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Fri, 30 Oct 2026 03:39:31 -0500 Subject: [PATCH 10/16] test(lightroom): the archive folder-sync test runs on Unix only (#3114) Windows can't open a folder to sync it, so `safe_file::sync_dir` does nothing there and the sync count the test checks doesn't change. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_archive.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 45ac3f41b17..63f59fd7e82 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -768,7 +768,9 @@ mod tests { /// The folder is synced once the archive has its name (and old ones are retired), so a power /// loss can't leave the archive the import reports without that name; also when a matching - /// archive is reused and old ones are retired. + /// archive is reused and old ones are retired. (Unix only: Windows can't open a folder to sync + /// it, so `sync_dir` does nothing there and counts nothing.) + #[cfg(unix)] #[test] fn the_archive_folder_is_synced_after_publishing_and_after_reuse() { let path = tempdir(); From efb2fe2f43a6fe9967da0b192bd674a19408fe32 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Fri, 30 Oct 2026 12:49:53 -0500 Subject: [PATCH 11/16] docs(lightroom): say which archive failures only warn, and what the no-replace claim covers (#3114) An Interop folder that can't hold the import index refuses the import before anything changes; only a failure writing the archive itself is a warning. On a volume without hard links the archive is published by an exclusive create and a rename over that placeholder: it never replaces an existing archive or one another writer claims the same way, but a process that deletes or replaces the placeholder in between is not guarded against (as safe_file's own docs say). Co-Authored-By: Claude Opus 5.5 --- docs/lightroom-catalog-import.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 68868080ccd..8bcd350dc63 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -76,10 +76,12 @@ catalog changes; any saved recovery archives remain available. Before changing records, the importer attempts to save source image records, decoded XMP, verbatim develop settings, history, snapshots and collection content to compressed `Interop/lightroom-import-N.lca` recovery archives in the LightCraft library. Archiving is -best-effort: a size limit or write failure produces a warning (naming the `Interop` folder) and -does not prevent photo import. On a volume without hard links (exFAT, FAT, some network shares) an -archive is published by claiming its name with an exclusive create and renaming over it, so it -still never replaces an existing archive. +best-effort: a size limit, or a failure writing the archive itself, produces a warning (naming the +`Interop` folder) and does not prevent photo import; an `Interop` folder that can't hold the import +index refuses the import first (below). On a volume without hard links (exFAT, FAT, some network +shares) an archive is published by claiming its name with an exclusive create and renaming over +it, so it still never replaces an existing archive or one another writer claims the same way; a +process that deletes or replaces the claimed placeholder before the rename is not guarded against. Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. Each archive is capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. When an From b1c17674d24574c3f92931b9cdf20722499ca4a4 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 27 Oct 2026 06:04:43 -0500 Subject: [PATCH 12/16] Issue #1588: one bad Lightroom record costs that record, not the import MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A damaged catalog failed the whole import at its first contradictory record, and every failure (I/O, a damaged database, bad records) read "invalid parameters for `library.importLightroom`", so nobody could tell what failed. - skip_inconsistent_records replaces validate. It runs where the catalog is read (so library.inspectLightroom reports it too) and again in apply_prepared. A second image with an id already seen (the first is kept), a virtual copy whose master is not in the catalog, and one whose master is itself a copy are skipped and listed in `skipped` (new reasons duplicateId, missingMaster, masterIsCopy). A collection hierarchy that loops is cut at its oldest collection (lowest id), and one deeper than 64 is cut every 64 levels from its top; the collection that is cut goes to the top level, with a warning. - A keyword whose parents loop or nest deeper than 64 keeps its path up to where the loop comes back, with one warning per keyword. - apply_prepared's "virtual copy …: missing master" errors became skips. - Only a catalog that can't be read at all still fails, before any change, as ErrorKind::Other naming the file: "the Lightroom catalog … can't be read: …" (I/O, too large, changed while read), "… is damaged: table Adobe_images can't be read: …" (database, WAL or a required table), or "… is not a Lightroom Classic catalog (or is damaged): it has no … table". read/read_with_progress return crate::Result, and cancelling stays Cancelled. An unreadable lightroom-index.json, an oversized index, and a stale completion are Other too; real bad parameters (a missing `path`) stay BadParams. - The result window counts contradictory records on their own translated line next to the incomplete-records line. Refs #2532 and #2589 (bad records no longer cost a whole large catalog). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/library/specs.rs | 2 +- crates/engine/src/lightroom_catalog.rs | 341 +++++++++++++------ crates/engine/src/lightroom_catalog/tests.rs | 164 ++++++++- crates/engine/src/lightroom_job.rs | 22 +- crates/engine/src/lightroom_sqlite.rs | 5 +- crates/ui-egui/locales/cs-formats.json | 1 + crates/ui-egui/locales/de-formats.json | 1 + crates/ui-egui/locales/es-formats.json | 1 + crates/ui-egui/locales/fi-formats.json | 1 + crates/ui-egui/locales/fr-formats.json | 1 + crates/ui-egui/locales/id-formats.json | 1 + crates/ui-egui/locales/it-formats.json | 1 + crates/ui-egui/locales/ja-formats.json | 1 + crates/ui-egui/locales/ka-formats.json | 1 + crates/ui-egui/locales/pl-formats.json | 1 + crates/ui-egui/locales/pt-br-formats.json | 1 + crates/ui-egui/locales/ru-formats.json | 1 + crates/ui-egui/locales/sv-formats.json | 1 + crates/ui-egui/locales/uk-formats.json | 1 + crates/ui-egui/locales/vi-formats.json | 1 + crates/ui-egui/locales/zh-hans-formats.json | 1 + crates/ui-egui/locales/zh-hant-formats.json | 1 + crates/ui-egui/src/lightroom_import.rs | 35 +- docs/lightroom-catalog-import.md | 26 +- docs/parity-checklist.md | 5 +- docs/whats-new.md | 7 + 26 files changed, 478 insertions(+), 146 deletions(-) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 2e7c1311d0c..979c12db032 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1252,7 +1252,7 @@ pub fn specs() -> Vec { "{path: .lrcat} → {photos, collections, missing, warnings}; read-only, no Lightroom required", always, |_, p| { let path = str_param(p,"path").ok_or_else(|| bad("library.inspectLightroom","missing path"))?; - let data = crate::lightroom_catalog::read(std::path::Path::new(path)).map_err(|e| bad("library.inspectLightroom",e))?; + let data = crate::lightroom_catalog::read(std::path::Path::new(path))?; Ok(json!({"photos":data.photos.len(),"collections":data.collections.iter().filter(|r|r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0)==0.0).count(),"missing":data.photos.iter().filter(|p| !p.original_is_file()).map(|p|&p.path).collect::>(),"warnings":data.warnings,"skipped":data.skipped})) }), cmd!( diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 1c9631b9b9a..a424dbbf159 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -15,12 +15,21 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; type Row = BTreeMap; -const COMMAND: &str = "library.importLightroom"; /// Largest catalog database or WAL read into memory (4 GiB). The whole file is held in RAM, so the cap stays finite. const MAX_FILE: u64 = 1 << 32; +/// Deepest keyword or collection hierarchy followed; a deeper chain is cut there. +const MAX_DEPTH: usize = 64; -fn error(why: impl Into) -> crate::EngineError { - crate::EngineError::BadParams { cmd: COMMAND.into(), msg: why.into() } +/// The catalog at `path` can't be read (it is missing, not allowed, too large or changing): an +/// error naming it, not "invalid parameters". +fn unreadable(path: &Path, why: impl std::fmt::Display) -> crate::EngineError { + crate::EngineError::Other(format!("the Lightroom catalog {} can't be read: {why}", path.display())) +} + +/// The catalog at `path` is read but isn't a whole catalog (its database or a table it needs is +/// broken): an error naming it. +fn damaged(path: &Path, why: impl std::fmt::Display) -> crate::EngineError { + crate::EngineError::Other(format!("the Lightroom catalog {} is damaged: {why}", path.display())) } fn text<'a>(r: &'a Row, k: &str) -> &'a str { @@ -49,14 +58,18 @@ struct Reader { tables: Vec, } impl Reader { - fn table(&self, name: &str, required: bool) -> Result, String> { - let Some(t) = self.tables.iter().find(|t| t.name == name) else { - return if required { Err(format!("unsupported Lightroom catalog: missing {name}")) } else { Ok(Vec::new()) }; - }; - let columns = t.column_names.as_ref().ok_or_else(|| format!("cannot read {name} columns"))?; - let rows = self.db.read_table(t.rootpage, columns.len()).map_err(|e| format!("{name}: {e:?}"))?; + fn has(&self, name: &str) -> bool { + self.tables.iter().any(|t| t.name == name) + } + + /// The rows of table `name` (none when it is not in the catalog); an error says what is wrong + /// with the table, the caller names it. + fn table(&self, name: &str) -> Result, String> { + let Some(t) = self.tables.iter().find(|t| t.name == name) else { return Ok(Vec::new()) }; + let columns = t.column_names.as_ref().ok_or("cannot read its columns")?; + let rows = self.db.read_table(t.rootpage, columns.len())?; if rows.len() > 1_000_000 { - return Err(format!("{name}: more than one million records")); + return Err("more than one million records".into()); } Ok(rows .into_iter() @@ -78,22 +91,19 @@ impl Reader { .collect()) } - fn optional_table(&self, name: &str, warnings: &mut Vec) -> Result, String> { - match self.table(name, false) { - Ok(rows) => Ok(rows), - Err(error) => { - warnings.push(format!("skipping optional Lightroom table {name}: {error}")); - Ok(Vec::new()) - } - } + fn optional_table(&self, name: &str, warnings: &mut Vec) -> Vec { + self.table(name).unwrap_or_else(|error| { + warnings.push(format!("skipping optional Lightroom table {name}: {error}")); + Vec::new() + }) } fn xmp_table(&self) -> Result<(Vec, Vec), String> { let Some(t) = self.tables.iter().find(|t| t.name == "Adobe_AdditionalMetadata") else { return Ok((Vec::new(), Vec::new())) }; - let columns = t.column_names.as_ref().ok_or_else(|| "cannot read Adobe_AdditionalMetadata columns".to_string())?; - let rows = self.db.read_table(t.rootpage, columns.len()).map_err(|e| format!("Adobe_AdditionalMetadata: {e:?}"))?; + let columns = t.column_names.as_ref().ok_or("cannot read its columns")?; + let rows = self.db.read_table(t.rootpage, columns.len())?; if rows.len() > 1_000_000 { - return Err("Adobe_AdditionalMetadata: more than one million records".into()); + return Err("more than one million records".into()); } let mut warnings = Vec::new(); let mut out = Vec::with_capacity(rows.len()); @@ -195,7 +205,8 @@ pub struct SkippedImage { pub reason: SkipReason, } -/// Why a catalog image was not imported. Lightroom leaves such records behind and ignores them. +/// Why a catalog image was not imported. Lightroom leaves incomplete records behind and ignores +/// them; contradictory ones come from a damaged catalog. Either costs that image, not the import. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum SkipReason { @@ -209,6 +220,12 @@ pub enum SkipReason { IncompletePath, /// A virtual copy whose master was skipped. MasterSkipped, + /// A virtual copy whose master is not in the catalog. + MissingMaster, + /// A virtual copy whose master is itself a virtual copy (or the copy itself). + MasterIsCopy, + /// An image whose id an earlier image of the catalog has: the first one is imported. + DuplicateId, } #[derive(Clone, Default, Serialize, Deserialize)] @@ -217,24 +234,27 @@ pub(crate) struct ImportIndex { pub(crate) collections: BTreeMap, } +/// The library's record of earlier imports (`Interop/lightroom-index.json`; none yet: empty). An +/// error names the file: it is the library's, not the catalog's. pub(crate) fn load_index(path: Option<&Path>) -> crate::Result { match path { Some(path) => { + let failed = |why: String| crate::EngineError::Other(format!("can't read the Lightroom import index {}: {why}", path.display())); let file = match std::fs::File::open(path) { Ok(file) => file, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(ImportIndex::default()), - Err(e) => return Err(error(e.to_string())), + Err(e) => return Err(failed(e.to_string())), }; - if file.metadata().map_err(|e| error(e.to_string()))?.len() > 16 * 1024 * 1024 { - return Err(error("Lightroom import index exceeds 16 MiB")); + if file.metadata().map_err(|e| failed(e.to_string()))?.len() > 16 * 1024 * 1024 { + return Err(failed("it exceeds 16 MiB".into())); } let mut bytes = Vec::new(); use std::io::Read; - file.take(16 * 1024 * 1024 + 1).read_to_end(&mut bytes).map_err(|e| error(e.to_string()))?; + file.take(16 * 1024 * 1024 + 1).read_to_end(&mut bytes).map_err(|e| failed(e.to_string()))?; if bytes.len() > 16 * 1024 * 1024 { - return Err(error("Lightroom import index exceeds 16 MiB")); + return Err(failed("it exceeds 16 MiB".into())); } - serde_json::from_slice(&bytes).map_err(|e| error(format!("invalid Lightroom import index: {e}"))) + serde_json::from_slice(&bytes).map_err(|e| failed(format!("it is damaged: {e}"))) } None => Ok(ImportIndex::default()), } @@ -249,45 +269,113 @@ fn identity(data: &CatalogImport, photo: &CatalogPhoto) -> String { if photo.uuid.is_empty() { format!("{}:{}", key(&data.source), photo.source_id) } else { photo.uuid.clone() } } -fn validate(data: &CatalogImport) -> Result<(), String> { - let photos: HashMap<_, _> = data.photos.iter().map(|p| (p.source_id, p)).collect(); - if photos.len() != data.photos.len() { - return Err("duplicate source photo ids".into()); +/// Leave out the catalog's contradictory records, so one bad record costs that record and not the +/// import (#1588). An image with an id an earlier image has, and a virtual copy whose master is not +/// in the catalog or is itself a virtual copy, are skipped and listed in `skipped`. A collection +/// hierarchy that loops or is deeper than [`MAX_DEPTH`] is cut, the collection where it is cut +/// going to the top level with a warning. +/// +/// Called where the catalog is read and again where its photos become records, so neither route +/// can keep one; the second pass finds nothing. +pub(crate) fn skip_inconsistent_records(data: &mut CatalogImport) { + let mut skipped = Vec::new(); + let mut seen = HashSet::new(); + data.photos.retain(|p| { + if seen.insert(p.source_id) { + return true; + } + skipped.push(SkippedImage { image: p.source_id, reason: SkipReason::DuplicateId }); + false + }); + // whether each image is a virtual copy (`masterImage` is 0 for a master) + let is_copy: HashMap = data.photos.iter().map(|p| (p.source_id, number(&p.image, "masterImage") != 0)).collect(); + data.photos.retain(|p| { + let master = number(&p.image, "masterImage"); + let reason = match is_copy.get(&master) { + _ if master == 0 => return true, + Some(false) => return true, + Some(true) => SkipReason::MasterIsCopy, + None => SkipReason::MissingMaster, + }; + skipped.push(SkippedImage { image: p.source_id, reason }); + false + }); + data.skipped.extend(skipped); + let cut = collection_cuts(&data.collections); + if cut.is_empty() { + return; } - for photo in &data.photos { - let master = number(&photo.image, "masterImage"); - if master != 0 - && (master == photo.source_id - || !photos.contains_key(&master) - || photos.get(&master).is_some_and(|p| number(&p.image, "masterImage") != 0)) - { - return Err(format!("invalid virtual copy master for {}", photo.source_id)); + for collection in &mut data.collections { + if let Some(why) = cut.get(&number(collection, "id_local")) { + collection.insert("parent".into(), json!(0)); + data.warnings.push(format!("collection “{}”: {why}; imported at the top level", text(collection, "name"))); } } - let collections: HashMap<_, _> = data.collections.iter().map(|r| (number(r, "id_local"), r)).collect(); - for id in collections.keys() { - let mut seen = HashSet::new(); - let mut at = *id; - while let Some(r) = collections.get(&at) { - if seen.len() >= 64 || !seen.insert(at) { - return Err("cyclic or overly deep collection hierarchy".into()); - } - at = number(r, "parent"); - if at == 0 { +} + +/// The collections whose parent link must go for the hierarchy to be a tree no deeper than +/// [`MAX_DEPTH`], and why. A loop is cut at its oldest collection (the lowest id: Lightroom numbers +/// records as they are made, so it is most likely the loop's real top); a chain too deep is cut +/// every [`MAX_DEPTH`] levels from its top, the collection there going to the top level. Each +/// chain is followed once. +fn collection_cuts(collections: &[Row]) -> HashMap { + let mut parents: HashMap = collections.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect(); + let ids: Vec = collections.iter().map(|r| number(r, "id_local")).filter(|id| *id != 0).collect(); + let mut cut = HashMap::new(); + // loops: a collection met again on the chain being followed closes one + let mut done = HashSet::new(); + for &start in &ids { + let mut chain = Vec::new(); + let mut on_chain = HashMap::new(); + let mut at = start; + while at != 0 && !done.contains(&at) { + let Some(&parent) = parents.get(&at) else { break }; + if let Some(&i) = on_chain.get(&at) { + if let Some(&top) = chain.get(i..).and_then(|looped: &[i64]| looped.iter().min()) { + parents.insert(top, 0); + cut.insert(top, "its parent collections form a loop"); + } break; } + on_chain.insert(at, chain.len()); + chain.push(at); + at = parent; } + done.extend(chain); } - Ok(()) -} - -pub(crate) fn validate_for_job(data: &CatalogImport) -> Result<(), String> { - validate(data) + // depth from the top, now that no chain loops (bounded all the same) + let mut depth: HashMap = HashMap::new(); + for &start in &ids { + let mut chain = Vec::new(); + let mut at = start; + let top = loop { + if let Some(&known) = depth.get(&at) { + break known + 1; + } + match parents.get(&at) { + Some(&parent) if at != 0 && chain.len() <= ids.len() => { + chain.push(at); + at = parent; + } + // `chain`'s last collection is at the top level + _ => break 0, + } + }; + for (i, id) in chain.into_iter().rev().enumerate() { + depth.insert(id, top + i); + } + } + for (id, d) in depth { + if d > 0 && d.is_multiple_of(MAX_DEPTH) { + cut.insert(id, "it is nested more than 64 collections deep"); + } + } + cut } fn bytes(path: &Path) -> Result, String> { use std::io::Read; - let f = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let f = std::fs::File::open(path).map_err(|e| e.to_string())?; let len = f.metadata().map_err(|e| e.to_string())?.len(); if len > MAX_FILE { return Err("catalog or WAL exceeds 4 GiB import limit".into()); @@ -429,7 +517,7 @@ fn original_path(root: &str, folder: &str, name: &str, catalog: &Path) -> (Strin } /// Inspect `.lrcat` plus committed WAL pages without modifying either source file. -pub fn read(path: &Path) -> Result { +pub fn read(path: &Path) -> crate::Result { let cancel = AtomicBool::new(false); let total = AtomicUsize::new(0); let done = AtomicUsize::new(0); @@ -437,47 +525,58 @@ pub fn read(path: &Path) -> Result { } /// Read a Lightroom Classic catalog for import, counting the tables read in `total` / `done` and -/// stopping when `cancel` is set. Images whose catalog records are incomplete are left out and -/// listed in [`CatalogImport::skipped`] instead of failing the read. -pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, done: &AtomicUsize) -> Result { +/// stopping when `cancel` is set ([`crate::EngineError::Cancelled`]). A bad record costs that +/// record, not the read: images whose records are incomplete or contradictory are left out and +/// listed in [`CatalogImport::skipped`], a looping keyword or collection hierarchy is cut with a +/// warning. Only a catalog that can't be read, or whose database or required tables are broken, +/// is an error, naming the file. +pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, done: &AtomicUsize) -> crate::Result { // 13 catalog tables plus one validation stage; ImportJob adds one unit per original path. total.store(14, Ordering::Relaxed); done.store(0, Ordering::Relaxed); ensure_read_active(cancel)?; - let before = std::fs::metadata(path).map_err(|e| e.to_string())?; + let before = std::fs::metadata(path).map_err(|e| unreadable(path, e))?; let wal_path = PathBuf::from(format!("{}-wal", path.display())); let wal_before = std::fs::metadata(&wal_path).ok().map(|m| (m.len(), m.modified().ok())); - let main = FileSource::open(path)?; + let main = FileSource::open(path).map_err(|e| unreadable(path, e))?; + let wal_error = |e: String| format!("its write-ahead log {}: {e}", wal_path.display()); let wal = match std::fs::metadata(&wal_path) { - Ok(_) => bytes(&wal_path)?, + Ok(_) => bytes(&wal_path).map_err(|e| unreadable(path, wal_error(e)))?, Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(), - Err(e) => return Err(e.to_string()), + Err(e) => return Err(unreadable(path, wal_error(e.to_string()))), }; - let wal_len = committed_wal_len(main.header(), &wal)?; + let wal_len = committed_wal_len(main.header(), &wal).map_err(|e| damaged(path, wal_error(e)))?; ensure_read_active(cancel)?; - let db = Database::open_file_with_wal(main, &wal[..wal_len]).map_err(|e| format!("invalid SQLite catalog: {e:?}"))?; - let after = std::fs::metadata(path).map_err(|e| e.to_string())?; + let db = Database::open_file_with_wal(main, &wal[..wal_len]).map_err(|e| damaged(path, format!("not a readable SQLite database: {e}")))?; + let after = std::fs::metadata(path).map_err(|e| unreadable(path, e))?; let wal_after = std::fs::metadata(&wal_path).ok().map(|m| (m.len(), m.modified().ok())); if before.len() != after.len() || before.modified().ok() != after.modified().ok() || wal_before != wal_after { - return Err("catalog changed during reading; close Lightroom and retry".into()); + return Err(unreadable(path, "it changed during reading; close Lightroom and retry")); } - let reader = Reader { tables: db.live_tables()?, db }; + let reader = Reader { tables: db.live_tables().map_err(|e| damaged(path, e))?, db }; let mut warnings = Vec::new(); - let table = |name: &str, required: bool| -> Result, String> { + // a table every catalog has: without it, or with it broken, there is nothing to import + let table = |name: &str| -> crate::Result> { ensure_read_active(cancel)?; - let rows = reader.table(name, required)?; + if !reader.has(name) { + return Err(crate::EngineError::Other(format!( + "{} is not a Lightroom Classic catalog (or is damaged): it has no {name} table", + path.display() + ))); + } + let rows = reader.table(name).map_err(|e| damaged(path, format!("table {name} can't be read: {e}")))?; done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; - let optional_table = |name: &str, warnings: &mut Vec| -> Result, String> { + let optional_table = |name: &str, warnings: &mut Vec| -> crate::Result> { ensure_read_active(cancel)?; - let rows = reader.optional_table(name, warnings)?; + let rows = reader.optional_table(name, warnings); done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; - let roots: HashMap<_, _> = table("AgLibraryRootFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let folders: HashMap<_, _> = table("AgLibraryFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let files: HashMap<_, _> = table("AgLibraryFile", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let roots: HashMap<_, _> = table("AgLibraryRootFolder")?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let folders: HashMap<_, _> = table("AgLibraryFolder")?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let files: HashMap<_, _> = table("AgLibraryFile")?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); let develops: HashMap<_, _> = optional_table("Adobe_imageDevelopSettings", &mut warnings)? .into_iter() .map(|r| (number(&r, "image"), text(&r, "text").to_string())) @@ -495,23 +594,19 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, let metadata: HashMap<_, _> = metadata_rows.into_iter().map(|r| (number(&r, "image"), r)).collect(); let keyword_rows: HashMap<_, _> = optional_table("AgLibraryKeyword", &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); let mut keywords: HashMap> = HashMap::new(); + // keywords whose looping hierarchy was reported, so the warning comes once per keyword + let mut looped = HashSet::new(); for r in optional_table("AgLibraryKeywordImage", &mut warnings)? { ensure_read_active(cancel)?; - let mut parts = Vec::new(); - let mut at = number(&r, "tag"); - let mut seen = HashSet::new(); - while at != 0 { - if parts.len() >= 64 || !seen.insert(at) { - return Err("cyclic or overly deep keyword hierarchy".into()); - } - let Some(k) = keyword_rows.get(&at) else { break }; - let name = text(k, "name"); - if !name.is_empty() { - parts.push(name.to_string()); - } - at = number(k, "parent"); + let tag = number(&r, "tag"); + let (parts, cut) = keyword_path(tag, &keyword_rows); + if cut && looped.insert(tag) { + let name = keyword_rows.get(&tag).map_or("", |k| text(k, "name")); + warnings.push(format!( + "keyword “{name}”: its parent keywords form a loop or are nested more than 64 deep; imported as “{}”", + parts.join("|") + )); } - parts.reverse(); if !parts.is_empty() { keywords.entry(number(&r, "image")).or_default().push(parts.join("|")); } @@ -559,7 +654,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, // these behind and ignores them); they and their virtual copies are skipped and reported // instead of failing the import let mut orphans = HashSet::new(); - for image in table("Adobe_images", true)? { + for image in table("Adobe_images")? { ensure_read_active(cancel)?; let id = number(&image, "id_local"); let record = files.get(&number(&image, "rootFile")).ok_or(SkipReason::MissingFile).and_then(|file| { @@ -612,15 +707,40 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, } drop_copies_of(&mut out, &orphans); refuse_non_media(&mut out); + skip_inconsistent_records(&mut out); ensure_read_active(cancel)?; - reader.db.ensure_unchanged()?; + reader.db.ensure_unchanged().map_err(|e| unreadable(path, e))?; let wal_after = std::fs::metadata(&wal_path).ok().map(|m| (m.len(), m.modified().ok())); if wal_before != wal_after { - return Err("catalog changed during reading; close Lightroom and retry".into()); + return Err(unreadable(path, "it changed during reading; close Lightroom and retry")); } Ok(out) } +/// A keyword's path from the top of its hierarchy (`Travel|Goa`), and whether its parent chain had +/// to be cut: when it loops, the path stops before the first keyword that comes again; when it is +/// deeper than [`MAX_DEPTH`], at that depth. +fn keyword_path(tag: i64, keywords: &HashMap) -> (Vec, bool) { + let mut parts = Vec::new(); + let mut seen = HashSet::new(); + let mut at = tag; + let mut cut = false; + while at != 0 { + if seen.len() >= MAX_DEPTH || !seen.insert(at) { + cut = true; + break; + } + let Some(k) = keywords.get(&at) else { break }; + let name = text(k, "name"); + if !name.is_empty() { + parts.push(name.to_string()); + } + at = number(k, "parent"); + } + parts.reverse(); + (parts, cut) +} + /// Drop the virtual copies whose master was skipped, adding them to the skipped images: a copy has /// no original of its own. fn drop_copies_of(data: &mut CatalogImport, masters: &HashSet) { @@ -683,8 +803,8 @@ pub(crate) fn refuse_non_media(data: &mut CatalogImport) { data.warnings.extend(warnings); } -fn ensure_read_active(cancel: &AtomicBool) -> Result<(), String> { - if cancel.load(Ordering::Relaxed) { Err("Lightroom import cancelled".into()) } else { Ok(()) } +fn ensure_read_active(cancel: &AtomicBool) -> crate::Result<()> { + if cancel.load(Ordering::Relaxed) { Err(crate::EngineError::Cancelled("Lightroom import cancelled".into())) } else { Ok(()) } } fn mapped_settings( @@ -824,8 +944,10 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) -> let archive_dir = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop")); let index_path = archive_dir.as_ref().map(|p| p.join("lightroom-index.json")); let mut index = load_index(index_path.as_deref())?; - let archive_path = - archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map(|stored| stored.path).map_err(error)).transpose()?; + let archive_path = archive_dir + .as_ref() + .map(|dir| crate::lightroom_archive::store(dir, &data).map(|stored| stored.path).map_err(crate::EngineError::Other)) + .transpose()?; let undo0 = s.undo.len(); let existing: HashMap<_, _> = s.catalog.photos().filter(|p| p.copy_of.is_none()).filter_map(|p| source_path(p).map(|path| (key(path), p.id))).collect(); @@ -842,8 +964,8 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) -> apply_prepared(s, data, ApplyPrepared { update_existing, files, index: &mut index, archive_path, missing_sources: &missing_sources, undo0 })?; if let Some(path) = index_path { s.persist()?; - let bytes = serde_json::to_vec(&applied.index).map_err(|e| error(e.to_string()))?; - lightcraft_catalog::safe_file::write_atomic(&path, &bytes).map_err(|e| error(e.to_string()))?; + let bytes = serde_json::to_vec(&applied.index).map_err(|e| crate::EngineError::Other(e.to_string()))?; + lightcraft_catalog::safe_file::write_atomic(&path, &bytes).map_err(|e| crate::EngineError::Other(e.to_string()))?; } Ok(applied.report) } @@ -940,9 +1062,10 @@ fn stage_collections( /// (added, missing, failed, warnings and skipped images). pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, context: ApplyPrepared<'_>) -> crate::Result { let ApplyPrepared { update_existing, files, index, archive_path, missing_sources, undo0 } = context; - // nothing but a file type LightCraft reads becomes a record, whichever route got here (#2135) + // nothing but a file type LightCraft reads becomes a record, whichever route got here (#2135), + // nor a contradictory one (#1588) refuse_non_media(&mut data); - validate(&data).map_err(error)?; + skip_inconsistent_records(&mut data); let mut warnings = data.warnings.clone(); let duplicates: HashMap<_, _> = files.duplicates.iter().filter_map(|d| d.existing.map(|id| (key(&d.path), PhotoId(id)))).collect(); let mut by_path: HashMap<_, _> = @@ -963,6 +1086,8 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co let copy_masters: HashSet<_> = data.photos.iter().map(|p| number(&p.image, "masterImage")).filter(|id| *id != 0).collect(); let refused: HashSet<_> = data.photos.iter().filter(|p| matches!(p.original, Original::Refused(_))).map(|p| p.source_id).collect(); let mut planned: HashMap = HashMap::new(); + // virtual copies whose master didn't become a record (`skip_inconsistent_records` leaves none) + let mut masterless = Vec::new(); for src in photos { let master = number(&src.image, "masterImage"); if master == 0 && missing_sources.contains(&key(&src.path)) { @@ -983,12 +1108,13 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co let mut p = if let Some(id) = existing_id.and_then(|id| s.catalog.photo(id)) { (**id).clone() } else if master != 0 { - let master_id = ids.get(&master).copied().ok_or_else(|| error(format!("virtual copy {}: missing master", src.source_id)))?; - let mut p = planned - .get(&master_id) - .cloned() - .or_else(|| s.catalog.photo(master_id).map(|p| (**p).clone())) - .ok_or_else(|| error("virtual copy master is unavailable"))?; + let master_record = + ids.get(&master).copied().and_then(|id| planned.get(&id).cloned().or_else(|| s.catalog.photo(id).map(|p| (**p).clone()))); + let Some(mut p) = master_record else { + masterless.push(SkippedImage { image: src.source_id, reason: SkipReason::MissingMaster }); + continue; + }; + let master_id = p.id; p.id = s.catalog.alloc_photo_id(); p.copy_of = Some(master_id); p.copy_name = Some(text(&src.image, "copyName").to_string()); @@ -1100,6 +1226,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co } by_path.entry(key(&src.path)).or_insert(photo_id); } + data.skipped.extend(masterless); let album_count = stage_collections(s, &data, index, &ids, &mut ops, &mut warnings); if !ops.is_empty() { s.commit("Import Lightroom Catalog", Op::Batch { ops })?; diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 86640c49dee..a17659b01bb 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -158,25 +158,90 @@ fn imports_copies_collections_ratings_and_mapped_edits_in_one_undo_step() { assert!(data.photos[1].settings.contains("CameraProfile")); // unmapped source stays intact } #[test] -fn preserves_existing_edits_and_rejects_invalid_structure_before_mutation() { +fn preserves_existing_edits_and_rejects_unbounded_settings() { let mut s = crate::Session::new(); let data = sample(); apply(&mut s, data.clone(), false).unwrap(); let id = s.catalog.photos().find(|p| p.copy_of.is_none()).unwrap().id; s.set_develop(id, lightcraft_develop::DevelopSettings::default(), "Personal edit").unwrap(); - let r = apply(&mut s, data.clone(), false).unwrap(); + let r = apply(&mut s, data, false).unwrap(); assert!(r["preservedExistingEdits"].as_u64().unwrap() > 0); assert_eq!(s.catalog.photo(id).unwrap().develop.light.exposure, 0.0); - let before = s.catalog.to_snapshot(); - let mut cyclic = data; - cyclic.collections[0].insert("parent".into(), json!(10)); - assert!(apply(&mut s, cyclic, false).is_err()); - assert_eq!(s.catalog.to_snapshot(), before); assert!( mapped_settings(&format!("{}0{}", "{".repeat(1000), "}".repeat(1000)), crate::crs::Target::RawAbsolute, 1.0, Orientation::Normal, 1.5) .is_err() ); } +/// A damaged catalog used to fail the whole import (#1588): a repeated image id, or a virtual copy +/// whose master is gone or is itself a copy, now costs that image, and the rest is imported. +#[test] +fn contradictory_images_are_skipped_and_the_rest_imports() { + let mut data = sample(); + let mut twin = data.photos[1].clone(); + twin.uuid = "twin".into(); + twin.path = "/missing/twin.ARW".into(); + data.photos.push(twin); + for (id, master) in [(5, 99), (6, 2), (7, 7)] { + let mut copy = data.photos[0].clone(); + copy.source_id = id; + copy.uuid = format!("copy-{id}"); + copy.image = row(json!({"id_local": id, "masterImage": master, "copyName": "Bad"})); + data.photos.push(copy); + } + let mut s = crate::Session::new(); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["photos"], 2, "the master and its copy: {r}"); + assert_eq!( + r["skipped"], + json!([ + {"image": 1, "reason": "duplicateId"}, + {"image": 5, "reason": "missingMaster"}, + {"image": 6, "reason": "masterIsCopy"}, + {"image": 7, "reason": "masterIsCopy"}, + ]) + ); + assert_eq!(s.catalog.len(), 2); + assert!(s.catalog.photos().all(|p| source_path(p) == Some("/missing/test.ARW")), "the first image with id 1 is the one imported"); + assert!(s.catalog.albums().any(|a| a.name == "Keepers")); + assert_eq!(s.undo.len(), 1); +} + +/// A looping (or too deep) collection hierarchy used to fail the whole import: it is cut at the +/// loop's oldest collection, which goes to the top level with a warning. +#[test] +fn a_looping_collection_hierarchy_is_cut_not_fatal() { + let mut data = sample(); + data.collections[0].insert("parent".into(), json!(10)); + data.collections.push(row(json!({"id_local": 11, "parent": 11, "name": "Self", "creationId": "collection"}))); + // a chain of 70 sets, each in the one before + data.collections.extend((100..170).map(|id| { + row(json!({"id_local": id, "parent": if id == 100 { 0 } else { id - 1 }, "name": format!("Set {id}"), "creationId": "collection.group"})) + })); + let mut s = crate::Session::new(); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["photos"], 2); + assert_eq!(r["collections"], 73); + let album = |name: &str| s.catalog.albums().find(|a| a.name == name).unwrap(); + assert_eq!(album("Travel").parent, None, "the loop's oldest collection is at the top level"); + assert_eq!(album("Keepers").parent, Some(album("Travel").id)); + assert_eq!(album("Keepers").photos.len(), 2); + assert_eq!(album("Self").parent, None); + assert_eq!(album("Set 164").parent, None, "cut once, 64 below the top"); + assert_eq!(album("Set 165").parent, Some(album("Set 164").id)); + assert_eq!(album("Set 163").parent, Some(album("Set 162").id)); + assert_eq!(album("Set 101").parent, Some(album("Set 100").id)); + let warnings: Vec<_> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!( + warnings, + [ + "collection “Travel”: its parent collections form a loop; imported at the top level", + "collection “Self”: its parent collections form a loop; imported at the top level", + "collection “Set 164”: it is nested more than 64 collections deep; imported at the top level", + ] + ); + assert_eq!(s.undo.len(), 1); +} + #[test] fn compressed_xmp_is_bounded_and_settings_are_data_only() { let packet = b"example"; @@ -619,7 +684,9 @@ fn native_catalog_with_last_table_page(tables: &[(&str, &str, Vec)], l /// table's root page. fn native_catalog_rows(tables: &[(&str, &str, Vec>)], last_page: Option) -> Vec { use SqlValue::{Integer as I, Text as T}; - let mut bytes = vec![0u8; 5 * 2048]; + // the schema page, then one page per table + let pages = tables.len() + 1; + let mut bytes = vec![0u8; pages * 2048]; bytes[..16].copy_from_slice(b"SQLite format 3\0"); bytes[16..18].copy_from_slice(&2048u16.to_be_bytes()); bytes[18] = 1; @@ -627,7 +694,7 @@ fn native_catalog_rows(tables: &[(&str, &str, Vec>)], last_page: O bytes[21] = 64; bytes[22] = 32; bytes[23] = 32; - bytes[28..32].copy_from_slice(&5u32.to_be_bytes()); + bytes[28..32].copy_from_slice(&(pages as u32).to_be_bytes()); bytes[44..48].copy_from_slice(&4u32.to_be_bytes()); bytes[56..60].copy_from_slice(&1u32.to_be_bytes()); let mut schema = Vec::new(); @@ -697,7 +764,7 @@ fn reads_native_sqlite_tables_without_lightroom_or_external_processes() { assert!(session.catalog.is_empty()); } std::fs::write(&path, b"bad catalog").unwrap(); - assert!(read(&path).is_err()); + assert_eq!(read(&path).unwrap_err().kind(), crate::ErrorKind::Other); std::fs::remove_file(path).unwrap(); } @@ -755,7 +822,80 @@ fn a_virtual_copy_of_a_skipped_master_is_skipped_too() { catalog.skipped, [SkippedImage { image: 1, reason: SkipReason::MissingFile }, SkippedImage { image: 2, reason: SkipReason::MasterSkipped }] ); - validate(&catalog).unwrap(); + let mut again = catalog.clone(); + skip_inconsistent_records(&mut again); + assert_eq!(again.skipped, catalog.skipped, "the second pass finds nothing"); +} + +/// A keyword whose parents loop used to fail the whole read; it is now cut where the loop comes +/// back, with one warning however many photos have it. +#[test] +fn a_looping_keyword_hierarchy_is_cut_not_fatal() { + use SqlValue::{Integer as I, Null as N, Text as T}; + let mut tables = one_row(photo_tables(("/catalog/", ""))); + tables.push(( + "AgLibraryKeyword", + "id_local INTEGER PRIMARY KEY, name, parent", + vec![vec![N, T("Travel".into()), I(2)], vec![N, T("Goa".into()), I(1)]], + )); + tables.push(("AgLibraryKeywordImage", "id_local INTEGER PRIMARY KEY, image, tag", vec![vec![N, I(1), I(1)], vec![N, I(1), I(1)]])); + let catalog = read_tables(&tables, "keyword-loop"); + assert_eq!(catalog.photos[0].keywords, ["Goa|Travel", "Goa|Travel"]); + assert_eq!(catalog.warnings, ["keyword “Travel”: its parent keywords form a loop or are nested more than 64 deep; imported as “Goa|Travel”"]); + assert!(catalog.skipped.is_empty()); +} + +/// A catalog that can't be read at all is still an error, but it names the file and says what is +/// wrong (not "invalid parameters"), and nothing is changed. +#[test] +fn an_unreadable_catalog_is_an_error_naming_it_and_changes_nothing() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-damaged-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let source = dir.join("source.lrcat"); + let mut no_files = photo_tables(("/catalog/", "")); + no_files.remove(2); + let cases = [ + // the Adobe_images table points past the end of the file + (native_catalog_with_last_table_page(&photo_tables(("/catalog/", "")), Some(99)), "is damaged: table Adobe_images can't be read: "), + (native_catalog(&no_files), "is not a Lightroom Classic catalog (or is damaged): it has no AgLibraryFile table"), + (b"bad catalog".to_vec(), "can't be read: it is too short to be a SQLite database"), + (vec![b'x'; 4096], "is damaged: not a readable SQLite database: "), + ]; + for (bytes, expected) in cases { + std::fs::write(&source, bytes).unwrap(); + let mut s = crate::Session::new(); + apply(&mut s, sample(), false).unwrap(); + let before = s.catalog.to_snapshot(); + let undo = s.undo.len(); + let e = import(&mut s, &source, false).unwrap_err(); + assert_eq!(e.kind(), crate::ErrorKind::Other, "{e}"); + let message = e.to_string(); + assert!(message.contains(&*source.to_string_lossy()) && message.contains(expected), "{message}"); + assert_eq!(s.catalog.to_snapshot(), before); + assert_eq!(s.undo.len(), undo); + } + let e = import(&mut crate::Session::new(), &dir.join("gone.lrcat"), false).unwrap_err(); + assert_eq!(e.kind(), crate::ErrorKind::Other, "{e}"); + assert!(e.to_string().starts_with(&format!("the Lightroom catalog {} can't be read: ", dir.join("gone.lrcat").display())), "{e}"); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// The library's import index that can't be read is an error naming it, not "invalid parameters". +#[test] +fn an_unreadable_import_index_is_an_error_naming_it() { + let dir = std::env::temp_dir().join(format!("lightcraft-lr-index-unreadable-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let index = dir.join("lightroom-index.json"); + std::fs::create_dir_all(&index).unwrap(); + let Err(e) = load_index(Some(&index)) else { panic!("a folder is not an index") }; + assert_eq!(e.kind(), crate::ErrorKind::Other, "{e}"); + assert!(e.to_string().starts_with(&format!("can't read the Lightroom import index {}: ", index.display())), "{e}"); + std::fs::remove_dir(&index).unwrap(); + std::fs::write(&index, b"{not json").unwrap(); + let Err(e) = load_index(Some(&index)) else { panic!("not an index") }; + assert!(e.to_string().contains("it is damaged"), "{e}"); + std::fs::remove_dir_all(dir).unwrap(); } #[test] @@ -919,7 +1059,7 @@ fn oversized_optional_table_warns_and_is_skipped() { let db = Database::open_with_wal(main, &[]).unwrap(); let reader = Reader { db, tables: vec![LiveTable { name: "optional_history".into(), rootpage: 2, column_names: Some(vec!["payload".into()]) }] }; let mut warnings = Vec::new(); - let rows = reader.optional_table("optional_history", &mut warnings).unwrap(); + let rows = reader.optional_table("optional_history", &mut warnings); assert!(rows.is_empty()); assert!(warnings.iter().any(|warning| warning.contains("optional_history"))); } diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 882b76eb28b..593f7579f46 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -20,14 +20,11 @@ use crate::lightroom_catalog::{self, CatalogImport, ImportIndex}; const COMMAND: &str = "library.importLightroom"; const MAX_INDEX_BYTES: usize = 16 * 1024 * 1024; -fn error(message: impl Into) -> crate::EngineError { - crate::EngineError::BadParams { cmd: COMMAND.into(), msg: message.into() } -} - /// The import was cancelled ([`crate::ErrorKind::Cancelled`]: not a failure). The message is the /// one it always had, so control-channel and MCP clients see the same `error` text. fn cancelled() -> crate::EngineError { - crate::EngineError::Cancelled(error("Lightroom import cancelled").to_string()) + let message = crate::EngineError::BadParams { cmd: COMMAND.into(), msg: "Lightroom import cancelled".into() }; + crate::EngineError::Cancelled(message.to_string()) } /// Save the recovery archive. It is best-effort: nothing reads it back during import, so an archive @@ -168,7 +165,7 @@ impl LightroomArchiveFinalization { pub fn finish(self) -> crate::Result<()> { let (Some(path), Some(bytes)) = (self.path, self.bytes) else { return Ok(()) }; if bytes.len() > MAX_INDEX_BYTES { - return Err(error("Lightroom import index exceeds 16 MiB")); + return Err(crate::EngineError::Other(format!("could not write the Lightroom import index {}: it exceeds 16 MiB", path.display()))); } let failed = |e: &dyn std::fmt::Display| crate::EngineError::Other(format!("could not write the Lightroom import index {}: {e}", path.display())); @@ -300,10 +297,10 @@ impl LightroomJob { if cancel.load(Ordering::Relaxed) { return Err(cancelled()); } - // (reading stops with a message when `cancel` is set: the flag says it was cancelled) + // (reading stops when `cancel` is set: the flag says it was cancelled; a catalog that can't be + // read is an error naming it, and a bad record is skipped, not an error) let mut data = lightroom_catalog::read_with_progress(&self.path, cancel, &self.progress.catalog_total, &self.progress.catalog_done) - .map_err(|e| if cancel.load(Ordering::Relaxed) { cancelled() } else { error(e) })?; - lightroom_catalog::validate_for_job(&data).map_err(error)?; + .map_err(|e| if cancel.load(Ordering::Relaxed) { cancelled() } else { e })?; if cancel.load(Ordering::Relaxed) { return Err(cancelled()); } @@ -344,7 +341,7 @@ pub fn commit_prepared(s: &mut crate::Session, mut prepared: PreparedLightroom) } if !prepared.token.matches(s) { prepared.normal.rollback(); - return Err(error("Lightroom import belongs to a different open library")); + return Err(crate::EngineError::Other("Lightroom import belongs to a different open library".into())); } // A command-scoped Lightroom import must never rewrite source XMP sidecars. Direct depth-0 // callers do not set this transient flag, so they cannot affect a later command. @@ -370,7 +367,7 @@ pub fn commit_prepared(s: &mut crate::Session, mut prepared: PreparedLightroom) }, )?; let path = prepared.token.library_dir().map(|dir| dir.join("Interop/lightroom-index.json")); - let bytes = if path.is_some() { Some(serde_json::to_vec(&applied.index).map_err(|e| error(e.to_string()))?) } else { None }; + let bytes = if path.is_some() { Some(serde_json::to_vec(&applied.index).map_err(|e| crate::EngineError::Other(e.to_string()))?) } else { None }; Ok(LightroomCompletion { report: applied.report, finalization: LightroomArchiveFinalization { path, bytes } }) } @@ -538,6 +535,9 @@ mod tests { assert_eq!(e.to_string(), "invalid parameters for `library.importLightroom`: Lightroom import cancelled"); let Err(e) = job.prepare(&AtomicBool::new(false)) else { panic!("no such catalog") }; assert_ne!(e.kind(), crate::ErrorKind::Cancelled, "{e}"); + // a catalog that can't be read is not "invalid parameters": the error names it + assert_eq!(e.kind(), crate::ErrorKind::Other, "{e}"); + assert!(e.to_string().starts_with("the Lightroom catalog /nonexistent/cancelled.lrcat can't be read: "), "{e}"); } #[test] diff --git a/crates/engine/src/lightroom_sqlite.rs b/crates/engine/src/lightroom_sqlite.rs index 60e03281c92..c8353513e0f 100644 --- a/crates/engine/src/lightroom_sqlite.rs +++ b/crates/engine/src/lightroom_sqlite.rs @@ -37,7 +37,10 @@ impl FileSource { return Err("catalog exceeds 16 GiB import limit".into()); } let mut header = vec![0; 100]; - file.read_exact(&mut header).map_err(|e| format!("cannot read SQLite header: {e}"))?; + file.read_exact(&mut header).map_err(|e| match e.kind() { + std::io::ErrorKind::UnexpectedEof => "it is too short to be a SQLite database".to_string(), + _ => format!("cannot read SQLite header: {e}"), + })?; let source = Self { file: Mutex::new(file), path: path.into(), before, header }; source.ensure_unchanged()?; Ok(source) diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d4..44aa3cf1f8e 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -268,6 +268,7 @@ "{n} preset{}": "Přednastavení: {n}{:.0}", "{count} more warnings.": "Další varování: {count}.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Neimportované obrázky katalogu: {skipped}. Jejich záznamy v katalogu jsou neúplné.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "Neimportované obrázky katalogu: {skipped}. Jejich záznamy v katalogu odporují jiným (opakované ID obrázku nebo virtuální kopie virtuální kopie).", "{photos} catalog records processed; {collections} collections.": "Zpracováno záznamů katalogu: {photos}; kolekcí: {collections}.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Chybějící originály: {missing}. Jejich záznamy jsou v katalogu dostupné; použijte Najít chybějící fotografie a znovu je propojte.", "Applied {name}": "Použito: {name}", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f13647..563a6d5c337 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -270,6 +270,7 @@ "· {in_source} identical copies": "· {in_source} identische Kopien", "{count} more warnings.": "{count} weitere Warnungen.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} Katalogbilder wurden nicht importiert, weil ihre Einträge im Katalog unvollständig sind.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "{skipped} Katalogbilder wurden nicht importiert, weil ihre Einträge im Katalog anderen widersprechen (eine doppelte Bild-ID oder eine virtuelle Kopie einer virtuellen Kopie).", "{photos} catalog records processed; {collections} collections.": "{photos} Katalogeinträge verarbeitet; {collections} Sammlungen.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} Originale fehlen. Ihre Katalogeinträge sind verfügbar; verwende „Fehlende Fotos suchen“, um sie neu zu verknüpfen.", "Applied {name}": "{name} angewendet", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6e..d50733b43b9 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -270,6 +270,7 @@ "· {in_source} identical copies": "· {in_source} copias idénticas", "{count} more warnings.": "{count} advertencias más.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "No se importaron {skipped} imágenes del catálogo porque sus registros en el catálogo están incompletos.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "No se importaron {skipped} imágenes del catálogo porque sus registros en el catálogo contradicen a otros (un ID de imagen repetido o una copia virtual de una copia virtual).", "{photos} catalog records processed; {collections} collections.": "{photos} registros del catálogo procesados; {collections} colecciones.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Faltan {missing} originales. Sus registros del catálogo están disponibles; usa Buscar fotos que faltan para volver a vincularlos.", "Applied {name}": "Se aplicó {name}", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9f..090e21148c3 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -258,6 +258,7 @@ "{sel_n} selected · {counted}": "Valittu: {sel_n} · {counted}", "{size} GB": "{size} Gt", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).", "{stage}… {:.0}%": "{stage}… {:.0}%", "{s} s of AV1 video": "{s} s AV1-videota", "{verb} {n} Photo{}": "{verb} kuvia: {n}{:.0}", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e0..223c23105e5 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -270,6 +270,7 @@ "· {in_source} identical copies": "· {in_source} copies identiques", "{count} more warnings.": "{count} avertissements supplémentaires.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} images du catalogue n’ont pas été importées, car leurs entrées dans le catalogue sont incomplètes.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "{skipped} images du catalogue n’ont pas été importées, car leurs entrées dans le catalogue en contredisent d’autres (un identifiant d’image répété ou une copie virtuelle d’une copie virtuelle).", "{photos} catalog records processed; {collections} collections.": "{photos} entrées du catalogue traitées ; {collections} collections.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} originaux sont manquants. Leurs entrées de catalogue sont disponibles ; utilisez Rechercher les photos manquantes pour rétablir les liens.", "Applied {name}": "{name} appliqué", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221e..cab8198f0de 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -297,6 +297,7 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}: resolusi penuhnya ({full}) memerlukan memori melebihi kapasitas komputer ini", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}, resolusi maksimum untuk panorama (resolusi penuhnya {full})", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).", "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", "Added {n} photo{}": "{n} foto ditambahkan{:.0}", "Could not read {name}: {e}": "Tidak dapat membaca {name}: {e}", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e945..f867edcaa1b 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -251,6 +251,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Eliminare i preset effetto ({n})?{:.0} L'operazione non si può annullare.", "{count} more warnings.": "Altri avvisi: {count}.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} immagini del catalogo non sono state importate perché i loro record nel catalogo sono incompleti.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "{skipped} immagini del catalogo non sono state importate perché i loro record nel catalogo ne contraddicono altri (un ID immagine ripetuto o una copia virtuale di una copia virtuale).", "· {in_source} identical copies": "· copie identiche: {in_source}", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Unione {what} aggiunta a {mp}, la dimensione massima di un panorama (la dimensione piena è {full})", "{n} preset{}": "Preset: {n}{:.0}", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16dc..939360ef902 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -274,6 +274,7 @@ "· {in_source} identical copies": "・同一のコピー {in_source} 件", "{count} more warnings.": "ほかに{count}件の警告があります。", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "カタログ内のレコードが不完全なため、{skipped}件の画像を読み込めませんでした。", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "カタログ内のレコードが他のレコードと矛盾しているため(画像IDの重複、または仮想コピーの仮想コピー)、{skipped}件の画像を読み込めませんでした。", "{photos} catalog records processed; {collections} collections.": "カタログの{photos}件のレコードを処理しました。コレクションは{collections}件です。", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing}件のオリジナルが見つかりません。カタログのレコードは利用できます。「見つからない写真を検索」で再リンクしてください。", "Applied {name}": "{name} を適用しました", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 46036826186..c760ac708f8 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -280,6 +280,7 @@ "new, inside {parent}": "new, inside {parent}", "{count} more warnings.": "{count} more warnings.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "კატალოგის {skipped} სურათი არ დაიმპორტდა, რადგან მათი ჩანაწერები კატალოგში არასრულია.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "კატალოგის {skipped} სურათი არ დაიმპორტდა, რადგან მათი ჩანაწერები კატალოგში სხვა ჩანაწერებს ეწინააღმდეგება (გამეორებული სურათის ID ან ვირტუალური ასლის ვირტუალური ასლი).", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.", "{n} JPEG files": "{n} JPEG files", "{n} pages": "{n} pages", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6e..a8c8b4831f1 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -262,6 +262,7 @@ "{n} preset{}": "Ustawienia: {n}{:.0}", "{count} more warnings.": "Pozostałe ostrzeżenia: {count}.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Nie zaimportowano obrazów z katalogu: {skipped}. Ich rekordy w katalogu są niekompletne.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "Nie zaimportowano obrazów z katalogu: {skipped}. Ich rekordy w katalogu są sprzeczne z innymi (powtórzony identyfikator obrazu lub kopia wirtualna kopii wirtualnej).", "{photos} catalog records processed; {collections} collections.": "Przetworzone rekordy katalogu: {photos}; kolekcje: {collections}.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Brakujące oryginały: {missing}. Ich rekordy w katalogu są dostępne; użyj polecenia Znajdź brakujące zdjęcia, aby je ponownie powiązać.", "Applied {name}": "Zastosowano {name}", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4b..da940ed6a3f 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -274,6 +274,7 @@ "· {in_source} identical copies": "· {in_source} cópias idênticas", "{count} more warnings.": "Mais {count} avisos.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} imagens do catálogo não foram importadas porque seus registros no catálogo estão incompletos.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "{skipped} imagens do catálogo não foram importadas porque seus registros no catálogo contradizem outros (um ID de imagem repetido ou uma cópia virtual de uma cópia virtual).", "{photos} catalog records processed; {collections} collections.": "{photos} registros do catálogo processados; {collections} coleções.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} originais estão ausentes. Seus registros no catálogo estão disponíveis; use Encontrar fotos ausentes para vinculá-los novamente.", "Applied {name}": "{name} aplicado", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af42764..f6093247bd2 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -270,6 +270,7 @@ "· {in_source} identical copies": "· идентичных копий: {in_source}", "{count} more warnings.": "Других предупреждений: {count}.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Не импортированы изображения каталога: {skipped}. Их записи в каталоге неполные.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "Не импортированы изображения каталога: {skipped}. Их записи в каталоге противоречат другим (повторяющийся идентификатор изображения или виртуальная копия виртуальной копии).", "{photos} catalog records processed; {collections} collections.": "Обработано записей каталога: {photos}; коллекций: {collections}.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Не найдены оригиналы: {missing}. Их записи каталога доступны; используйте поиск отсутствующих фотографий, чтобы восстановить ссылки.", "Applied {name}": "Применено: {name}", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c4..5f7d54f2a00 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -297,6 +297,7 @@ "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).", "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", "Added {n} photo{}": "{n} foto tillagda{:.0}", "Could not read {name}: {e}": "Kunde inte läsa {name}: {e}", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a25..1d4fbad4553 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -270,6 +270,7 @@ "· {in_source} identical copies": "· ідентичних копій: {in_source}", "{count} more warnings.": "Інших попереджень: {count}.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Не імпортовано зображення каталогу: {skipped}. Їхні записи в каталозі неповні.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "Не імпортовано зображення каталогу: {skipped}. Їхні записи в каталозі суперечать іншим (повторений ідентифікатор зображення або віртуальна копія віртуальної копії).", "{photos} catalog records processed; {collections} collections.": "Оброблено записів каталогу: {photos}; колекцій: {collections}.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Не знайдено оригінали: {missing}. Їхні записи каталогу доступні; скористайтеся пошуком відсутніх фотографій, щоб відновити посилання.", "Applied {name}": "Застосовано: {name}", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff060..d09139d9e46 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -258,6 +258,7 @@ "{sel_n} selected · {counted}": "Đã chọn {sel_n} · {counted}", "{size} GB": "{size} GB", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).", "{stage}… {:.0}%": "{stage}… {:.0}%", "{s} s of AV1 video": "{s} s of AV1 video", "{verb} {n} Photo{}": "{verb} {n} ảnh{:.0}", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b866..c8b1eb9c896 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -274,6 +274,7 @@ "· {in_source} identical copies": "· {in_source} 个相同副本", "{count} more warnings.": "另有 {count} 条警告。", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "有 {skipped} 张图像未导入,因为它们在目录中的记录不完整。", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "有 {skipped} 张图像未导入,因为它们在目录中的记录与其他记录矛盾(图像 ID 重复,或是虚拟副本的虚拟副本)。", "{photos} catalog records processed; {collections} collections.": "已处理 {photos} 条目录记录;{collections} 个收藏集。", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "有 {missing} 个原始文件缺失。其目录记录可用;请使用“查找缺失照片”重新链接文件。", "Applied {name}": "已应用 {name}", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a2..2726db596dd 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -274,6 +274,7 @@ "· {in_source} identical copies": "· {in_source} 個相同副本", "{count} more warnings.": "另有 {count} 則警告。", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "有 {skipped} 張影像未匯入,因為它們在目錄中的記錄不完整。", + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).": "有 {skipped} 張影像未匯入,因為它們在目錄中的記錄與其他記錄矛盾(影像 ID 重複,或是虛擬副本的虛擬副本)。", "{photos} catalog records processed; {collections} collections.": "已處理 {photos} 筆目錄記錄;{collections} 個收藏集。", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "有 {missing} 個原始檔案遺失。其目錄記錄可用;請使用「尋找遺失相片」重新連結檔案。", "Applied {name}": "已套用 {name}", diff --git a/crates/ui-egui/src/lightroom_import.rs b/crates/ui-egui/src/lightroom_import.rs index 098c989d5cf..fd9e47edbfe 100644 --- a/crates/ui-egui/src/lightroom_import.rs +++ b/crates/ui-egui/src/lightroom_import.rs @@ -186,7 +186,7 @@ fn spawn_inspect( let result = lightcraft_engine::guard::catch("Lightroom inspect", || { lightcraft_engine::lightroom_catalog::read_with_progress(&path, &cancel, &progress.catalog_total, &progress.catalog_done) }) - .and_then(|r| r.map(inspect_report)); + .and_then(|r| r.map(inspect_report).map_err(|e| e.to_string())); let _ = tx.send(Message::Inspected(result)); ctx.request_repaint(); }) @@ -340,13 +340,21 @@ fn result_dialog(value: &Value, summary: &str) -> crate::state::Dialog { missing = missing )); } - // images whose catalog records are incomplete come as data (`skipped`), said here in the UI - // language; their ids are in the report for the CLI and agents - let skipped = report["skipped"].as_array().map_or(0, Vec::len); - if skipped > 0 { + // images whose catalog records are incomplete or contradictory come as data (`skipped`), said + // here in the UI language; their ids and reasons are in the report for the CLI and agents + let skipped = report["skipped"].as_array().map_or(&[][..], Vec::as_slice); + let contradictory = skipped.iter().filter(|s| matches!(s["reason"].as_str(), Some("duplicateId" | "masterIsCopy"))).count(); + let incomplete = skipped.len() - contradictory; + if incomplete > 0 { details.push(crate::i18n::tr_format!( "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - skipped = skipped + skipped = incomplete + )); + } + if contradictory > 0 { + details.push(crate::i18n::tr_format!( + "{skipped} catalog images were not imported because their records in the catalog contradict others (a repeated image id, or a virtual copy of a virtual copy).", + skipped = contradictory )); } if let Some(warning) = value.get("indexWarning").and_then(Value::as_str) { @@ -713,6 +721,21 @@ mod tests { assert_eq!(&en[2..], ["w1", "w2"]); } + /// Images skipped for contradictory records (a damaged catalog, #1588) are their own line. + #[test] + fn contradictory_records_are_their_own_line() { + let value = json!({"report": {"photos": 3, "collections": 0, "skipped": [ + {"image": 7, "reason": "missingMaster"}, + {"image": 8, "reason": "duplicateId"}, + {"image": 9, "reason": "masterIsCopy"}, + ]}}); + crate::i18n::set_language(crate::i18n::Locale::En); + let crate::state::Dialog::LightroomResult { details, .. } = result_dialog(&value, "done") else { panic!("not a Lightroom result") }; + assert_eq!(details.len(), 3, "{details:?}"); + assert_eq!(details[1], "1 catalog images were not imported because their records in the catalog are incomplete."); + assert!(details[2].starts_with("2 catalog images were not imported because their records in the catalog contradict others"), "{details:?}"); + } + #[test] fn skipped_images_do_not_take_the_warning_slots() { let warnings: Vec<_> = (0..10).map(|i| format!("w{i}")).collect(); diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 8bcd350dc63..cb3719cdde9 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -62,11 +62,25 @@ settings are imported. Missing originals remain catalogued for relinking, count separately from failures reading files that are present. Known-missing originals are not probed again. Previously browsed Local records join All Photos even when their originals are offline; their promotion is counted once and undone together with the catalog import. -An image whose file, folder or root folder record is gone from the catalog, or whose original path -is empty (Lightroom leaves these behind and ignores them), is skipped together with its virtual -copies instead of failing the whole import. The result lists them as data (`skipped`: each -image id with its reason, `missingFile`, `missingFolder`, `missingRoot`, `incompletePath` or -`masterSkipped`), also in `library.inspectLightroom`, and the desktop result window says how many in the UI language. +One bad record costs that record, not the import (issue #1588). An image whose file, folder or root folder +record is gone from the catalog, or whose original path is empty (Lightroom leaves these behind and ignores them), +is skipped together with its virtual copies. So are the contradictory records of a damaged catalog: a second +image with an id an earlier image has (the first is imported), and a virtual copy whose master is not in the +catalog or is itself a virtual copy. The result lists them as data (`skipped`: each image id with its reason, +`missingFile`, `missingFolder`, `missingRoot`, `incompletePath`, `masterSkipped`, `missingMaster`, +`masterIsCopy` or `duplicateId`), also in `library.inspectLightroom`, and the desktop result window says how many +in the UI language (one line for incomplete records, one for contradictory ones). A keyword or collection +hierarchy that loops, or is nested more than 64 levels deep, is cut with a warning instead of failing the import: +a keyword keeps its path up to where the loop comes back, and a collection loop is cut at its oldest collection +(the lowest id), which is imported at the top level. + +Only a catalog that can't be read at all still fails the import, before anything changes, with an error that +names the file and says what is wrong, not "invalid parameters": "the Lightroom catalog … can't be read: …" (it +is missing, not allowed, too large, or changed while it was read), "the Lightroom catalog … is damaged: …" (the +database or its write-ahead log is broken, or a table every catalog has — `AgLibraryRootFolder`, +`AgLibraryFolder`, `AgLibraryFile`, `Adobe_images` — can't be read), or "… is not a Lightroom Classic catalog +(or is damaged): it has no … table". A library import index (`Interop/lightroom-index.json`) that can't be read +is an error naming that file. These are `ErrorKind::Other`; a cancelled import stays `Cancelled`. Virtual copies count as added records too; reimport reports zero additions when all records already exist. Existing LightCraft edits are preserved by default; `updateExisting=true` explicitly replaces them. Persistent import @@ -107,7 +121,7 @@ importing: metadata checks detect ordinary concurrent changes, but are not SQLit The in-tree, read-only Rust SQLite B-tree reader follows SQLite's public file-format specification; it introduces no dependency or C runtime. Optional history, keyword and collection tables that exceed limits are skipped with warnings; -required photo tables still report errors. Unrelated unsupported schemas are ignored. A needed +required photo tables still report errors (naming the catalog and the table). Unrelated unsupported schemas are ignored. A needed WITHOUT ROWID or virtual table produces an explicit error, handled as a warning when optional. Develop settings reuse the existing XMP/preset mapper. Supported sliders, curves and supported diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 08dab300b2a..180f81b461a 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (LRC-LIB-CATALOG-IMPORT: a damaged catalog's contradictory records are skipped, not fatal, and an unreadable catalog names the file, #1588; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -699,7 +699,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N | | LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo; each pane says “Rendering…” (widget `compare:rendering:`) or “This photo can't be opened” (`compare:renderFailed:`) as the loupe does. Escape → Detail without losing edits; pins are catalog-local; missing/deleted photos refused and deleted references no longer drawn (Windows regression/native smoke verified) | | LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) | -| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | +| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Contradictory records of a damaged catalog (a repeated image id, a virtual copy whose master is gone or is itself a copy) are skipped the same way, and a keyword or collection hierarchy that loops is cut with a warning; only a catalog that can't be read at all fails, before any change, with an error naming the file and what is wrong instead of "invalid parameters" (issue #1588). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) | | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290) | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-27 | patch | LRC-LIB-CATALOG-IMPORT: a repeated image id or a virtual copy whose master is gone or is itself a copy is skipped (`skipped`: `duplicateId`, `missingMaster`, `masterIsCopy`) and a looping keyword or collection hierarchy is cut with a warning, instead of failing the whole import; an unreadable or damaged catalog fails with an error naming the file, not "invalid parameters" (#1588); status unchanged (🟡) | | 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 1a995606251..d878c2b7ca2 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -5,6 +5,13 @@ ### The Edit menu groups Select Only Active Photo and Paste Settings from Previous with their kin - Select Only Active Photo now sits under Deselect All, and Paste Settings from Previous under Paste Selected Settings…, instead of both after Settings…, near the end of the Edit menu. On macOS, where Settings… lives in the application menu, the Edit menu no longer shows two separator lines in a row. +### A damaged Lightroom catalog imports everything it can +- A Lightroom catalog with a few contradictory records (two images with the same id, a virtual copy whose master + is gone or is itself a copy, keywords or collections whose parents loop) no longer fails the whole import: those + images are skipped and counted in the result window, and a looping keyword or collection is imported with a + warning. A catalog that can't be read at all now says which file and what is wrong ("the Lightroom catalog … is + damaged: table Adobe_images can't be read: …") instead of "invalid parameters". + ## 2026-10-26 ### Lightroom catalogs import into libraries on exFAT drives From db1ab694472fcd83dac5cfc1fb506eb32b2581ae Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 27 Oct 2026 06:48:11 -0500 Subject: [PATCH 13/16] Issue #1588: duplicate ids and bad capture times cost only that record MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-ups to 3e98bce6: - A second image with an id already read is skipped while Adobe_images is read, before anything is keyed by its id, and apply_prepared runs skip_inconsistent_records before refuse_non_media. A duplicate whose original is a refused type no longer takes the first image and its virtual copies with it, and one without a file record no longer drops the first image's copies. - A capture time iso_seconds can't read (the check SetCaptured makes) is left out with a warning naming the image, which imports without it. It used to be stored through the unchecked AddPhoto and failed the whole batch at SetCaptured on the next import. A record an earlier version stored with such a time keeps it and gets no SetCaptured. - skip_duplicate_collections keeps the first collection of an id and leaves out the rest with a warning naming both. The photos and collections listed under the id land in the one kept. Two rows used to stage two AddAlbums with one album id ("album … exists"). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_catalog.rs | 54 +++++++-- crates/engine/src/lightroom_catalog/tests.rs | 114 +++++++++++++++++++ docs/lightroom-catalog-import.md | 7 +- docs/parity-checklist.md | 4 +- docs/whats-new.md | 3 +- 5 files changed, 170 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index a424dbbf159..902222ea568 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -273,7 +273,8 @@ fn identity(data: &CatalogImport, photo: &CatalogPhoto) -> String { /// import (#1588). An image with an id an earlier image has, and a virtual copy whose master is not /// in the catalog or is itself a virtual copy, are skipped and listed in `skipped`. A collection /// hierarchy that loops or is deeper than [`MAX_DEPTH`] is cut, the collection where it is cut -/// going to the top level with a warning. +/// going to the top level with a warning. A second collection with an id an earlier one has is +/// left out with a warning. /// /// Called where the catalog is read and again where its photos become records, so neither route /// can keep one; the second pass finds nothing. @@ -301,6 +302,7 @@ pub(crate) fn skip_inconsistent_records(data: &mut CatalogImport) { false }); data.skipped.extend(skipped); + skip_duplicate_collections(data); let cut = collection_cuts(&data.collections); if cut.is_empty() { return; @@ -313,6 +315,29 @@ pub(crate) fn skip_inconsistent_records(data: &mut CatalogImport) { } } +/// Keep the first collection of each id and leave out the rest with a warning naming both: two +/// albums can't have one id. The photos and collections the catalog lists under that id stay +/// there, so they land in the collection kept. +fn skip_duplicate_collections(data: &mut CatalogImport) { + let mut kept: HashMap = HashMap::new(); + let mut warnings = Vec::new(); + data.collections.retain(|c| { + let id = number(c, "id_local"); + let Some(first) = kept.get(&id) else { + kept.insert(id, text(c, "name").to_string()); + return true; + }; + let photos = if data.members.iter().any(|m| number(m, "collection") == id) { + format!("; the photos listed under that id go to “{first}”") + } else { + String::new() + }; + warnings.push(format!("collection “{}”: not imported, it has the id of collection “{first}”{photos}", text(c, "name"))); + false + }); + data.warnings.extend(warnings); +} + /// The collections whose parent link must go for the hierarchy to be a tree no deeper than /// [`MAX_DEPTH`], and why. A loop is cut at its oldest collection (the lowest id: Lightroom numbers /// records as they are made, so it is most likely the loop's real top); a chain too deep is cut @@ -654,9 +679,16 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, // these behind and ignores them); they and their virtual copies are skipped and reported // instead of failing the import let mut orphans = HashSet::new(); + // a second image with an id already read is skipped before anything is keyed by its id, so it + // can't take the first one's records or its virtual copies with it (#1588) + let mut ids = HashSet::new(); for image in table("Adobe_images")? { ensure_read_active(cancel)?; let id = number(&image, "id_local"); + if !ids.insert(id) { + out.skipped.push(SkippedImage { image: id, reason: SkipReason::DuplicateId }); + continue; + } let record = files.get(&number(&image, "rootFile")).ok_or(SkipReason::MissingFile).and_then(|file| { let folder = folders.get(&number(file, "folder")).ok_or(SkipReason::MissingFolder)?; let root = roots.get(&number(folder, "rootFolder")).ok_or(SkipReason::MissingRoot)?; @@ -706,8 +738,8 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, }); } drop_copies_of(&mut out, &orphans); - refuse_non_media(&mut out); skip_inconsistent_records(&mut out); + refuse_non_media(&mut out); ensure_read_active(cancel)?; reader.db.ensure_unchanged().map_err(|e| unreadable(path, e))?; let wal_after = std::fs::metadata(&wal_path).ok().map(|m| (m.len(), m.modified().ok())); @@ -1063,9 +1095,10 @@ fn stage_collections( pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, context: ApplyPrepared<'_>) -> crate::Result { let ApplyPrepared { update_existing, files, index, archive_path, missing_sources, undo0 } = context; // nothing but a file type LightCraft reads becomes a record, whichever route got here (#2135), - // nor a contradictory one (#1588) - refuse_non_media(&mut data); + // nor a contradictory one (#1588); duplicate ids go first, so refusing a duplicate's original + // can't take the first image with it skip_inconsistent_records(&mut data); + refuse_non_media(&mut data); let mut warnings = data.warnings.clone(); let duplicates: HashMap<_, _> = files.duplicates.iter().filter_map(|d| d.existing.map(|id| (key(&d.path), PhotoId(id)))).collect(); let mut by_path: HashMap<_, _> = @@ -1168,8 +1201,12 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co _ => Flag::None, }; p.label = s.catalog.label_from_name(text(&src.image, "colorLabels")); - if !text(&src.image, "captureTime").is_empty() { - p.captured = Some(text(&src.image, "captureTime").into()); + // a capture time the catalog can't hold would fail the whole batch at `SetCaptured` + let captured = text(&src.image, "captureTime"); + if lightcraft_catalog::stacks::iso_seconds(captured).is_some() { + p.captured = Some(captured.into()); + } else if !captured.is_empty() { + warnings.push(format!("image {}: capture time “{captured}” is not a date; imported without it", src.source_id)); } if !src.keywords.is_empty() { p.meta.keywords = src.keywords.clone(); @@ -1217,8 +1254,11 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co Op::SetFlag { id: p.id, flag: p.flag }, Op::SetLabel { id: p.id, label: p.label }, Op::SetMeta { id: p.id, meta: Box::new(p.meta.clone()) }, - Op::SetCaptured { id: p.id, captured: p.captured.clone() }, ]); + // a record an earlier import gave a time that isn't a date keeps it rather than fail the batch + if p.captured.as_deref().is_none_or(|c| lightcraft_catalog::stacks::iso_seconds(c).is_some()) { + ops.push(Op::SetCaptured { id: p.id, captured: p.captured.clone() }); + } ops.push(Op::SetDevelop { id: p.id, settings: p.develop.clone(), label: "Lightroom catalog".into(), edited: p.edited.clone() }); } else { imported += 1; diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index a17659b01bb..c25716896ba 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -206,6 +206,120 @@ fn contradictory_images_are_skipped_and_the_rest_imports() { assert_eq!(s.undo.len(), 1); } +/// A second image with an id already used must not take the first one, or its virtual copy, with +/// it: refusing its original, or finding its file record gone, used to drop every image with that id. +#[test] +fn a_duplicate_image_id_costs_only_the_duplicate() { + let mut data = sample(); + let mut planted = data.photos[1].clone(); + planted.uuid = "planted".into(); + planted.path = "/Users/sky/Downloads/payload.exe".into(); + data.photos.push(planted); + let mut s = crate::Session::new(); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["photos"], 2, "the first image with id 1 and its copy: {r}"); + assert_eq!(r["skipped"], json!([{"image": 1, "reason": "duplicateId"}])); + assert!(!r["warnings"].to_string().contains("payload.exe"), "the duplicate is skipped before its original is looked at: {r}"); + assert!(s.catalog.photos().all(|p| source_path(p) == Some("/missing/test.ARW"))); + assert_eq!(s.catalog.photos().filter(|p| p.copy_of.is_some()).count(), 1); + + use SqlValue::{Integer as I, Null as N, Text as T}; + for (duplicate_file, case) in [(2, "a refused file type"), (9, "no file record")] { + let mut tables = one_row(photo_tables(("/catalog/", ""))); + tables[2].2.push(vec![N, I(1), T("payload.exe".into())]); + tables[3] = ( + "Adobe_images", + "id_local INTEGER PRIMARY KEY, id_global, rootFile, masterImage, fileFormat, fileWidth, fileHeight, rating, pick", + vec![ + vec![N, T("master".into()), I(1), N, T("ARW".into()), I(20), I(10), I(5), I(1)], + vec![N, T("copy".into()), I(1), I(1), T("ARW".into()), I(20), I(10), I(3), I(0)], + vec![I(1), T("duplicate".into()), I(duplicate_file), N, T("ARW".into()), I(20), I(10), I(0), I(0)], + ], + ); + let catalog = read_tables(&tables, &format!("duplicate-{duplicate_file}")); + let read: Vec<_> = catalog.photos.iter().map(|p| (p.source_id, p.uuid.as_str())).collect(); + assert_eq!(read, [(1, "master"), (2, "copy")], "{case}"); + assert_eq!(catalog.skipped, [SkippedImage { image: 1, reason: SkipReason::DuplicateId }], "{case}"); + assert!(catalog.warnings.is_empty(), "{case}: {:?}", catalog.warnings); + let mut s = crate::Session::new(); + let r = apply(&mut s, catalog, false).unwrap(); + assert_eq!(r["photos"], 2, "{case}: {r}"); + assert_eq!(s.catalog.photos().filter(|p| p.copy_of.is_some()).count(), 1, "{case}"); + } +} + +/// A capture time that isn't a date used to fail the whole metadata batch at `SetCaptured` on the +/// first import that met the photo as a record (a reimport); it is left out with a warning. +#[test] +fn a_capture_time_that_is_not_a_date_is_left_out() { + let mut data = sample(); + let mut other = data.photos[1].clone(); + other.source_id = 3; + other.uuid = "other".into(); + other.path = "/missing/other.ARW".into(); + other.image = row(json!({"id_local": 3, "fileFormat": "ARW", "captureTime": "broken"})); + data.photos.push(other); + let mut s = crate::Session::new(); + let mut index = ImportIndex::default(); + let missing_sources = HashSet::new(); + let mut import = |s: &mut crate::Session| { + let undo0 = s.undo.len(); + let context = ApplyPrepared { + update_existing: true, + files: Default::default(), + index: &mut index, + archive_path: None, + missing_sources: &missing_sources, + undo0, + }; + apply_prepared(s, data.clone(), context).unwrap().report + }; + let first = import(&mut s); + assert_eq!(first["photos"], 3, "{first}"); + let warning = "image 3: capture time “broken” is not a date; imported without it"; + assert!(first["warnings"].as_array().unwrap().iter().any(|w| w == warning), "{first}"); + let captured = |s: &crate::Session, image: &str| s.catalog.photo(PhotoId(first["mapping"][image].as_u64().unwrap())).unwrap().captured.clone(); + assert_eq!(captured(&s, "3"), None); + assert_eq!(captured(&s, "1").as_deref(), Some("2024-01-16T12:34:56"), "the rest of the batch stands"); + assert_eq!(s.catalog.albums().count(), 2); + let second = import(&mut s); + assert_eq!(second["mapping"], first["mapping"], "the reimport updates the same records: {second}"); + assert_eq!(second["imported"], 0); + + // a record an earlier version stored with that time keeps it, and the import goes on + let mut s = crate::Session::new(); + let id = s.catalog.alloc_photo_id(); + let mut old = Photo::new(id, Source::File { path: "/missing/other.ARW".into() }, "other.ARW", "ARW", 20, 10, "before"); + old.captured = Some("broken".into()); + s.commit("Earlier import", Op::AddPhoto { photo: Box::new(old) }).unwrap(); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["mapping"]["3"], id.0, "{r}"); + assert_eq!(s.catalog.photo(id).unwrap().captured.as_deref(), Some("broken")); + assert_eq!(s.catalog.photo(PhotoId(r["mapping"]["1"].as_u64().unwrap())).unwrap().captured.as_deref(), Some("2024-01-16T12:34:56")); +} + +/// Two collections with one id used to stage two albums with one id, failing the import: the first +/// is kept, and the photos listed under the id go to it. +#[test] +fn a_duplicate_collection_id_costs_only_the_duplicate() { + let mut data = sample(); + data.collections.push(row(json!({"id_local": 10, "parent": 0, "name": "Rejects", "creationId": "collection"}))); + let mut s = crate::Session::new(); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(r["photos"], 2); + assert_eq!(r["collections"], 2, "{r}"); + let names: Vec<_> = s.catalog.albums().map(|a| a.name.clone()).collect(); + assert!(names.contains(&"Keepers".to_string()) && !names.contains(&"Rejects".to_string()), "{names:?}"); + let keepers = s.catalog.albums().find(|a| a.name == "Keepers").unwrap(); + assert_eq!(keepers.photos.len(), 2); + assert!(keepers.parent.is_some(), "the first row's place is kept"); + assert_eq!( + r["warnings"], + json!(["collection “Rejects”: not imported, it has the id of collection “Keepers”; the photos listed under that id go to “Keepers”"]) + ); + assert_eq!(s.undo.len(), 1); +} + /// A looping (or too deep) collection hierarchy used to fail the whole import: it is cut at the /// loop's oldest collection, which goes to the top level with a warning. #[test] diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index cb3719cdde9..f51b98b9d2f 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -66,13 +66,16 @@ One bad record costs that record, not the import (issue #1588). An image whose f record is gone from the catalog, or whose original path is empty (Lightroom leaves these behind and ignores them), is skipped together with its virtual copies. So are the contradictory records of a damaged catalog: a second image with an id an earlier image has (the first is imported), and a virtual copy whose master is not in the -catalog or is itself a virtual copy. The result lists them as data (`skipped`: each image id with its reason, +catalog or is itself a virtual copy. A duplicate is left out before anything else looks at it, so it can't take +the first image's records or virtual copies with it. The result lists them as data (`skipped`: each image id with its reason, `missingFile`, `missingFolder`, `missingRoot`, `incompletePath`, `masterSkipped`, `missingMaster`, `masterIsCopy` or `duplicateId`), also in `library.inspectLightroom`, and the desktop result window says how many in the UI language (one line for incomplete records, one for contradictory ones). A keyword or collection hierarchy that loops, or is nested more than 64 levels deep, is cut with a warning instead of failing the import: a keyword keeps its path up to where the loop comes back, and a collection loop is cut at its oldest collection -(the lowest id), which is imported at the top level. +(the lowest id), which is imported at the top level. A second collection with the id of an earlier one is left out +with a warning naming both; the photos the catalog lists under that id go to the first. A capture time that isn't a +date is left out with a warning naming the image, which imports without it. Only a catalog that can't be read at all still fails the import, before anything changes, with an error that names the file and says what is wrong, not "invalid parameters": "the Lightroom catalog … can't be read: …" (it diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 180f81b461a..37529b59d60 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -699,7 +699,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N | | LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo; each pane says “Rendering…” (widget `compare:rendering:`) or “This photo can't be opened” (`compare:renderFailed:`) as the loupe does. Escape → Detail without losing edits; pins are catalog-local; missing/deleted photos refused and deleted references no longer drawn (Windows regression/native smoke verified) | | LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) | -| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Contradictory records of a damaged catalog (a repeated image id, a virtual copy whose master is gone or is itself a copy) are skipped the same way, and a keyword or collection hierarchy that loops is cut with a warning; only a catalog that can't be read at all fails, before any change, with an error naming the file and what is wrong instead of "invalid parameters" (issue #1588). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | +| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Contradictory records of a damaged catalog (a repeated image id, a virtual copy whose master is gone or is itself a copy) are skipped the same way, a keyword or collection hierarchy that loops is cut with a warning, and a repeated collection id or a capture time that isn't a date is left out with a warning; only a catalog that can't be read at all fails, before any change, with an error naming the file and what is wrong instead of "invalid parameters" (issue #1588). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) | | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290) | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) | @@ -799,7 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| -| 2026-10-27 | patch | LRC-LIB-CATALOG-IMPORT: a repeated image id or a virtual copy whose master is gone or is itself a copy is skipped (`skipped`: `duplicateId`, `missingMaster`, `masterIsCopy`) and a looping keyword or collection hierarchy is cut with a warning, instead of failing the whole import; an unreadable or damaged catalog fails with an error naming the file, not "invalid parameters" (#1588); status unchanged (🟡) | +| 2026-10-27 | patch | LRC-LIB-CATALOG-IMPORT: a repeated image id or a virtual copy whose master is gone or is itself a copy is skipped (`skipped`: `duplicateId`, `missingMaster`, `masterIsCopy`), a looping keyword or collection hierarchy is cut with a warning, and a repeated collection id or a capture time that isn't a date is left out with a warning, instead of failing the whole import; an unreadable or damaged catalog fails with an error naming the file, not "invalid parameters" (#1588); status unchanged (🟡) | | 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | diff --git a/docs/whats-new.md b/docs/whats-new.md index d878c2b7ca2..feed93718cb 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -9,7 +9,8 @@ - A Lightroom catalog with a few contradictory records (two images with the same id, a virtual copy whose master is gone or is itself a copy, keywords or collections whose parents loop) no longer fails the whole import: those images are skipped and counted in the result window, and a looping keyword or collection is imported with a - warning. A catalog that can't be read at all now says which file and what is wrong ("the Lightroom catalog … is + warning. So is a second collection with the id of another (its photos go to the first), and a capture time that + isn't a date is left out with a warning. A catalog that can't be read at all now says which file and what is wrong ("the Lightroom catalog … is damaged: table Adobe_images can't be read: …") instead of "invalid parameters". ## 2026-10-26 From 379c96327b664813addd0d4a344d564dc22ef26b Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 27 Oct 2026 10:19:39 -0500 Subject: [PATCH 14/16] docs(lightroom): a virtual copy whose master is gone is an incomplete record (#1588) The result window counts `missingMaster` with the incomplete records (a record the image refers to is gone, like a missing file, folder or root record), and only `duplicateId` and `masterIsCopy` as contradictory. The import guide, the parity-checklist row, the What's new entry and the `SkipReason` doc called a missing master contradictory; they now say what the code does. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_catalog.rs | 7 +++++-- crates/ui-egui/src/lightroom_import.rs | 3 ++- docs/lightroom-catalog-import.md | 11 ++++++----- docs/parity-checklist.md | 2 +- docs/whats-new.md | 2 +- 5 files changed, 15 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 902222ea568..43a7dabc4b9 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -205,8 +205,11 @@ pub struct SkippedImage { pub reason: SkipReason, } -/// Why a catalog image was not imported. Lightroom leaves incomplete records behind and ignores -/// them; contradictory ones come from a damaged catalog. Either costs that image, not the import. +/// Why a catalog image was not imported. Incomplete records, which Lightroom leaves behind and +/// ignores, refer to a record that is gone or empty: every reason up to [`SkipReason::MissingMaster`] +/// (a virtual copy whose master is gone). Contradictory ones, [`SkipReason::MasterIsCopy`] and +/// [`SkipReason::DuplicateId`], conflict with another record of a damaged catalog; the desktop +/// result window counts them on their own line. Either costs that image, not the import. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum SkipReason { diff --git a/crates/ui-egui/src/lightroom_import.rs b/crates/ui-egui/src/lightroom_import.rs index fd9e47edbfe..780379ede29 100644 --- a/crates/ui-egui/src/lightroom_import.rs +++ b/crates/ui-egui/src/lightroom_import.rs @@ -721,7 +721,8 @@ mod tests { assert_eq!(&en[2..], ["w1", "w2"]); } - /// Images skipped for contradictory records (a damaged catalog, #1588) are their own line. + /// Images skipped for contradictory records (a damaged catalog, #1588) are their own line; a + /// virtual copy whose master is gone is incomplete, like a missing file record. #[test] fn contradictory_records_are_their_own_line() { let value = json!({"report": {"photos": 3, "collections": 0, "skipped": [ diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index f51b98b9d2f..c02e1ab6a58 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -63,11 +63,12 @@ separately from failures reading files that are present. Known-missing originals again. Previously browsed Local records join All Photos even when their originals are offline; their promotion is counted once and undone together with the catalog import. One bad record costs that record, not the import (issue #1588). An image whose file, folder or root folder -record is gone from the catalog, or whose original path is empty (Lightroom leaves these behind and ignores them), -is skipped together with its virtual copies. So are the contradictory records of a damaged catalog: a second -image with an id an earlier image has (the first is imported), and a virtual copy whose master is not in the -catalog or is itself a virtual copy. A duplicate is left out before anything else looks at it, so it can't take -the first image's records or virtual copies with it. The result lists them as data (`skipped`: each image id with its reason, +record is gone from the catalog, or whose original path is empty, is skipped together with its virtual copies, and +so is a virtual copy whose master is not in the catalog: these records are incomplete (Lightroom leaves them behind +and ignores them). So are the contradictory records of a damaged catalog: a second image with an id an earlier +image has (the first is imported), and a virtual copy whose master is itself a virtual copy. A duplicate is +left out before anything else looks at it, so it can't take the first image's records or virtual copies with it. +The result lists them as data (`skipped`: each image id with its reason, `missingFile`, `missingFolder`, `missingRoot`, `incompletePath`, `masterSkipped`, `missingMaster`, `masterIsCopy` or `duplicateId`), also in `library.inspectLightroom`, and the desktop result window says how many in the UI language (one line for incomplete records, one for contradictory ones). A keyword or collection diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 37529b59d60..27caf312a0e 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -699,7 +699,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N | | LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo; each pane says “Rendering…” (widget `compare:rendering:`) or “This photo can't be opened” (`compare:renderFailed:`) as the loupe does. Escape → Detail without losing edits; pins are catalog-local; missing/deleted photos refused and deleted references no longer drawn (Windows regression/native smoke verified) | | LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) | -| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Contradictory records of a damaged catalog (a repeated image id, a virtual copy whose master is gone or is itself a copy) are skipped the same way, a keyword or collection hierarchy that loops is cut with a warning, and a repeated collection id or a capture time that isn't a date is left out with a warning; only a catalog that can't be read at all fails, before any change, with an error naming the file and what is wrong instead of "invalid parameters" (issue #1588). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | +| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). A virtual copy whose master is gone is skipped as incomplete too, and contradictory records of a damaged catalog (a repeated image id, a virtual copy whose master is itself a copy) are skipped the same way, a keyword or collection hierarchy that loops is cut with a warning, and a repeated collection id or a capture time that isn't a date is left out with a warning; only a catalog that can't be read at all fails, before any change, with an error naming the file and what is wrong instead of "invalid parameters" (issue #1588). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) | | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290) | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) | diff --git a/docs/whats-new.md b/docs/whats-new.md index feed93718cb..81347dfc048 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -6,7 +6,7 @@ - Select Only Active Photo now sits under Deselect All, and Paste Settings from Previous under Paste Selected Settings…, instead of both after Settings…, near the end of the Edit menu. On macOS, where Settings… lives in the application menu, the Edit menu no longer shows two separator lines in a row. ### A damaged Lightroom catalog imports everything it can -- A Lightroom catalog with a few contradictory records (two images with the same id, a virtual copy whose master +- A Lightroom catalog with a few damaged records (two images with the same id, a virtual copy whose master is gone or is itself a copy, keywords or collections whose parents loop) no longer fails the whole import: those images are skipped and counted in the result window, and a looping keyword or collection is imported with a warning. So is a second collection with the id of another (its photos go to the first), and a capture time that From f7a76f9a0b24908bb40157dceebab2910e2f03e4 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Fri, 30 Oct 2026 12:52:50 -0500 Subject: [PATCH 15/16] fix(lightroom): check capture dates strictly and keep a bad stored one undoable (#1588) - An impossible date such as 2026-02-30 passed the capture-time check (iso_seconds rolls it over to another day) and was stored. The check now uses dates::normalize_iso, so it is left out with the warning a time that isn't a date gets. - A new record (a virtual copy, a duplicate original) cloned a time an earlier version stored unchecked; it is now dropped with a warning. - A record whose stored time isn't a date took Lightroom's valid time, but SetCaptured refuses the old value, so undoing the import failed. Such a record now keeps its time, with a warning, and the import stays one undo step. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lightroom_catalog.rs | 21 ++++++-- crates/engine/src/lightroom_catalog/tests.rs | 57 ++++++++++++++++++++ docs/lightroom-catalog-import.md | 4 +- 3 files changed, 77 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 43a7dabc4b9..7cd12228ac5 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -1204,13 +1204,20 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co _ => Flag::None, }; p.label = s.catalog.label_from_name(text(&src.image, "colorLabels")); - // a capture time the catalog can't hold would fail the whole batch at `SetCaptured` + // A capture time the catalog can't hold would fail the whole batch at `SetCaptured`, and an + // impossible date (2026-02-30) would roll over to another day in date grouping. let captured = text(&src.image, "captureTime"); - if lightcraft_catalog::stacks::iso_seconds(captured).is_some() { + if lightcraft_catalog::dates::normalize_iso(captured).is_some() { p.captured = Some(captured.into()); } else if !captured.is_empty() { warnings.push(format!("image {}: capture time “{captured}” is not a date; imported without it", src.source_id)); } + // a new record (a virtual copy, a duplicate) doesn't inherit a time an earlier import stored unchecked + if s.catalog.photo(p.id).is_none() + && let Some(inherited) = p.captured.take_if(|c| lightcraft_catalog::dates::normalize_iso(c).is_none()) + { + warnings.push(format!("image {}: inherited capture time “{inherited}” is not a date; imported without it", src.source_id)); + } if !src.keywords.is_empty() { p.meta.keywords = src.keywords.clone(); } @@ -1258,9 +1265,15 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co Op::SetLabel { id: p.id, label: p.label }, Op::SetMeta { id: p.id, meta: Box::new(p.meta.clone()) }, ]); - // a record an earlier import gave a time that isn't a date keeps it rather than fail the batch - if p.captured.as_deref().is_none_or(|c| lightcraft_catalog::stacks::iso_seconds(c).is_some()) { + // A record an earlier import gave a time that isn't a date keeps it: `SetCaptured` refuses + // such a time, so setting it would fail the batch, and replacing it would leave an undo + // that can't put it back. + let settable = |c: Option<&str>| c.is_none_or(|c| lightcraft_catalog::stacks::iso_seconds(c).is_some()); + let stored = s.catalog.photo(p.id).and_then(|old| old.captured.clone()); + if settable(stored.as_deref()) && settable(p.captured.as_deref()) { ops.push(Op::SetCaptured { id: p.id, captured: p.captured.clone() }); + } else if let (Some(stored), true) = (&stored, p.captured != stored) { + warnings.push(format!("image {}: the library's capture time “{stored}” is not a date, so Lightroom's was not applied (undoing the import could not restore it)", src.source_id)); } ops.push(Op::SetDevelop { id: p.id, settings: p.develop.clone(), label: "Lightroom catalog".into(), edited: p.edited.clone() }); } else { diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index c25716896ba..6fea2b74b72 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -298,6 +298,63 @@ fn a_capture_time_that_is_not_a_date_is_left_out() { assert_eq!(s.catalog.photo(PhotoId(r["mapping"]["1"].as_u64().unwrap())).unwrap().captured.as_deref(), Some("2024-01-16T12:34:56")); } +/// An impossible date (2026-02-30) is not a capture time either: stored, it would roll over to +/// another day in date grouping. +#[test] +fn an_impossible_capture_date_is_left_out() { + let mut data = sample(); + data.photos[1].image.insert("captureTime".into(), json!("2026-02-30T10:00:00")); + let mut s = crate::Session::new(); + let r = apply(&mut s, data, false).unwrap(); + let id = PhotoId(r["mapping"]["1"].as_u64().unwrap()); + assert_eq!(s.catalog.photo(id).unwrap().captured, None); + assert_eq!(r["warnings"], json!(["image 1: capture time “2026-02-30T10:00:00” is not a date; imported without it"])); +} + +/// A record an earlier version stored with a time that isn't a date: Lightroom's time doesn't +/// replace it (undo could not put it back, `SetCaptured` refuses it), and a new virtual copy of it +/// doesn't inherit it. +#[test] +fn a_stored_capture_time_that_is_not_a_date_stays_undoable_and_is_not_copied() { + let earlier = |captured: &str| { + let mut s = crate::Session::new(); + let id = s.catalog.alloc_photo_id(); + let mut old = Photo::new(id, Source::File { path: "/missing/test.ARW".into() }, "test.ARW", "ARW", 20, 10, "before"); + old.captured = Some(captured.into()); + s.commit("Earlier import", Op::AddPhoto { photo: Box::new(old) }).unwrap(); + s.undo.clear(); + (s, id) + }; + // Lightroom has a time for the master + let (mut s, id) = earlier("broken"); + let r = apply(&mut s, sample(), false).unwrap(); + assert_eq!(r["mapping"]["1"], id.0, "{r}"); + assert_eq!(s.catalog.photo(id).unwrap().captured.as_deref(), Some("broken")); + assert_eq!( + r["warnings"], + json!([ + "image 1: the library's capture time “broken” is not a date, so Lightroom's was not applied (undoing the import could not restore it)" + ]) + ); + let copy = PhotoId(r["mapping"]["2"].as_u64().unwrap()); + assert_eq!(s.catalog.photo(copy).unwrap().captured.as_deref(), Some("2024-01-16T12:34:56"), "the copy gets Lightroom's time"); + s.undo_step().unwrap(); + assert_eq!(s.catalog.len(), 1, "the import is undone in one step"); + assert_eq!(s.catalog.photo(id).unwrap().captured.as_deref(), Some("broken")); + + // Lightroom has none: the master keeps its own, the new copy gets none + let (mut s, id) = earlier("broken"); + let mut data = sample(); + data.photos[1].image.remove("captureTime"); + let r = apply(&mut s, data, false).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().captured.as_deref(), Some("broken")); + let copy = PhotoId(r["mapping"]["2"].as_u64().unwrap()); + assert_eq!(s.catalog.photo(copy).unwrap().captured, None); + assert_eq!(r["warnings"], json!(["image 2: inherited capture time “broken” is not a date; imported without it"])); + s.undo_step().unwrap(); + assert_eq!(s.catalog.len(), 1); +} + /// Two collections with one id used to stage two albums with one id, failing the import: the first /// is kept, and the photos listed under the id go to it. #[test] diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index c02e1ab6a58..a12a22cada5 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -76,7 +76,9 @@ hierarchy that loops, or is nested more than 64 levels deep, is cut with a warni a keyword keeps its path up to where the loop comes back, and a collection loop is cut at its oldest collection (the lowest id), which is imported at the top level. A second collection with the id of an earlier one is left out with a warning naming both; the photos the catalog lists under that id go to the first. A capture time that isn't a -date is left out with a warning naming the image, which imports without it. +date (including an impossible one such as 2026-02-30) is left out with a warning naming the image, which imports +without it. A record an earlier version stored with such a time keeps it, with a warning, rather than take +Lightroom's (undoing the import could not restore it), and a new virtual copy of it doesn't inherit it. Only a catalog that can't be read at all still fails the import, before anything changes, with an error that names the file and says what is wrong, not "invalid parameters": "the Lightroom catalog … can't be read: …" (it From 852e3b6d189ef73201f52e81755fc1ab91a23048 Mon Sep 17 00:00:00 2001 From: Clyde C Brown Date: Sat, 31 Oct 2026 15:00:55 -0600 Subject: [PATCH 16/16] #3501: keep a capture date of just a year or a month as stated A photo dated only to the year (1983) or the month (1983-04), as Lightroom Classic keeps scanned prints, now keeps that date: the Lightroom catalog import, photo.setCaptureTime and XMP read and write it as reduced ISO 8601 text, and the app shows it as "1983" or "April 1983". Sorting, grouping, date filters, smart-collection rules, import folders and the {date} token treat it as the start of its period. Auto-stacking, burst detection and track-log tagging leave it out, and a shift reports it as having no time (noTime). XMP gets photoshop:DateCreated only; a stale exif:DateTimeOriginal in a sidecar is removed, and EXIF writes no date. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/dates.rs | 181 ++++++++++++++++++- crates/catalog/src/lib.rs | 2 +- crates/catalog/src/query.rs | 35 ++-- crates/catalog/src/rules.rs | 3 +- crates/engine/src/cmd/cull.rs | 14 +- crates/engine/src/cmd/manage.rs | 45 ++++- crates/engine/src/export/tests.rs | 25 +++ crates/engine/src/import/types.rs | 3 +- crates/engine/src/lightroom_catalog.rs | 10 +- crates/engine/src/lightroom_catalog/tests.rs | 102 +++++++++++ crates/engine/src/rename/tests.rs | 15 ++ crates/engine/src/rename/tokens.rs | 3 +- crates/engine/src/sidecar.rs | 11 +- crates/engine/src/tests/libops.rs | 74 ++++++++ crates/engine/src/tests/xmp.rs | 39 ++++ crates/meta/src/datetime.rs | 76 +++++++- crates/meta/src/exif.rs | 5 +- crates/meta/src/lib.rs | 2 +- crates/meta/src/xmp.rs | 4 +- crates/ui-egui/src/dialogs.rs | 28 ++- crates/ui-egui/src/dialogs/confirm.rs | 2 + crates/ui-egui/src/i18n.rs | 4 + crates/ui-egui/src/i18n/tests.rs | 4 + crates/ui-egui/src/menus/run.rs | 5 +- crates/ui-egui/src/panels/detail/info.rs | 22 +++ crates/ui-egui/src/tests/capture_time.rs | 91 ++++++++++ docs/lightroom-catalog-import.md | 5 +- docs/parity-checklist.md | 2 +- docs/whats-new.md | 12 ++ docs/xmp-interop.md | 3 + 30 files changed, 775 insertions(+), 52 deletions(-) diff --git a/crates/catalog/src/dates.rs b/crates/catalog/src/dates.rs index 2dfebbf9068..785dde7b323 100644 --- a/crates/catalog/src/dates.rs +++ b/crates/catalog/src/dates.rs @@ -100,6 +100,37 @@ fn tail_start(iso: &str) -> Option { ok.then_some(start) } +/// A capture time stated only to the year (`1983`) or the month (`1983-04`): the reduced ISO 8601 +/// dates XMP allows, as for a scanned print whose day isn't known. `Some((year, month))` for exactly +/// those two forms, a year 0001–9999 and a month 01–12; `None` for anything else, a full date included. +pub fn partial_capture(s: &str) -> Option<(u16, Option)> { + let digits = |x: &str| x.bytes().all(|c| c.is_ascii_digit()); + let year = s.get(..4).filter(|y| digits(y)).and_then(|y| y.parse::().ok()).filter(|y| *y > 0)?; + match s.get(4..)? { + "" => Some((year, None)), + rest => { + let month = rest.strip_prefix('-').filter(|m| m.len() == 2 && digits(m))?.parse::().ok()?; + (1..=12).contains(&month).then_some((year, Some(month))) + } + } +} + +/// What a capture time stands for when the library sorts, groups, filters or compares it: a +/// [`partial_capture`] is the start of its period (`1983` → `1983-01-01T00:00:00`, `1983-04` → +/// `1983-04-01T00:00:00`); any other time is itself. +pub fn capture_start(c: &str) -> std::borrow::Cow<'_, str> { + match partial_capture(c) { + Some((y, m)) => format!("{y:04}-{:02}-01T00:00:00", m.unwrap_or(1)).into(), + None => c.into(), + } +} + +/// Whether the library can hold `c` as a capture time: a time [`iso_seconds`] reads, or a +/// [`partial_capture`]. (`Op::SetCaptured` refuses anything else.) +pub fn is_capture_time(c: &str) -> bool { + iso_seconds(&capture_start(c)).is_some() +} + /// Normalize user input to `YYYY-MM-DDTHH:MM:SS` (accepts a space instead of `T`, missing /// seconds or time). `None` if it isn't a valid date. pub fn normalize_iso(s: &str) -> Option { @@ -159,8 +190,13 @@ pub struct DateRun { } /// A capture time for display: `2022-03-30T22:11:11` → "March 30, 2022 at 10:11:11 PM" (the -/// date alone when there is no time; the input unchanged when it doesn't parse). +/// date alone when there is no time, "April 1983" / "1983" for a [`partial_capture`]; the input +/// unchanged when it doesn't parse). pub fn display_time(iso: &str) -> String { + // a year or a month alone shows as such: "1983", "April 1983" + if partial_capture(iso).is_some() { + return group_label(iso); + } let num = |r: std::ops::Range| iso.get(r).and_then(|v| v.parse::().ok()); let (Some(y), Some(mo), Some(d)) = (num(0..4), num(5..7), num(8..10)) else { return iso.to_string() }; let Some(month) = MONTHS.get((mo as usize).wrapping_sub(1)) else { return iso.to_string() }; @@ -218,7 +254,9 @@ impl Catalog { SortKey::EditDate => p.edited.as_deref(), _ => None, }; - d.filter(|d| iso_seconds(d.get(..10).unwrap_or("")).is_some()).and_then(|d| d.get(..by.prefix())).unwrap_or("").to_string() + // a partial capture time (`1983-04`) groups at the start of its period + let d = d.map(capture_start); + d.as_deref().filter(|d| iso_seconds(d.get(..10).unwrap_or("")).is_some()).and_then(|d| d.get(..by.prefix())).unwrap_or("").to_string() } } @@ -423,4 +461,143 @@ mod tests { [("2026-09-30".into(), 0, 3), ("2026-08-01".into(), 3, 1)] ); } + + /// A year or a month alone (`1983`, `1983-04`: a scanned print's date) and nothing else. + #[test] + fn a_partial_capture_time_is_a_year_or_a_month_alone() { + assert_eq!(partial_capture("1983"), Some((1983, None))); + assert_eq!(partial_capture("1983-04"), Some((1983, Some(4)))); + for not in [ + "", + "0000", + "0000-00", + "1983-00", + "1983-13", + "1983-4", + "1983-04-", + "198", + "19830", + " 1983", + "1983 ", + "1983-04-12", + "1983", + "1983-04", + "1980", + "garbage", + ] { + assert_eq!(partial_capture(not), None, "{not}"); + } + assert_eq!(capture_start("1983"), "1983-01-01T00:00:00"); + assert_eq!(capture_start("1983-04"), "1983-04-01T00:00:00"); + assert_eq!(capture_start("2024-01-16T12:34:56Z"), "2024-01-16T12:34:56Z"); + assert_eq!(display_time("1983"), "1983"); + assert_eq!(display_time("1983-04"), "April 1983"); + } + + /// A catalog with one photo per `(capture time, import time)`, each stored through `SetCaptured`. + fn dated(times: &[(&str, &str)]) -> (Catalog, Vec) { + let mut c = Catalog::new(); + let mut ids = Vec::new(); + for (captured, imported) in times { + let id = c.alloc_photo_id(); + let p = Photo::new(id, Source::Demo { scene: 1 }, "a.jpg", "JPEG", 3, 2, imported); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + c.apply(Op::SetCaptured { id, captured: Some((*captured).into()) }).unwrap(); + ids.push(id); + } + (c, ids) + } + + const PERIODS: [(&str, &str); 6] = [ + ("1983-04-01T00:00:01", "2026-10-01T00:00:00"), + ("1983-04", "2026-10-01T00:00:00"), + ("1983-03-31T23:59:59", "2026-10-01T00:00:00"), + ("1983", "2026-10-01T00:00:00"), + ("1982-12-31T23:59:59", "2026-10-01T00:00:00"), + ("1984-01", "2026-10-01T00:00:00"), + ]; + + /// The library holds a partial capture time as stated, and still refuses what isn't a date. + #[test] + fn a_partial_capture_time_is_held_as_stated() { + let (mut c, ids) = dated(&PERIODS); + assert_eq!(c.photo(ids[1]).unwrap().captured.as_deref(), Some("1983-04")); + for bad in ["1983-13", "0000-00", "0000", "text", "1983"] { + assert!(c.apply(Op::SetCaptured { id: ids[0], captured: Some(bad.into()) }).is_err(), "{bad}"); + } + } + + /// Sorted by capture date, a partial time is the start of its period: `1983-04` ties with + /// `1983-04-01T00:00:00`, and the import time decides, as for any two photos taken at once. + #[test] + fn a_partial_capture_time_sorts_as_the_start_of_its_period() { + let mut times = PERIODS.to_vec(); + times[1].1 = "2026-10-02T00:00:00"; + times.push(("1983-04-01T00:00:00", "2026-10-01T00:00:00")); + let (c, _) = dated(×); + let sort = crate::Sort { key: SortKey::CaptureDate, ascending: true, ..Default::default() }; + let order: Vec<_> = c.query(&crate::Filter::default(), &sort).iter().map(|id| c.photo(*id).unwrap().captured.clone().unwrap()).collect(); + assert_eq!(order, ["1982-12-31T23:59:59", "1983", "1983-03-31T23:59:59", "1983-04-01T00:00:00", "1983-04", "1983-04-01T00:00:01", "1984-01"]); + } + + /// Date headers and the By Date section put a partial time at the start of its period. + #[test] + fn a_partial_capture_time_groups_at_the_start_of_its_period() { + let (c, ids) = dated(&PERIODS); + let group = |id, by| c.date_group(id, SortKey::CaptureDate, by); + assert_eq!( + (group(ids[1], GroupBy::Year), group(ids[1], GroupBy::Month), group(ids[1], GroupBy::Day)), + ("1983".into(), "1983-04".into(), "1983-04-01".into()) + ); + assert_eq!((group(ids[3], GroupBy::Month), group(ids[3], GroupBy::Day)), ("1983-01".into(), "1983-01-01".into())); + let by_date = c.date_groups(); + let y1983 = by_date.iter().find(|g| g.year == "1983").unwrap(); + assert_eq!(y1983.count, 4, "{by_date:?}"); + assert!(y1983.months.contains(&("1983-04".into(), 2)), "{by_date:?}"); + assert!(y1983.months.contains(&("1983-01".into(), 1)), "{by_date:?}"); + } + + /// Date filters and smart-collection rules read a partial time as the start of its period. + #[test] + fn a_partial_capture_time_meets_filters_and_rules_as_the_start_of_its_period() { + let (c, ids) = dated(&PERIODS); + let sort = crate::Sort { key: SortKey::CaptureDate, ascending: true, ..Default::default() }; + let matching = |f: crate::Filter| { + let mut found: Vec<_> = c.query(&f, &sort).iter().map(|id| c.photo(*id).unwrap().captured.clone().unwrap()).collect(); + found.sort(); + found + }; + assert_eq!(matching(crate::Filter { date: Some("1983-04-01".into()), ..Default::default() }), ["1983-04", "1983-04-01T00:00:01"]); + assert_eq!( + matching(crate::Filter { date_from: Some("1983-04-01".into()), date_to: Some("1983-04-30".into()), ..Default::default() }), + ["1983-04", "1983-04-01T00:00:01"] + ); + assert_eq!(matching(crate::Filter { text: "date:1983-01".into(), ..Default::default() }), ["1983"]); + let rule = |op: &str, value: serde_json::Value| { + let set: crate::RuleSet = + serde_json::from_value(serde_json::json!({"match": "all", "rules": [{"field": "captureDate", "op": op, "value": value}]})).unwrap(); + set.matches(c.photo(ids[1]).unwrap(), &c) + }; + assert!(rule("is", "1983-04".into())); + assert!(rule("is", "1983".into())); + assert!(rule("is", "1983-04-01".into())); + assert!(!rule("is", "1983-03".into())); + assert!(rule("between", serde_json::json!(["1983-04-01", "1983-04-30"]))); + assert!(!rule("after", "1983-04-01T00:00:01".into())); + } + + /// A year or a month alone has no time of day, so photos dated to the same one are not a burst. + #[test] + fn partial_capture_times_are_not_stacked_by_time() { + let mut c = Catalog::new(); + let mut ids = Vec::new(); + for (i, t) in ["1983", "1983", "1983-04", "1983-04"].iter().enumerate() { + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::Demo { scene: 1 }, &format!("{i}.jpg"), "JPEG", 3, 2, "2026-10-01T00:00:00"); + p.captured = Some((*t).into()); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + ids.push(id); + } + assert!(c.auto_stack_groups(&ids, 60.0).is_empty()); + } } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a6972..e6828fdbc7a 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -901,7 +901,7 @@ impl Catalog { } Op::SetCaptured { id, captured } => { if let Some(c) = &captured - && stacks::iso_seconds(c).is_none() + && !dates::is_capture_time(c) { return Err(CatalogError::Invalid(format!("not a date: {c}"))); } diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index 94cfa176406..b74c95ba095 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -102,7 +102,11 @@ impl Sort { /// Which of two photos comes first in this order (never `Equal` for two photos: the id decides last). pub fn order(&self, a: &Photo, b: &Photo) -> std::cmp::Ordering { let o = match self.key { - SortKey::CaptureDate => a.captured.cmp(&b.captured).then_with(|| a.imported.cmp(&b.imported)), + // a partial capture time (`1983-04`) sorts at the start of its period + SortKey::CaptureDate => { + let (at_a, at_b) = (a.captured.as_deref().map(crate::dates::capture_start), b.captured.as_deref().map(crate::dates::capture_start)); + at_a.cmp(&at_b).then_with(|| a.imported.cmp(&b.imported)) + } SortKey::ImportDate => a.imported.cmp(&b.imported), SortKey::EditDate => a.edited.cmp(&b.edited), SortKey::FileName => cmp_name(&a.file_name, &b.file_name), @@ -214,7 +218,7 @@ fn token_matches(p: &Photo, tok: &str) -> bool { "person" | "who" => has_person(p, val), "type" | "kind" => format!("{:?}", p.kind).eq_ignore_ascii_case(val), "edited" => (val == "true" || val == "yes") == p.is_edited(), - "date" => p.captured.as_deref().is_some_and(|c| c.starts_with(val)), + "date" => p.captured.as_deref().is_some_and(|c| crate::dates::capture_start(c).starts_with(val)), "copy" | "virtual" => (val == "true" || val == "yes") == p.copy_of.is_some(), "name" | "file" => p.file_name.to_lowercase().contains(val), // Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted @@ -408,17 +412,18 @@ impl Filter { { return false; } + // a partial capture time (`1983-04`) stands for the start of its period if let Some(from) = &self.date_from - && match p.captured.as_deref() { - Some(c) => c < from.as_str(), + && match p.captured.as_deref().map(crate::dates::capture_start) { + Some(c) => *c < *from.as_str(), None => true, } { return false; } if let Some(to) = &self.date_to - && match p.captured.as_deref() { - Some(c) => c.get(..to.len()).unwrap_or(c) > to.as_str(), + && match p.captured.as_deref().map(crate::dates::capture_start) { + Some(c) => c.get(..to.len()).unwrap_or(&c) > to.as_str(), None => true, } { @@ -430,7 +435,7 @@ impl Filter { return false; } if let Some(d) = &self.date - && !p.captured.as_deref().is_some_and(|c| c.starts_with(d.as_str())) + && !p.captured.as_deref().is_some_and(|c| crate::dates::capture_start(c).starts_with(d.as_str())) { return false; } @@ -525,20 +530,26 @@ impl Catalog { /// Year → month → day counts for the "By Date" section (newest first). pub fn date_groups(&self) -> Vec { + use std::borrow::Cow; use std::collections::BTreeMap; - let mut years: BTreeMap<&str, (BTreeMap<&str, usize>, BTreeMap<&str, usize>)> = BTreeMap::new(); + let mut years: BTreeMap, (BTreeMap, usize>, BTreeMap, usize>)> = BTreeMap::new(); for p in self.photos().filter(|p| p.in_library()) { - let Some(d) = p.captured.as_deref() else { continue }; + let Some(d) = p.captured.as_deref().map(crate::dates::capture_start) else { continue }; // `get`, not `[..]`: a corrupt or foreign `captured` (a Lightroom catalog's // captureTime is copied verbatim) may not be ASCII, and slicing it on a byte index - // would panic — the same rule as `dates::group_label`. - if let (Some(year), Some(month), Some(day)) = (d.get(..4), d.get(..7), d.get(..10)) { + // would panic — the same rule as `dates::group_label`. A partial time (`1983-04`) counts + // at the start of its period, so only it owns its keys. + let part = |n: usize| match &d { + Cow::Borrowed(d) => d.get(..n).map(Cow::Borrowed), + Cow::Owned(d) => d.get(..n).map(|k| Cow::Owned(k.to_string())), + }; + if let (Some(year), Some(month), Some(day)) = (part(4), part(7), part(10)) { let (months, days) = years.entry(year).or_default(); *months.entry(month).or_default() += 1; *days.entry(day).or_default() += 1; } } - let newest_first = |m: BTreeMap<&str, usize>| m.into_iter().rev().map(|(k, n)| (k.to_string(), n)).collect::>(); + let newest_first = |m: BTreeMap, usize>| m.into_iter().rev().map(|(k, n)| (k.to_string(), n)).collect::>(); years .into_iter() .rev() diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index ec92dc72461..ad7e121ef7d 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -1020,7 +1020,8 @@ impl Rule { let want = crate::CopyrightStatus::parse(&want); (want == Some(m.copyright_status)) == (op == "is") } - "captureDate" => date_op(op, p.captured.as_deref(), value), + // a partial capture time (`1983-04`) stands for the start of its period + "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), "shutterSpeed" => num_op(op, crate::parse_shutter_seconds(&m.shutter), &shutter_value(value)), diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 383ed890d99..df2d89ba434 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -17,7 +17,8 @@ const SAME: f64 = 0.93; const MAX_GAP: f64 = 86_400.0; fn secs(iso: &str) -> Option { - let d = lightcraft_meta::DateTime::parse_iso(iso)?; + // a year or a month alone has no time to find a burst by + let d = lightcraft_meta::DateTime::parse_iso(iso).filter(lightcraft_meta::DateTime::is_full)?; Some(d.unix_seconds()) } @@ -164,3 +165,14 @@ pub fn specs() -> Vec { ), ] } + +#[cfg(test)] +mod tests { + /// A year or a month alone has no time to find a burst by; a full time does. + #[test] + fn a_year_or_month_alone_has_no_burst_time() { + assert_eq!(super::secs("1983"), None); + assert_eq!(super::secs("1983-04"), None); + assert_eq!(super::secs("1983-04-01T00:00:00"), Some(418_003_200)); + } +} diff --git a/crates/engine/src/cmd/manage.rs b/crates/engine/src/cmd/manage.rs index 9b1f7e9f74d..34df549d75e 100644 --- a/crates/engine/src/cmd/manage.rs +++ b/crates/engine/src/cmd/manage.rs @@ -107,7 +107,8 @@ fn auto_tag_tracklog(s: &mut crate::Session, p: &Value) -> Result { has_gps += 1; continue; } - let Some(dt) = ph.captured.as_deref().and_then(DateTime::parse_iso) else { + // a year or a month alone has no time to place on the track + let Some(dt) = ph.captured.as_deref().and_then(DateTime::parse_iso).filter(DateTime::is_full) else { no_time += 1; continue; }; @@ -183,10 +184,10 @@ pub fn specs() -> Vec { "Edit Capture Time", [], None, - "{ids?, time?: `2026-09-30T14:05:00` (the active photo gets it, the others shift by the same amount), each?: bool (every photo gets `time`), shift?: seconds, hours?: time-zone shift in hours} → {changed, captured: [..], unreadable: photos skipped because their capture time can't be read}", + "{ids?, time?: `2026-09-30T14:05:00` (the active photo gets it, the others shift by the same amount), or a year or month alone (`1983`, `1983-04`; kept as stated, for one photo or with `each`), each?: bool (every photo gets `time`), shift?: seconds, hours?: time-zone shift in hours} → {changed, captured: [..], unreadable: photos skipped because their capture time can't be read, noTime: photos skipped because their capture time is a year or month alone, with no time to shift}", has_selection, |s, p| { - use lightcraft_catalog::dates::{iso_seconds, normalize_iso, shift_iso}; + use lightcraft_catalog::dates::{iso_seconds, normalize_iso, partial_capture, shift_iso}; let c = "photo.setCaptureTime"; let targets: Vec<_> = s.targets(p)?.into_iter().filter(|id| s.catalog.photo(*id).is_some()).collect(); if targets.is_empty() { @@ -202,16 +203,30 @@ pub fn specs() -> Vec { } let mut delta = shift.round() as i64; let mut each: Option = None; - if let Some(t) = str_param(p, "time") { - let t = normalize_iso(t).ok_or_else(|| bad(c, format!("`{t}` is not a date (YYYY-MM-DDTHH:MM:SS)")))?; + // a year or a month alone (`1983`, `1983-04`: a scanned print's date) is kept as + // stated; it has no time to move other photos by, nor one to shift + let partial = str_param(p, "time").map(str::trim).filter(|t| partial_capture(t).is_some()); + if let Some(t) = partial { + if targets.len() > 1 && !bool_or(p, "each", false) { + return Err(bad(c, "a year or month alone can't move other photos by the same amount; give every photo it with `each`")); + } + if delta != 0 { + return Err(bad(c, "a year or month alone can't be shifted")); + } + each = Some(t.to_string()); + } else if let Some(t) = str_param(p, "time") { + let t = normalize_iso(t).ok_or_else(|| bad(c, format!("`{t}` is not a date (YYYY-MM-DDTHH:MM:SS, or YYYY / YYYY-MM)")))?; if bool_or(p, "each", false) { each = Some(t); } else { let anchor = s.active().filter(|a| targets.contains(a)).unwrap_or(targets[0]); let anchor_date = base(s, anchor); - // An impossible calendar date cannot anchor changes to the other photos. - let from = normalize_iso(anchor_date.trim().get(..10).unwrap_or("")) - .and_then(|_| iso_seconds(&anchor_date)) + // An impossible calendar date cannot anchor changes to the other photos. A + // year or a month alone reads (as the start of its period) but has no + // time to move the others by: alone, it gets the time below. + let start = lightcraft_catalog::dates::capture_start(&anchor_date); + let from = normalize_iso(start.trim().get(..10).unwrap_or("")) + .and_then(|_| iso_seconds(&start)) .ok_or_else(|| bad(c, "the photo's date doesn't parse"))?; // the others move by the anchor's change, so it must read in full, not just // its leading digits (a Lightroom catalog's capture time is copied verbatim); @@ -220,6 +235,11 @@ pub fn specs() -> Vec { delta += iso_seconds(&t).unwrap_or(from) - from; } else if targets.len() == 1 { each = Some(t); + } else if partial_capture(anchor_date.trim()).is_some() { + return Err(bad( + c, + "the active photo's capture time is a year or month alone, with no time to move the other photos by; set its time with it selected alone", + )); } else { return Err(bad( c, @@ -232,16 +252,21 @@ pub fn specs() -> Vec { let mut out = Vec::new(); let mut out_of_range = 0usize; let mut unreadable = 0usize; + let mut no_time = 0usize; for id in &targets { let from = match &each { Some(t) => t.clone(), None => base(s, *id), }; - let Some(new) = shift_iso(&from, delta) else { + let new = if partial.is_some() { Some(from.clone()) } else { shift_iso(&from, delta) }; + let Some(new) = new else { // a date that reads but would leave years 0000–9999 is refused below; one // that doesn't read is skipped and counted if shift_iso(&from, 0).is_some() { out_of_range += 1; + } else if partial_capture(from.trim()).is_some() { + // a year or a month alone reads, but has no time to shift + no_time += 1; } else { unreadable += 1; } @@ -259,7 +284,7 @@ pub fn specs() -> Vec { if n > 0 { s.commit("Edit Capture Time", Op::Batch { ops })?; } - Ok(json!({"changed": n, "captured": out, "unreadable": unreadable})) + Ok(json!({"changed": n, "captured": out, "unreadable": unreadable, "noTime": no_time})) } ), cmd!( diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index 139939a1d97..03f6b5369d0 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -264,6 +264,31 @@ fn exported_keywords_follow_their_options() { assert_eq!((back.keywords, back.hierarchical_keywords), (m.keywords.clone(), m.hierarchical_keywords.clone())); } +/// A year or a month alone (`1983-04`, a scanned print's date) is exported in the XMP's +/// `photoshop:DateCreated` as stated, and in neither Exif date nor `exif:DateTimeOriginal`, whose +/// form can't say it; a full time still goes in all of them. +#[test] +fn a_partial_capture_time_is_exported_as_stated() { + use lightcraft_catalog::{Catalog, Photo, PhotoId, Source}; + let mut p = Photo::new(PhotoId(1), Source::Demo { scene: 0 }, "a.jpg", "jpeg", 10, 10, "2026-09-30T00:00:00"); + for (captured, full) in [("1983", false), ("1983-04", false), ("2024-01-16T12:34:56", true)] { + p.captured = Some(captured.into()); + let m = export_metadata(&p, &Catalog::new(), &ExportOptions::default()).unwrap(); + let xmp = lightcraft_meta::write_xmp(&m, None); + let props = lightcraft_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 = lightcraft_meta::read_exif(&lightcraft_meta::write_exif(&m)); + 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!( + lightcraft_meta::extract(&jpg).capture_time.map(|d| d.to_iso()).as_deref(), + Some(captured), + "the exported file reads back as stated" + ); + } +} + #[test] fn metadata_policies() { use lightcraft_catalog::{Catalog, Photo, PhotoId, Source}; diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index 6ad3e21539e..16e375117c0 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -100,7 +100,8 @@ impl Organize { /// The folders (inside the destination) a copy of `p` goes to. pub fn folders(&self, p: &Photo) -> Vec { - let date = p.date(); + // a year or a month alone (`1983`) files under the start of its period + let date = lightcraft_catalog::dates::capture_start(p.date()); let day = date.get(..10).filter(|d| d.len() == 10).unwrap_or("undated"); let year = day.get(..4).unwrap_or("undated"); match self { diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 7cd12228ac5..fc2dc2231de 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -1205,16 +1205,18 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co }; p.label = s.catalog.label_from_name(text(&src.image, "colorLabels")); // A capture time the catalog can't hold would fail the whole batch at `SetCaptured`, and an - // impossible date (2026-02-30) would roll over to another day in date grouping. + // impossible date (2026-02-30) would roll over to another day in date grouping. A year or a + // month alone (`1983`, `1983-04`: a scanned print's date, from its XMP) is kept as stated. let captured = text(&src.image, "captureTime"); - if lightcraft_catalog::dates::normalize_iso(captured).is_some() { + let is_date = |c: &str| lightcraft_catalog::dates::normalize_iso(&lightcraft_catalog::dates::capture_start(c)).is_some(); + if is_date(captured) { p.captured = Some(captured.into()); } else if !captured.is_empty() { warnings.push(format!("image {}: capture time “{captured}” is not a date; imported without it", src.source_id)); } // a new record (a virtual copy, a duplicate) doesn't inherit a time an earlier import stored unchecked if s.catalog.photo(p.id).is_none() - && let Some(inherited) = p.captured.take_if(|c| lightcraft_catalog::dates::normalize_iso(c).is_none()) + && let Some(inherited) = p.captured.take_if(|c| !is_date(c)) { warnings.push(format!("image {}: inherited capture time “{inherited}” is not a date; imported without it", src.source_id)); } @@ -1268,7 +1270,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co // A record an earlier import gave a time that isn't a date keeps it: `SetCaptured` refuses // such a time, so setting it would fail the batch, and replacing it would leave an undo // that can't put it back. - let settable = |c: Option<&str>| c.is_none_or(|c| lightcraft_catalog::stacks::iso_seconds(c).is_some()); + let settable = |c: Option<&str>| c.is_none_or(lightcraft_catalog::dates::is_capture_time); let stored = s.catalog.photo(p.id).and_then(|old| old.captured.clone()); if settable(stored.as_deref()) && settable(p.captured.as_deref()) { ops.push(Op::SetCaptured { id: p.id, captured: p.captured.clone() }); diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 6fea2b74b72..05a3ee9ad05 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -818,6 +818,10 @@ fn record(values: &[SqlValue]) -> Vec { body.extend(s.as_bytes()); 13 + 2 * s.len() as u64 } + SqlValue::Blob(b) => { + body.extend(b); + 12 + 2 * b.len() as u64 + } _ => unreachable!(), }; header.extend(varint(serial)); @@ -1234,3 +1238,101 @@ fn oversized_optional_table_warns_and_is_skipped() { assert!(rows.is_empty()); assert!(warnings.iter().any(|warning| warning.contains("optional_history"))); } + +/// Lightroom's `Adobe_AdditionalMetadata.xmp` blob for a photo whose file states only +/// `photoshop:DateCreated` (a scanned print): a big-endian length, then the zlib-compressed packet. +fn lightroom_xmp_blob(date_created: &str) -> Vec { + let packet = format!( + "\ + " + ); + let mut blob = (packet.len() as u32).to_be_bytes().to_vec(); + blob.extend(miniz_oxide::deflate::compress_to_vec_zlib(packet.as_bytes(), 6)); + blob +} + +/// Every shape of `Adobe_images.captureTime`, read from a catalog file and imported: a year or a +/// month alone (a scanned print's date; Lightroom also has it in the photo's XMP as +/// `photoshop:DateCreated`) is kept as stated, as is every full time; what isn't a date is left +/// out with one warning, and nothing panics. +#[test] +fn every_capture_time_shape_imports_as_stated_or_is_left_out() { + use SqlValue::{Blob as B, Integer as I, Null as N, Text as T}; + // (captureTime, what the library keeps; None = left out with a warning, or nothing to keep) + let shapes: &[(&str, Option<&str>)] = &[ + ("1983", Some("1983")), + ("1983-04", Some("1983-04")), + ("1983-04-12", Some("1983-04-12")), + ("2024-01-16T12:34:56", Some("2024-01-16T12:34:56")), + ("2024-01-16T12:34:56.12", Some("2024-01-16T12:34:56.12")), + ("2024-01-16T12:34:56.123", Some("2024-01-16T12:34:56.123")), + ("2024-01-16T12:34:56.123456", Some("2024-01-16T12:34:56.123456")), + ("2024-01-16T12:34", Some("2024-01-16T12:34")), + ("2024-01-16T12:34:56-07:00", Some("2024-01-16T12:34:56-07:00")), + ("2024-01-16T12:34:56Z", Some("2024-01-16T12:34:56Z")), + ("", None), + ("1983-13", None), + ("0000", None), + ("garbage", None), + ("1983", None), + ("1983-04", None), + ]; + let partial = |c: &str| c == "1983" || c == "1983-04"; + let tables = vec![ + ( + "AgLibraryRootFolder", + "id_local INTEGER PRIMARY KEY, absolutePath, name, relativePathFromCatalog", + vec![vec![N, T("/catalog/".into()), T("Photos".into()), T("".into())]], + ), + ("AgLibraryFolder", "id_local INTEGER PRIMARY KEY, rootFolder, pathFromRoot", vec![vec![N, I(1), T("Photos/".into())]]), + ( + "AgLibraryFile", + "id_local INTEGER PRIMARY KEY, folder, idx_filename", + (0..shapes.len()).map(|i| vec![N, I(1), T(format!("scan{i}.jpg"))]).collect(), + ), + ( + "Adobe_images", + "id_local INTEGER PRIMARY KEY, id_global, rootFile, fileFormat, fileWidth, fileHeight, captureTime", + shapes + .iter() + .enumerate() + .map(|(i, (c, _))| { + vec![N, T(format!("scan-{i}")), I(i as i64 + 1), T("JPG".into()), I(20), I(10), if c.is_empty() { N } else { T((*c).into()) }] + }) + .collect(), + ), + ( + "Adobe_AdditionalMetadata", + "id_local INTEGER PRIMARY KEY, image, xmp", + shapes + .iter() + .enumerate() + .filter(|(_, (c, _))| partial(c)) + .map(|(i, (c, _))| vec![N, I(i as i64 + 1), B(lightroom_xmp_blob(c))]) + .collect(), + ), + ]; + let catalog = read_tables(&tables, "capture-time-shapes"); + assert_eq!(catalog.photos.len(), shapes.len(), "{:?}", catalog.skipped); + assert!(catalog.warnings.is_empty(), "{:?}", catalog.warnings); + let mut s = crate::Session::new(); + let r = apply(&mut s, catalog, false).unwrap(); + let mut warnings = Vec::new(); + for (i, (c, kept)) in shapes.iter().enumerate() { + let id = PhotoId(r["mapping"][(i + 1).to_string()].as_u64().unwrap()); + assert_eq!(s.catalog.photo(id).unwrap().captured.as_deref(), *kept, "captureTime “{c}”: {r}"); + if kept.is_none() && !c.is_empty() { + warnings.push(format!("image {}: capture time “{c}” is not a date; imported without it", i + 1)); + } + } + assert_eq!(r["warnings"], json!(warnings), "one warning for each time that isn't a date, none for a partial one"); + // a reimport over the same records sets the same times again, partial ones included + let again = apply(&mut s, read_tables(&tables, "capture-time-shapes-again"), false).unwrap(); + assert_eq!(again["mapping"], r["mapping"]); + assert_eq!(again["imported"], 0, "{again}"); + for (i, (c, kept)) in shapes.iter().enumerate() { + let id = PhotoId(r["mapping"][(i + 1).to_string()].as_u64().unwrap()); + assert_eq!(s.catalog.photo(id).unwrap().captured.as_deref(), *kept, "reimported captureTime “{c}”"); + } +} diff --git a/crates/engine/src/rename/tests.rs b/crates/engine/src/rename/tests.rs index d8ef8de10d3..cea2c720ddf 100644 --- a/crates/engine/src/rename/tests.rs +++ b/crates/engine/src/rename/tests.rs @@ -487,6 +487,21 @@ fn case_only_rename_on_disk() { let _ = std::fs::remove_dir_all(&dir); } +/// A year or a month alone (`1983`, a scanned print's date) names and files a photo by the start +/// of its period, as before the library kept such a date as stated (it read as 1 January). +#[test] +fn a_year_or_month_alone_names_and_files_by_the_start_of_its_period() { + let mut p = sample_photo(); + for (captured, day) in [("1983", "1983-01-01"), ("1983-04", "1983-04-01")] { + p.captured = Some(captured.into()); + let compact = day.replace('-', ""); + assert_eq!(expand_folder("{date:%Y}/{date:%Y%m%d}", &p, 1), vec!["1983".to_string(), compact.clone()], "{captured}"); + assert_eq!(expand("{date}-{name}", &p, 1), format!("{compact}-{}", expand("{name}", &p, 1)), "{captured}"); + assert_eq!(crate::import::Organize::ByDay.folders(&p), vec!["1983".to_string(), day.to_string()], "{captured}"); + assert_eq!(crate::import::Organize::ByMonth.folders(&p), vec!["1983".to_string(), day[..7].to_string()], "{captured}"); + } +} + #[test] fn folder_templates_stay_inside_the_destination() { let mut p = sample_photo(); diff --git a/crates/engine/src/rename/tokens.rs b/crates/engine/src/rename/tokens.rs index ee15836e87c..cd3c45c6e6b 100644 --- a/crates/engine/src/rename/tokens.rs +++ b/crates/engine/src/rename/tokens.rs @@ -246,7 +246,8 @@ pub fn expand_tokens_with( let w: usize = arg.and_then(|a| a.parse().ok()).unwrap_or(seq_width).min(9); format!("{seq:0w$}") } - "date" => format_date(p.date(), arg.unwrap_or("%Y%m%d")), + // a year or a month alone (`1983`) names the start of its period + "date" => format_date(&lightcraft_catalog::dates::capture_start(p.date()), arg.unwrap_or("%Y%m%d")), "folder" => match &p.source { Source::File { path } => { Path::new(path).parent().and_then(Path::file_name).map(|f| f.to_string_lossy().to_string()).unwrap_or_default() diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index d13b9512571..a9b95f55141 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -458,8 +458,11 @@ pub struct SidecarSaved { } /// The new contents for the sidecar at `path`: `fresh` merged into the existing file, if any. +/// `partial_capture`: the photo's capture time is a year or a month alone, which `fresh` states +/// in `photoshop:DateCreated` only, so an `exif:DateTimeOriginal` already there (an earlier full +/// time) is removed rather than left to outrank it on the next read. /// Returns (contents, merged, backup). -fn sidecar_contents(path: &Path, fresh: String, stamp: &str) -> std::io::Result<(String, bool, Option)> { +fn sidecar_contents(path: &Path, fresh: String, stamp: &str, partial_capture: bool) -> std::io::Result<(String, bool, Option)> { let bytes = match std::fs::read(path) { Ok(b) => b, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((fresh, false, None)), @@ -469,7 +472,8 @@ fn sidecar_contents(path: &Path, fresh: String, stamp: &str) -> std::io::Result< if bytes.iter().all(u8::is_ascii_whitespace) { return Ok((fresh, false, None)); } - let rules = lightcraft_meta::MergeRules { owned: OWNED, owned_if_present: OWNED_IF_STATED }; + let owned: Vec<&str> = OWNED.iter().copied().chain(partial_capture.then_some("exif:DateTimeOriginal")).collect(); + let rules = lightcraft_meta::MergeRules { owned: &owned, owned_if_present: OWNED_IF_STATED }; match std::str::from_utf8(&bytes) .map_err(|e| e.to_string()) .and_then(|old| lightcraft_meta::merge_xmp(old, &fresh, rules).map_err(|e| e.to_string())) @@ -815,7 +819,8 @@ impl Session { self.validate_sidecar_packets_for_paths(std::slice::from_ref(&path), &crate::rename::RealFs)?; let p = self.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?; let err = |e: std::io::Error| EngineError::Other(format!("{}: {e}", path.display())); - let (data, merged, backup) = sidecar_contents(&path, sidecar_packet(p, &self.catalog), &(self.clock)()).map_err(err)?; + let partial = p.captured.as_deref().and_then(lightcraft_catalog::dates::partial_capture).is_some(); + let (data, merged, backup) = sidecar_contents(&path, sidecar_packet(p, &self.catalog), &(self.clock)(), partial).map_err(err)?; write_atomic(&path, data.as_bytes()).map_err(err)?; self.note_sidecar_write(&path, data.as_bytes()); Ok(SidecarSaved { path, merged, backup }) diff --git a/crates/engine/src/tests/libops.rs b/crates/engine/src/tests/libops.rs index b35167c1baa..c24784047d7 100644 --- a/crates/engine/src/tests/libops.rs +++ b/crates/engine/src/tests/libops.rs @@ -191,6 +191,80 @@ fn captured(s: &Session, id: u64) -> Option { s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().captured.clone() } +/// A year or a month alone has no time to place on a track log: such a photo counts as having no +/// time, not as taken at midnight on the 1st. +#[test] +fn tracklog_skips_a_year_or_month_alone() { + const GPX: &str = r#" + + + +"#; + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id: lightcraft_catalog::PhotoId(ids[0]), captured: Some("2026-05".into()) }).unwrap(); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id: lightcraft_catalog::PhotoId(ids[1]), captured: Some("2026-05-01T00:00:30Z".into()) }) + .unwrap(); + let r = s.execute("photo.autoTagTracklog", &json!({"gpx": GPX, "ids": ids, "replace": true, "dryRun": true})).unwrap(); + assert_eq!((r["tagged"].as_u64(), r["skipped"]["noTime"].as_u64()), (Some(1), Some(1)), "{r}"); +} + +/// A shift or a time-zone change leaves a photo dated to a year or a month alone as it is and counts +/// it as having no time (`noTime`), not as unreadable; such a date can't anchor a set that moves +/// other photos either, and the error says why. +#[test] +fn shifting_leaves_a_year_or_month_alone_and_says_why() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id: lightcraft_catalog::PhotoId(ids[0]), captured: Some("1983-04".into()) }).unwrap(); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id: lightcraft_catalog::PhotoId(ids[1]), captured: Some("2026-01-01T10:00:00".into()) }) + .unwrap(); + s.execute("library.select", &json!({"ids": ids, "active": ids[0]})).unwrap(); + for params in [json!({"shift": 3600}), json!({"hours": 1})] { + let r = s.execute("photo.setCaptureTime", ¶ms).unwrap(); + assert_eq!((r["changed"].as_u64(), r["noTime"].as_u64(), r["unreadable"].as_u64()), (Some(1), Some(1), Some(0)), "{params}: {r}"); + assert_eq!(captured(&s, ids[0]).as_deref(), Some("1983-04"), "{params}"); + } + assert_eq!(captured(&s, ids[1]).as_deref(), Some("2026-01-01T12:00:00")); + let e = s.execute("photo.setCaptureTime", &json!({"time": "1983-04-12 10:00"})).unwrap_err(); + assert!(e.to_string().contains("year or month alone"), "{e}"); + assert_eq!(captured(&s, ids[1]).as_deref(), Some("2026-01-01T12:00:00"), "nothing moved"); +} + +/// Edit Capture Time takes a year or a month alone (`1983`, `1983-04`: a scanned print's date) and +/// keeps it as stated: for the photo alone, or for every photo with `each`. It has no time to move +/// other photos by, nor one to shift, and what isn't a date is still refused. +#[test] +fn capture_time_set_keeps_a_year_or_month_as_stated() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().iter().take(3).map(|p| p.0).collect(); + s.execute("library.select", &json!({"ids": [ids[0]]})).unwrap(); + let r = s.execute("photo.setCaptureTime", &json!({"time": "1983"})).unwrap(); + assert_eq!(r["captured"], json!(["1983"]), "{r}"); + assert_eq!(captured(&s, ids[0]).as_deref(), Some("1983")); + s.execute("photo.setCaptureTime", &json!({"time": " 1983-04 "})).unwrap(); + assert_eq!(captured(&s, ids[0]).as_deref(), Some("1983-04")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(captured(&s, ids[0]).as_deref(), Some("1983"), "one undo step"); + for bad in ["1983-13", "0000-00", "0000", "1983-4", "a long time ago", "1983"] { + assert!(s.execute("photo.setCaptureTime", &json!({"time": bad})).is_err(), "{bad}"); + assert_eq!(captured(&s, ids[0]).as_deref(), Some("1983"), "{bad} changes nothing"); + } + assert!(s.execute("photo.setCaptureTime", &json!({"time": "1983", "shift": 60})).is_err(), "a year can't be shifted"); + // several photos: only with `each` + s.execute("library.select", &json!({"ids": ids, "active": ids[1]})).unwrap(); + let before: Vec<_> = ids.iter().map(|i| captured(&s, *i)).collect(); + let e = s.execute("photo.setCaptureTime", &json!({"time": "1983-04"})).unwrap_err(); + assert!(e.to_string().contains("each"), "{e}"); + assert_eq!(ids.iter().map(|i| captured(&s, *i)).collect::>(), before); + let r = s.execute("photo.setCaptureTime", &json!({"time": "1983-04", "each": true})).unwrap(); + assert_eq!(r["changed"], 3, "{r}"); + assert!(ids.iter().all(|i| captured(&s, *i).as_deref() == Some("1983-04"))); + // a full time replaces it + s.execute("photo.setCaptureTime", &json!({"time": "1983-04-12 10:00", "each": true})).unwrap(); + assert!(ids.iter().all(|i| captured(&s, *i).as_deref() == Some("1983-04-12T10:00:00"))); +} + /// Edit Capture Time: set (others shift along), set each, shift by an offset, time-zone shift; /// one undo step each; replayed from the op log; the grid order follows. #[test] diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 129662e4dc9..fcce90f3dc4 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -1336,6 +1336,45 @@ fn sidecar_capture_time_fills_in_when_the_file_has_none() { let _ = std::fs::remove_dir_all(&lib); } +/// A year or a month alone (`1983-04`, a scanned print's date) is saved to the sidecar in +/// `photoshop:DateCreated` as stated, with no `exif:DateTimeOriginal` (an earlier full time's is +/// removed, or it would win on the next read), and reads back as the same text; a full time +/// writes both again. +#[test] +fn a_partial_capture_time_is_saved_to_the_sidecar_as_stated() { + let src = temp_dir("partial-date"); + let lib = temp_dir("partial-date-lib"); + write_png(&src.join("scan.png"), 1); + std::fs::write(src.join("scan.xmp"), DATED_SIDECAR).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + s.execute("library.import", &json!({"paths": [src.join("scan.png").to_string_lossy()]})).unwrap(); + let id = only(&s); + assert_eq!(s.catalog.photo(id).unwrap().captured.as_deref(), Some("2026-01-14T05:58:48")); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + let saved = |s: &mut Session| { + s.execute("photo.saveMetadataToFile", &json!({})).unwrap(); + let out = std::fs::read_to_string(src.join("scan.xmp")).unwrap(); + let props = lightcraft_meta::parse_xmp(&out).unwrap().properties; + (props.get("photoshop:DateCreated").cloned(), props.get("exif:DateTimeOriginal").cloned(), out) + }; + for partial in ["1983-04", "1983"] { + s.execute("photo.setCaptureTime", &json!({"time": partial})).unwrap(); + let (created, original, out) = saved(&mut s); + assert_eq!(created, Some(vec![partial.to_string()]), "{out}"); + assert_eq!(original, None, "the earlier full time is gone: {out}"); + // reading it back gives the same text + s.catalog.apply(lightcraft_catalog::Op::SetCaptured { id, captured: None }).unwrap(); + s.execute("photo.readMetadataFromFile", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().captured.as_deref(), Some(partial)); + } + s.execute("photo.setCaptureTime", &json!({"time": "1983-04-12 10:00"})).unwrap(); + let (created, original, out) = saved(&mut s); + assert_eq!((created, original), (Some(vec!["1983-04-12T10:00:00".to_string()]), Some(vec!["1983-04-12T10:00:00".to_string()])), "{out}"); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&lib); +} + /// Copyright status, rights usage terms and copyright info URL: edited with `photo.setMeta` (one /// undo step), copied / pasted, kept in metadata presets, written to the sidecar as XMP Rights /// Management fields and read back on a fresh import. diff --git a/crates/meta/src/datetime.rs b/crates/meta/src/datetime.rs index 4b7d09634a5..db22199aa97 100644 --- a/crates/meta/src/datetime.rs +++ b/crates/meta/src/datetime.rs @@ -14,6 +14,30 @@ pub struct DateTime { /// Sub-second part in milliseconds. pub millis: u16, pub offset_minutes: Option, + /// How much of the date was stated. XMP dates may stop at the year (`1983`) or the month + /// (`1983-04`), as for a scanned print whose day isn't known; the missing parts read as 1 and + /// the time as midnight, and the date writes back as stated. + #[serde(default, skip_serializing_if = "DatePrecision::is_full")] + pub precision: DatePrecision, +} + +/// How much of a [`DateTime`] was stated. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum DatePrecision { + /// The day at least (a time of day may be midnight because none was given). + #[default] + Full, + /// The year and month only (`1983-04`). + Month, + /// The year only (`1983`). + Year, +} + +impl DatePrecision { + pub fn is_full(&self) -> bool { + *self == DatePrecision::Full + } } fn num(s: &str) -> Option { @@ -54,6 +78,7 @@ impl DateTime { second: g(&tp, 2)?.try_into().ok()?, millis: 0, offset_minutes: None, + precision: DatePrecision::Full, } .valid() } @@ -90,7 +115,8 @@ impl DateTime { self } - /// ISO 8601 (XMP date): `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, `YYYY-MM-DDThh:mm[:ss[.s+]][TZD]`. + /// ISO 8601 (XMP date): `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, `YYYY-MM-DDThh:mm[:ss[.s+]][TZD]`. A + /// year or a month alone keeps its [`DatePrecision`]. pub fn parse_iso(s: &str) -> Option { let s = s.trim(); let (d, t) = s.split_once('T').unwrap_or((s, "")); @@ -101,8 +127,17 @@ impl DateTime { if dp.len() > 3 { return None; } - let mut dt = DateTime { year, month, day, ..Default::default() }; + let precision = match dp.len() { + 1 => DatePrecision::Year, + 2 => DatePrecision::Month, + _ => DatePrecision::Full, + }; + let mut dt = DateTime { year, month, day, precision, ..Default::default() }; if !t.is_empty() { + // a time of day needs the day it is on + if !dt.precision.is_full() { + return None; + } let (clock, off) = match t.find(['Z', '+', '-']) { Some(i) => (&t[..i], Some(&t[i..])), None => (t, None), @@ -122,13 +157,25 @@ impl DateTime { dt.valid() } + /// Whether the day was stated: Exif's date form can't say a year or a month alone, so only a + /// full date is written there. + pub fn is_full(&self) -> bool { + self.precision.is_full() + } + /// Exif form `YYYY:MM:DD HH:MM:SS`. pub fn to_exif(&self) -> String { format!("{:04}:{:02}:{:02} {:02}:{:02}:{:02}", self.year, self.month, self.day, self.hour, self.minute, self.second) } - /// ISO 8601 with milliseconds when non-zero and the offset when known. + /// ISO 8601 with milliseconds when non-zero and the offset when known; a year or a month + /// alone as stated (`1983`, `1983-04`). pub fn to_iso(&self) -> String { + match self.precision { + DatePrecision::Year => return format!("{:04}", self.year), + DatePrecision::Month => return format!("{:04}-{:02}", self.year, self.month), + DatePrecision::Full => {} + } let mut s = format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", self.year, self.month, self.day, self.hour, self.minute, self.second); if self.millis != 0 { s += &format!(".{:03}", self.millis); @@ -179,6 +226,29 @@ mod tests { assert_eq!(DateTime::parse_exif("2024:06:01 13:45:59").unwrap().with_subsec("0123").millis, 12); } + /// XMP dates may stop at the year or the month (a scanned print's `photoshop:DateCreated`): + /// read with that precision, written back as stated, and never as an Exif date. + #[test] + fn a_year_or_month_alone_reads_and_writes_as_stated() { + for (iso, precision) in [("1983", DatePrecision::Year), ("1983-04", DatePrecision::Month)] { + let d = DateTime::parse_iso(iso).unwrap(); + assert_eq!((d.year, d.month, d.day, d.precision), (1983, if iso.len() == 7 { 4 } else { 1 }, 1, precision), "{iso}"); + assert!(!d.is_full()); + assert_eq!(d.to_iso(), iso); + let meta = crate::Metadata { capture_time: Some(d), ..Default::default() }; + 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}"); + } + for not in ["0000", "1983-00", "1983-13", "1983-04T10:00:00", "1983T10:00"] { + assert_eq!(DateTime::parse_iso(not), None, "{not}"); + } + let full = DateTime::parse_iso("1983-04-12").unwrap(); + assert!(full.is_full()); + assert_eq!(full.to_iso(), "1983-04-12T00:00:00"); + } + #[test] fn offsets() { assert_eq!(DateTime::parse_offset("+02:00"), Some(120)); diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index adcba0f8071..990f362402b 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -487,7 +487,8 @@ pub fn write_exif(meta: &Metadata) -> Vec { (t::ARTIST, ascii(&meta.artist)), (t::COPYRIGHT, ascii(&meta.copyright)), (t::IMAGE_DESCRIPTION, ascii(&meta.caption)), - (t::DATE_TIME, meta.capture_time.map(|d| Value::Ascii(d.to_exif()))), + // Exif's date can't say a year or a month alone (an XMP date can) + (t::DATE_TIME, meta.capture_time.filter(DateTime::is_full).map(|d| Value::Ascii(d.to_exif()))), (t::ORIENTATION, meta.orientation.map(|o| Value::Short(vec![o.to_exif()]))), ] { if let Some(v) = v { @@ -498,7 +499,7 @@ pub fn write_exif(meta: &Metadata) -> Vec { ex.set(t::EXIF_VERSION, Value::Undefined(b"0232".to_vec())); let r = |v: Option| v.filter(|v| v.is_finite() && *v > 0.0).map(|v| Value::Rational(vec![rational(v)])); for (tag, v) in [ - (t::DATE_TIME_ORIGINAL, meta.capture_time.map(|d| Value::Ascii(d.to_exif()))), + (t::DATE_TIME_ORIGINAL, meta.capture_time.filter(DateTime::is_full).map(|d| Value::Ascii(d.to_exif()))), (t::EXPOSURE_TIME, reciprocal(meta.exposure_time).or_else(|| r(meta.exposure_time))), (t::F_NUMBER, r(meta.f_number)), (t::FOCAL_LENGTH, r(meta.focal_length)), diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 07887bbdc62..64eed5b2a0f 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -26,7 +26,7 @@ mod xmp; mod xmp_merge; pub use container::{Embedded, embedded, jpeg_segments, png_chunks, webp_chunks}; -pub use datetime::DateTime; +pub use datetime::{DatePrecision, DateTime}; pub use exif::{from_tiff, read_exif, strip_exif_header, try_read_exif, try_read_exif_with, write_exif}; pub use focus::FocusPoint; pub use gpx::{GpxError, Match, TrackPoint, Tracklog, parse_gpx}; diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index 8ca82da0198..aa497bdb3fa 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -646,7 +646,9 @@ pub fn write_xmp_lc(meta: &Metadata, lc: &[(&str, &str)]) -> String { push("xmp:CreatorTool", meta.software.clone()); push("xmp:Rating", meta.rating.map(|v| v.to_string())); push("xmp:Label", meta.label.clone()); - push("exif:DateTimeOriginal", meta.capture_time.map(|d| d.to_iso())); + // a year or a month alone goes in `photoshop:DateCreated` only, as Lightroom writes it: Exif's + // date can't say it + push("exif:DateTimeOriginal", meta.capture_time.filter(DateTime::is_full).map(|d| d.to_iso())); push("photoshop:DateCreated", meta.capture_time.map(|d| d.to_iso())); push("exif:ExposureTime", meta.exposure_time.map(frac)); push("exif:FNumber", meta.f_number.map(frac)); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 64628822031..c17725877ea 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -487,6 +487,16 @@ fn confirmed(app: &mut LightcraftApp, ctx: &egui::Context, dlg: &mut Dialog) -> app.toast(ctx, e); closed = true; } + // photos dated to a year or a month alone have no time to shift: say so (and, in the same + // toast, about any whose time can't be read) + Ok(r) if matches!(dlg, Dialog::CaptureTime { .. }) && r["noTime"].as_u64().is_some_and(|n| n > 0) => { + let mut text = crate::i18n::tr("Photos dated to a year or month alone have no time to shift and were left as they were").to_string(); + if r["unreadable"].as_u64().is_some_and(|n| n > 0) { + text = format!("{text}. {}", crate::i18n::tr("Photos whose capture time can't be read were left as they were")); + } + app.toast(ctx, text); + closed = true; + } // photos whose capture time doesn't read are left as they were: say so Ok(r) if matches!(dlg, Dialog::CaptureTime { .. }) && r["unreadable"].as_u64().is_some_and(|n| n > 0) => { app.toast(ctx, crate::i18n::tr("Photos whose capture time can't be read were left as they were")); @@ -786,7 +796,7 @@ fn capture_time_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg let params = match mode.as_str() { "set" => { field(ui, "New time", |ui| { - let r = ui.add(egui::TextEdit::singleline(time).hint_text("2026-09-30 14:05:00").desired_width(f32::INFINITY)); + let r = ui.add(egui::TextEdit::singleline(time).hint_text("2026-09-30 14:05:00 · 1983-04 · 1983").desired_width(f32::INFINITY)); crate::widgets::register(ui, "field:captureTime", r.rect); }); json!({"time": time}) @@ -816,21 +826,31 @@ fn capture_time_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg // the photo's own time is the problem (a Lightroom catalog's capture time // is copied verbatim), not what was typed let unreadable = lightcraft_catalog::dates::shift_iso(&cur, 0).is_none(); + // a year or a month alone (`1983`, `1983-04`) is kept as typed, by every selected photo + let partial = |d: &str| lightcraft_catalog::dates::partial_capture(d.trim()).is_some(); let after = match (mode.as_str(), unreadable && n == 1) { + ("set", _) if partial(time) => Some(time.trim().to_string()), // alone, it simply gets the time typed (photo.setCaptureTime repairs it) ("set", true) => lightcraft_catalog::dates::normalize_iso(time), _ => delta.and_then(|d| lightcraft_catalog::dates::shift_iso(&cur, d)), }; + let show = |d: &str| if partial(d) { crate::i18n::display_time(d.trim()) } else { d.replace('T', " ") }; ui.label( egui::RichText::new(match after { - Some(a) => format!("{name}: {} → {}", cur.replace('T', " "), a.replace('T', " ")), + Some(a) => format!("{name}: {} → {}", show(&cur), show(&a)), + // it reads, but has no time of day to shift or to move the others by + None if partial(&cur) && !(mode == "set" && n == 1) => { + crate::i18n::tr("The active photo's capture time is a year or month alone, with no time to shift").to_string() + } None if unreadable && !(mode == "set" && n == 1) => crate::i18n::tr("The active photo's capture time can't be read").to_string(), - None => "Enter a date as YYYY-MM-DD HH:MM:SS".into(), + None => "Enter a date as YYYY-MM-DD HH:MM:SS, YYYY-MM or YYYY".into(), }) .color(t.text_label), ); } - if n > 1 { + if n > 1 && mode == "set" && lightcraft_catalog::dates::partial_capture(time.trim()).is_some() { + ui.label(egui::RichText::new(crate::i18n::tr_format!("All {n} selected photos get this date.", n = n)).color(t.text_dim)); + } else if n > 1 { ui.label(egui::RichText::new(crate::i18n::tr_format!("All {n} selected photos move by the same amount.", n = n)).color(t.text_dim)); } } diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 6b8998c33c8..4069ddb164d 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -62,6 +62,8 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result app.run( "photo.setCaptureTime", match mode.as_str() { + // a year or a month alone has no time to move the others by: every photo gets it + "set" if lightcraft_catalog::dates::partial_capture(time.trim()).is_some() => json!({"time": time, "each": true}), "set" => json!({"time": time}), "shift" => json!({"shift": *days as i64 * 86_400 + *hours as i64 * 3600 + *minutes as i64 * 60}), _ => json!({"hours": zone}), diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index a7df011c280..4442c9f9ecc 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -443,6 +443,10 @@ pub fn date_group_label(key: &str, short: bool) -> String { /// A capture time for display in the UI language (English: "March 30, 2022 at 10:11:11 PM"); /// the metadata itself is never rewritten, and a value that doesn't parse is shown as it is. pub fn display_time(iso: &str) -> String { + // a year or a month alone ("1983", "April 1983"), as the grid's date headers show it + if lightcraft_catalog::dates::partial_capture(iso).is_some() { + return date_group_label(iso, false); + } if language() == Locale::En || lightcraft_catalog::dates::normalize_iso(iso).is_none() { return lightcraft_catalog::dates::display_time(iso); } diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 77bbc14cbc7..15c2dc3ce53 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -862,6 +862,7 @@ fn date_headings_in_every_language() { assert_eq!(date_group_label("2026-09-20", true), "Sunday, 20"); assert_eq!(date_group_label("2026-09", true), "September"); assert_eq!(display_time("2026-09-20T16:04:05"), lightcraft_catalog::dates::display_time("2026-09-20T16:04:05")); + assert_eq!((display_time("1983-04"), display_time("1983")), ("April 1983".to_string(), "1983".to_string())); for language in Locale::ALL { set_language(*language); if *language != Locale::En { @@ -872,6 +873,9 @@ fn date_headings_in_every_language() { assert!(date_group_label("2026", false).contains("2026"), "{language:?}"); assert_eq!(display_time("2026-09-20T16:04:05"), format!("{day} 16:04:05"), "{language:?}"); } + // a capture time stated to the year or the month alone shows as such + assert_eq!(display_time("1983-04"), date_group_label("1983-04", false), "{language:?}"); + assert_eq!(display_time("1983"), date_group_label("1983", false), "{language:?}"); for key in ["", "abcd", "2026-xx", "2026-13", "2026-09-xx", "2026-09"] { assert!(!date_group_label(key, false).contains('{'), "{language:?}: {key:?}"); assert!(!date_group_label(key, true).contains('{'), "{language:?}: {key:?}"); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index c88a502078d..9a951d9761a 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1090,13 +1090,14 @@ fn ui_commands_8(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va fn ui_commands_9(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Value) -> Option> { let r: Result = match id { "dialog.captureTime" => { - // a time that doesn't fully read isn't offered as the starting point (`10:0` would read as midnight) + // a time that doesn't fully read isn't offered as the starting point (`10:0` would read as + // midnight); a year or a month alone (`1983-04`) is, as stated let time = app .session .active() .and_then(|id| app.session.catalog.photo(id)) .map(|p| p.date()) - .filter(|d| lightcraft_catalog::dates::shift_iso(d, 0).is_some()) + .filter(|d| lightcraft_catalog::dates::shift_iso(d, 0).is_some() || lightcraft_catalog::dates::partial_capture(d).is_some()) .map(|d| d.replace('T', " ")) .unwrap_or_default(); let mode = p.get("mode").and_then(Value::as_str).unwrap_or("set").to_string(); diff --git a/crates/ui-egui/src/panels/detail/info.rs b/crates/ui-egui/src/panels/detail/info.rs index da5ae1bed66..2ba419c3458 100644 --- a/crates/ui-egui/src/panels/detail/info.rs +++ b/crates/ui-egui/src/panels/detail/info.rs @@ -252,6 +252,10 @@ fn info_line(field: crate::state::LoupeInfoField, photo: &lightcraft_catalog::Ph /// `2026-09-30T12:00:00` → `2026-09-30 12:00`. fn pretty_date(iso: &str) -> String { + // a year or a month alone shows as such ("1983", "April 1983") + if lightcraft_catalog::dates::partial_capture(iso).is_some() { + return crate::i18n::display_time(iso); + } let d = iso.replacen('T', " ", 1); d.get(..16).map(str::to_string).unwrap_or(d) } @@ -446,6 +450,24 @@ mod info_overlay_tests { lines } + /// The info overlay's capture date shows a year or a month alone at its own precision. + #[test] + fn the_info_overlay_shows_a_year_or_month_alone_as_such() { + let mut photo = lightcraft_catalog::Photo::new( + lightcraft_catalog::PhotoId(1), + lightcraft_catalog::Source::Demo { scene: 0 }, + "scan.jpg", + "JPEG", + 3, + 2, + "2026-10-01T00:00:00", + ); + for (captured, shown) in [("1983-04", "April 1983"), ("1983", "1983"), ("2024-01-16T12:34:56", "2024-01-16 12:34")] { + photo.captured = Some(captured.into()); + assert_eq!(info_line(crate::state::LoupeInfoField::CaptureDate, &photo).as_deref(), Some(shown)); + } + } + /// View ▸ View Options: Info 1 and Info 2 each show the three lines chosen for them, in that /// order, without the lines set to None. #[test] diff --git a/crates/ui-egui/src/tests/capture_time.rs b/crates/ui-egui/src/tests/capture_time.rs index c604ecad1ae..e0ff94dd7da 100644 --- a/crates/ui-egui/src/tests/capture_time.rs +++ b/crates/ui-egui/src/tests/capture_time.rs @@ -174,3 +174,94 @@ fn set_mode_does_not_start_from_an_unreadable_time() { ); assert!(painted(&h, "Enter a date"), "alone, the photo will get the time typed, so the preview asks for one: {:?}", h.painted_text()); } + +/// A year or a month alone (`1983-04`, a scanned print's date) shows at its own precision in Edit +/// Capture Time, whose preview takes a year alone as typed, and OK keeps it as typed. (The grid's +/// date line and the Info panel show it through `i18n::display_time`, tested with the languages.) +#[test] +fn edit_capture_time_shows_and_keeps_a_year_or_month_alone() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let id = h.app.session.visible_cloned()[0]; + set_captured(&mut h, id, "1983-04"); + open(&mut h, &[id], id); + match &mut h.app.ui.dialog { + Some(Dialog::CaptureTime { mode, time, .. }) => { + *mode = "set".into(); + *time = "1983".into(); + } + other => panic!("Edit Capture Time is not open: {other:?}"), + } + h.settle(SETTLE); + assert!(painted(&h, "April 1983 → 1983"), "the preview shows both at their precision: {:?}", h.painted_text()); + let r = h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(h.app.session.catalog.photo(id).unwrap().captured.as_deref(), Some("1983")); +} + +/// Edit Capture Time opened on a photo dated to a year or a month alone starts from that date, as +/// stated; typed with several photos selected, a year or a month goes to each of them. +#[test] +fn edit_capture_time_starts_from_a_partial_date_and_gives_one_to_every_photo() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let ids = h.app.session.visible_cloned(); + let (a, b) = (ids[0], ids[1]); + set_captured(&mut h, a, "1983-04"); + set_captured(&mut h, b, "2026-01-01T10:00:00"); + open(&mut h, &[a], a); + match &h.app.ui.dialog { + Some(Dialog::CaptureTime { time, .. }) => assert_eq!(time, "1983-04", "starts from the date as stated"), + other => panic!("Edit Capture Time is not open: {other:?}"), + } + h.app.ui.dialog = None; + open(&mut h, &[a, b], a); + match &mut h.app.ui.dialog { + Some(Dialog::CaptureTime { mode, time, .. }) => { + *mode = "set".into(); + *time = "1983".into(); + } + other => panic!("Edit Capture Time is not open: {other:?}"), + } + h.settle(SETTLE); + assert!(painted(&h, "All 2 selected photos get this date."), "{:?}", h.painted_text()); + assert!(painted(&h, "April 1983 → 1983"), "{:?}", h.painted_text()); + let r = h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T); + assert_eq!(r["ok"], true, "{r}"); + for id in [a, b] { + assert_eq!(h.app.session.catalog.photo(id).unwrap().captured.as_deref(), Some("1983")); + } +} + +/// A shift with a photo dated to a year or a month alone: the preview and the result say it has no +/// time to shift (not that it can't be read), and it is left as it was; a photo whose time can't be +/// read is named in the same result. +#[test] +fn shifting_a_partial_date_says_it_has_no_time() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let ids = h.app.session.visible_cloned(); + let (a, b) = (ids[0], ids[1]); + set_captured(&mut h, a, "1983-04"); + set_captured(&mut h, b, "2026-01-01T10:00:00"); + let broken = "2026-01-01T10:00:00 and more"; + set_captured(&mut h, ids[2], broken); + open(&mut h, &[a, b, ids[2]], a); + match &mut h.app.ui.dialog { + Some(Dialog::CaptureTime { mode, hours, .. }) => { + *mode = "shift".into(); + *hours = 1; + } + other => panic!("Edit Capture Time is not open: {other:?}"), + } + h.settle(SETTLE); + assert!(painted(&h, "year or month alone, with no time to shift"), "{:?}", h.painted_text()); + assert!(!painted(&h, "can't be read"), "{:?}", h.painted_text()); + let r = h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T); + assert_eq!(r["ok"], true, "{r}"); + let toast = toast(&h); + assert!(toast.contains("no time to shift") && toast.contains("can't be read"), "both are named: {toast:?}"); + assert_eq!(h.app.session.catalog.photo(ids[2]).unwrap().captured.as_deref(), Some(broken)); + assert_eq!(h.app.session.catalog.photo(a).unwrap().captured.as_deref(), Some("1983-04")); + assert_eq!(h.app.session.catalog.photo(b).unwrap().captured.as_deref(), Some("2026-01-01T11:00:00")); +} diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index a12a22cada5..e482500caff 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -75,8 +75,9 @@ in the UI language (one line for incomplete records, one for contradictory ones) hierarchy that loops, or is nested more than 64 levels deep, is cut with a warning instead of failing the import: a keyword keeps its path up to where the loop comes back, and a collection loop is cut at its oldest collection (the lowest id), which is imported at the top level. A second collection with the id of an earlier one is left out -with a warning naming both; the photos the catalog lists under that id go to the first. A capture time that isn't a -date (including an impossible one such as 2026-02-30) is left out with a warning naming the image, which imports +with a warning naming both; the photos the catalog lists under that id go to the first. A capture time of a year or a +month alone (`1983`, `1983-04`: Lightroom keeps a scanned print's date that way) is imported as stated. A capture +time that isn't a date (including an impossible one such as 2026-02-30) is left out with a warning naming the image, which imports without it. A record an earlier version stored with such a time keeps it, with a warning, rather than take Lightroom's (undoing the import could not restore it), and a new virtual copy of it doesn't inherit it. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 27caf312a0e..5513e1235e7 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -111,7 +111,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-REMOVE-ALBUM | Remove from album | P0 | ✅ | `cmd:album.removePhotos`, `crates/engine/src/tests/album_remove.rs`, `crates/ui-egui/src/tests/album_remove.rs` | changes the album only: the photos stay in the library, their library folder and their folder on disk (issue #1805); `id` defaults to the album on screen; returns `{removed, album}`. In a normal album ⌫ removes from the album (as in Lightroom; no confirmation, one undo step), in a smart album it changes nothing and says to edit its rules | | LR-LIB-DUPLICATE | Duplicate a photo | P2 | ✅ | `cmd:photo.duplicate` | Photo ▸ Duplicate: a real `-copy` file with the same settings, metadata and albums (virtual copies share the file) | | LR-LIB-RENAME | Batch rename | P1 | ✅ | `cmd:photo.rename`, `cmd:photo.renamePreview`, `cmd:photo.renameTokens`, `cmd:dialog.rename`, `crates/engine/src/rename.rs` (`TOKENS`) | template tokens {name} {num} {seq:N} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext} (shared with export naming and import rename); a Tags picker beside every template field (Rename Photos, import Rename, export File name) lists each tag with meaning + live example, the date directives and the rules, and inserts the clicked tag at the text cursor; unknown tags are flagged; preview; renames files on disk with their XMP sidecars (a stem sidecar another file still shares, e.g. raw + JPEG, is copied rather than taken), never overwriting (-1, -2… suffixes; a change of letter case only is checked by file identity, so on case-sensitive volumes `img_1.jpg` next to `IMG_1.JPG` is a collision), rolls back on failure (a file that can't be moved back is reported old → new and the library follows it as an undoable partial rename; the same for undo/redo); undo/redo move the files; virtual copies follow | -| LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. A capture time that doesn't fully read (cut short, or text after it) is left as it is and counted (`unreadable`); it can't anchor a set that moves other photos, and set alone repairs it. | +| LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. A capture time that doesn't fully read (cut short, or text after it) is left as it is and counted (`unreadable`); it can't anchor a set that moves other photos, and set alone repairs it. A year or a month alone (`1983`, `1983-04`) is kept as stated (for one photo, or `each`; the dialog gives it to every selected photo and starts from it; shifts skip it as `noTime`), shown as "1983" / "April 1983", sorted and grouped as the start of its period, and written to XMP `photoshop:DateCreated` only. | | LR-LIB-SHOWFINDER | Reveal original in file manager | P0 | ✅ | `cmd:app.showInFinder` | ⌘R (see MENU-FILE-SHOWFINDER) | | LR-LIB-COVER | Album cover | P2 | ✅ | `cmd:album.setCover` | | | LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked; reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | diff --git a/docs/whats-new.md b/docs/whats-new.md index 81347dfc048..88955eefa87 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,17 @@ # What's new in LightCraft +## 2026-10-31 + +### A capture date of just a year or a month is kept as stated +- A photo dated only to the year (`1983`) or the month (`1983-04`), as a scanned print often is, keeps that date: a + Lightroom catalog imports it without a warning, Edit Capture Time takes it (typed with several photos selected, + each of them gets it) and starts from it, and the Info panel, the grid and the info overlay show "1983" or "April + 1983". A shift or time-zone change leaves such a photo as it is and says it has no time to shift. It sorts, groups and + matches date filters and smart-collection rules as the start of its period, and copies and names files by it. + Saved to XMP it goes in `photoshop:DateCreated` as stated, with no `exif:DateTimeOriginal` (whose form can't say + a year alone; an older one in the sidecar is removed), and it reads back the same. Auto-stacking, burst detection + and track-log tagging leave such photos out, since they have no time of day. + ## 2026-10-27 ### The Edit menu groups Select Only Active Photo and Paste Settings from Previous with their kin diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 0f455118249..7691f47dc87 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -81,6 +81,9 @@ the only copy of those edits outside that application's catalog. Saving never dr ones), `xmp:CreatorTool`, comments, the packet wrapper and padding. LightCraft's properties go into one `rdf:Description` of their own; owned properties written by another application (in attribute or element form) are removed from its description, which otherwise stays as it was. +- A **capture time of a year or a month alone** (`1983`, `1983-04`) is written to `photoshop:DateCreated` only, as + Lightroom does, since `exif:DateTimeOriginal` can't say it; an `exif:DateTimeOriginal` already in the sidecar is + then removed, or it would outrank the date on the next read. - Ownership follows the namespace URI, not the prefix spelling. A foreign namespace bound to `lc:` or `xmp:` stays foreign: its properties are preserved and do not become LightCraft settings or ratings. Genuine namespace aliases remain interchangeable, including namespace declarations containing XML character references.