LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
fix(lightroom): a content duplicate keeps the metadata its file carries (#2589)
Chad Elliott5b8b9b521d69
diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rsindex 7d1a69fdd..02f587a43 100644--- a/crates/engine/src/import/commit.rs+++ b/crates/engine/src/import/commit.rs@@ -213,7 +213,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare}report.imported.push(id.0);}- PreparedItem::Duplicate { path, existing, reason, hash } => {+ PreparedItem::Duplicate { path, existing, reason, hash, file_meta } => {let existing = existing.or_else(|| {let h = hash?;new_hash.get(&h).copied().or_else(|| s.catalog.photos().find(|p| p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id))@@ -232,7 +232,13 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, preparereport.restored.push(id.0);}}- _ => report.duplicates.push(Duplicate { path, existing: existing.map(|i| i.0), reason, existing_deleted: trashed.is_some() }),+ _ => report.duplicates.push(Duplicate {+ path,+ existing: existing.map(|i| i.0),+ reason,+ existing_deleted: trashed.is_some(),+ file_meta,+ }),}}PreparedItem::Failed(path, e) => report.failed.push((path, e)),diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rsindex 1730518d5..d4468d128 100644--- a/crates/engine/src/import/job.rs+++ b/crates/engine/src/import/job.rs@@ -73,6 +73,8 @@ pub(super) enum PreparedItem {existing: Option<PhotoId>,reason: &'static str,hash: Option<String>,+ /// The metadata the file itself carries, when it was read ([`Duplicate::file_meta`]).+ file_meta: Option<Box<lightcraft_catalog::Meta>>,},Failed(String, String),Kept(Kept),@@ -141,6 +143,7 @@ impl Prepared {existing: Some(existing),reason: if existing_path.is_some() { "path" } else { "content" },hash: info.content_hash,+ file_meta: Some(Box::new(info.meta)),});} else {items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed })));@@ -261,7 +264,7 @@ impl ImportJob {self.done.fetch_add(1, Relaxed);}Some((id, _)) => {- out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None });+ out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file_meta: None });self.done.fetch_add(1, Relaxed);}None => todo.push(f),@@ -326,7 +329,13 @@ impl ImportJob {&& let Some(existing) = self.by_hash.get(h){self.done.fetch_add(1, Relaxed);- plan.slots.push(Slot::Item(PreparedItem::Duplicate { path, existing: *existing, reason: "content", hash: Some(h.clone()) }));+ plan.slots.push(Slot::Item(PreparedItem::Duplicate {+ path,+ existing: *existing,+ reason: "content",+ hash: Some(h.clone()),+ file_meta: Some(Box::new(info.meta)),+ }));continue;}// the XMP sidecar (or a raw's embedded XMP), read before copying: its capture time filesdiff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rsindex 6ad3e2153..779c5f27c 100644--- a/crates/engine/src/import/types.rs+++ b/crates/engine/src/import/types.rs@@ -146,6 +146,12 @@ pub struct Duplicate {/// That photo is in Recently Deleted (see [`OnDeleted`]).#[serde(rename = "existingDeleted", skip_serializing_if = "std::ops::Not::not")]pub existing_deleted: bool,+ /// The metadata the file itself carries (EXIF, IPTC, embedded XMP), as a file import reads it;+ /// `None` when the file wasn't read (a path match). A Lightroom import makes a record of its+ /// own for a duplicate by content and starts it from these, not from the other photo's record,+ /// whose metadata may have been edited (#2589).+ #[serde(skip)]+ pub file_meta: Option<Box<lightcraft_catalog::Meta>>,}#[derive(Clone, Debug, Default, Serialize)]diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rsindex 30691009f..e77192b78 100644--- a/crates/engine/src/lightroom_catalog.rs+++ b/crates/engine/src/lightroom_catalog.rs@@ -943,7 +943,8 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, corefuse_non_media(&mut data);validate(&data).map_err(error)?;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 duplicates: HashMap<_, _> =+ files.duplicates.iter().filter_map(|d| d.existing.map(|id| (key(&d.path), (PhotoId(id), d.file_meta.as_deref())))).collect();let mut by_path: HashMap<_, _> =s.catalog.photos().filter(|p| p.copy_of.is_none()).filter_map(|p| source_path(p).map(|path| (key(path), p.id))).collect();let mut ids = HashMap::new();@@ -1000,11 +1001,14 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co// a new copy of a master in Recently Deleted is imported, not trashed with itp.deleted = false;p- } else if let Some(duplicate) = duplicates.get(&key(&src.path)).and_then(|id| s.catalog.photo(*id)).cloned() {+ } else if let Some((duplicate, file_meta)) =+ duplicates.get(&key(&src.path)).and_then(|(id, meta)| s.catalog.photo(*id).cloned().map(|p| (p, *meta)))+ {// Catalogs can contain distinct originals with identical bytes and independent edits.// The new record takes only what the bytes determine from the photo with the same// bytes, never that photo's own state: not its Recently Deleted (#2589), virtual copy,- // edits, history, versions, ratings or the metadata a person writes.+ // edits, history, versions, ratings or the metadata a person writes. Its metadata is+ // what its own file carries, as a file import reads it (copyright, creator…).let name = Path::new(&src.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| src.path.clone());let mut p = Photo::new(s.catalog.alloc_photo_id(),@@ -1024,15 +1028,20 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, cop.embedded_lens = duplicate.embedded_lens;p.preview_only = duplicate.preview_only.clone();p.preview_checked = duplicate.preview_checked.clone();- let m = &duplicate.meta;- p.meta.camera = m.camera.clone();- p.meta.lens = m.lens.clone();- p.meta.focal_mm = m.focal_mm;- p.meta.aperture = m.aperture;- p.meta.shutter = m.shutter.clone();- p.meta.iso = m.iso;- p.meta.gps = m.gps;- p.meta.focus = m.focus.clone();+ if let Some(meta) = file_meta {+ p.meta = meta.clone();+ } else {+ // (the file wasn't read: only the exposure description, which no command edits;+ // not GPS, which placing a photo on the map does)+ let m = &duplicate.meta;+ p.meta.camera = m.camera.clone();+ p.meta.lens = m.lens.clone();+ p.meta.focal_mm = m.focal_mm;+ p.meta.aperture = m.aperture;+ p.meta.shutter = m.shutter.clone();+ p.meta.iso = m.iso;+ p.meta.focus = m.focus.clone();+ }// the settings a file import gives it (as-shot white balance, embedded lens// corrections, the default preset); the catalog's settings apply on topcrate::import::apply_import_defaults(s, &mut p);diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rsindex 28d9c615f..34270621c 100644--- a/crates/engine/src/lightroom_catalog/tests.rs+++ b/crates/engine/src/lightroom_catalog/tests.rs@@ -208,6 +208,8 @@ fn a_content_duplicate_of_a_trashed_photo_or_virtual_copy_is_a_new_live_photo()existing: Some(other.0),reason: "content",existing_deleted: case == "trashed",+ // what the file itself carries+ file_meta: Some(Box::new(lightcraft_catalog::Meta { camera: "Same Camera".into(), ..Default::default() })),}],..Default::default()};@@ -268,6 +270,7 @@ fn a_content_duplicate_raw_starts_from_its_camera_defaults() {existing: Some(other.0),reason: "content",existing_deleted: true,+ file_meta: None,}],..Default::default()};@@ -291,6 +294,59 @@ fn a_content_duplicate_raw_starts_from_its_camera_defaults() {assert_eq!((new.develop.wb.temp, new.develop.wb.tint), (5200.0, 4.0), "the file's as-shot white balance");assert!(new.develop.optics.lens_profile, "the file's embedded lens corrections are on");}+/// A content duplicate keeps the metadata its file carries (copyright, rights, creator), as a file+/// import of it would, when the catalog's XMP doesn't restate it; it reads the file's, not the+/// other photo's, which a person may have edited (#2589).+#[test]+fn a_content_duplicate_keeps_the_rights_metadata_in_its_file() {+ let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-duplicate-rights-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join("Photos")).unwrap();+ let source = dir.join("source.lrcat");+ std::fs::write(dir.join("Photos/test.ARW"), b"same bytes").unwrap();+ std::fs::write(&source, native_catalog(&photo_tables((dir.to_str().unwrap(), "")))).unwrap();+ let mut s = crate::Session::new();+ let other = library_photo(&mut s, "/elsewhere/a.ARW", |p| {+ p.deleted = true;+ // edited on the other record after its import+ p.meta.copyright = "Other photo's notice".into();+ p.meta.creator = "Other photo's creator".into();+ p.meta.gps = Some((1.0, 2.0));+ });+ let file_meta = lightcraft_catalog::Meta {+ camera: "Same Camera".into(),+ copyright: "© Jo Example".into(),+ copyright_status: lightcraft_catalog::CopyrightStatus::Copyrighted,+ usage_terms: "No reuse".into(),+ creator: "Jo Example".into(),+ ..Default::default()+ };+ let probed = file_meta.clone();+ s.media.file_probe = Some(Arc::new(move |_| {+ Ok(crate::media::ProbeInfo {+ format: "ARW".into(),+ width: 20,+ height: 10,+ content_hash: Some("same-bytes".into()),+ meta: probed.clone(),+ ..Default::default()+ })+ }));+ let mut job = crate::lightroom_job::LightroomJob::new(&mut s, source, false).unwrap();+ let prepared = job.prepare(&AtomicBool::new(false)).unwrap();+ let r = crate::lightroom_job::commit_prepared(&mut s, prepared).unwrap().report;+ let new = s.catalog.photos().find(|p| p.id != other).unwrap_or_else(|| panic!("no new record: {r}"));+ assert_eq!(new.content_hash.as_deref(), Some("same-bytes"), "{r}");+ assert_eq!(new.rating, 5, "the catalog's own metadata applies: {r}");+ let m = &new.meta;+ assert_eq!(+ (m.copyright.as_str(), m.copyright_status, m.usage_terms.as_str(), m.creator.as_str(), m.camera.as_str()),+ ("© Jo Example", file_meta.copyright_status, "No reuse", "Jo Example", "Same Camera"),+ "the file's own metadata: {r}"+ );+ assert_eq!(m.gps, None, "nothing from the other photo's record");+ std::fs::remove_dir_all(dir).unwrap();+}/// A catalog photo matched (by path) to a library photo in Recently Deleted leaves it there, as/// the import was set up to do (a Lightroom import doesn't restore, see `OnDeleted`), and the report/// counts it so the photos don't go missing unexplained (#2589). A new virtual copy of it is