From f42001560582c828e71caacd2f7c57d99af1daee Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 13:04:04 -0400 Subject: [PATCH 01/11] LR-IMP-DUPES: a photo browsed in Local is offered by Import and no longer blocks the library's own file The scan listed a file that was only browsed in Local as a duplicate by path, so the Import review showed it "In library" and out of reach, and a browsed copy under another path counted as library content. Only library records now count as existing content: a browsed file is offered (still naming its record) and importing it promotes that record with its edits, a library photo with the same content is matched before a browsed copy is promoted, and promoted content counts across scan and background import batches. The review offers such a file only when adding in place, since copy and move would add it where it is, and says that keywords and presets apply to new files only. Ports the approach and the engine tests of #1433 to current main. Co-authored-by: Clearfall <237151555+Clearfall@users.noreply.github.com> --- crates/engine/src/import/commit.rs | 17 +- crates/engine/src/import/job.rs | 27 ++- crates/engine/src/import/scan.rs | 37 +++- crates/engine/src/import/tests_known.rs | 4 +- crates/engine/src/import/types.rs | 6 +- crates/engine/src/sync.rs | 12 +- crates/engine/src/sync/tests_browsed.rs | 22 +++ crates/engine/src/tests/import.rs | 216 ++++++++++++++++++++++ crates/ui-egui/locales/cs.json | 3 +- crates/ui-egui/locales/de.json | 3 +- crates/ui-egui/locales/es.json | 3 +- crates/ui-egui/locales/fi.json | 3 +- crates/ui-egui/locales/fr.json | 3 +- crates/ui-egui/locales/id.json | 3 +- crates/ui-egui/locales/it.json | 3 +- crates/ui-egui/locales/ja.json | 3 +- crates/ui-egui/locales/ka.json | 3 +- crates/ui-egui/locales/pl.json | 3 +- crates/ui-egui/locales/pt-br.json | 3 +- crates/ui-egui/locales/ru.json | 3 +- crates/ui-egui/locales/sv.json | 3 +- crates/ui-egui/locales/uk.json | 3 +- crates/ui-egui/locales/vi.json | 3 +- crates/ui-egui/locales/zh-hans.json | 3 +- crates/ui-egui/locales/zh-hant.json | 3 +- crates/ui-egui/src/dialogs/import.rs | 69 ++++++- crates/ui-egui/src/dialogs/import/body.rs | 13 +- crates/ui-egui/src/dialogs/import/scan.rs | 2 +- crates/ui-egui/src/headless/tests.rs | 35 ++++ docs/parity-checklist.md | 3 +- docs/whats-new.md | 70 +++---- 31 files changed, 503 insertions(+), 81 deletions(-) create mode 100644 crates/engine/src/sync/tests_browsed.rs diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 104d1f63b9..97e427b139 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -212,12 +212,21 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare if s.catalog.photo(id).is_some_and(|p| p.local) { ops.push(Op::SetLocal { id, local: false }); } + // "Import as new": a trashed photo with the same content is replaced, as for a new file + if let Some(old) = s.catalog.photo(id).and_then(|p| p.content_hash.as_ref()).and_then(|h| trash_hash.get(h)) + && purged.insert(*old) + { + purge.push(*old); + } report.imported.push(id.0); } PreparedItem::Duplicate { path, existing, reason, hash, file } => { 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)) + new_hash + .get(&h) + .copied() + .or_else(|| s.catalog.photos().find(|p| !p.local && p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id)) }); let trashed = existing.filter(|id| s.catalog.photo(*id).is_some_and(|p| p.deleted)); match trashed { @@ -227,7 +236,11 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare ops.push(Op::SetDeleted { id, deleted: false }); // matched by content from another path, and the file the record // points at is gone (moved, renamed): the photo follows the file - if reason == "content" && trashed_file_is_gone(&s.catalog, id) { + // (not onto a path another record holds, a file only browsed in Local) + if reason == "content" + && trashed_file_is_gone(&s.catalog, id) + && !s.catalog.photos().any(|p| matches!(&p.source, Source::File { path: held } if *held == path)) + { ops.push(crate::cmd::missing::relink_op(id, &path)); } report.restored.push(id.0); diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index ca906c6192..f84fc901a4 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -38,7 +38,7 @@ pub struct ImportJob { /// as the options said when the import was set up). pub(super) library: Option<(lightcraft_catalog::Catalog, bool)>, /// path → (photo, a Local browse record?) - pub(super) by_path: HashMap, + pub(super) by_path: HashMap)>, /// content hash → the photo that has it (`None`: a file earlier in this import) pub(super) by_hash: HashMap>, pub(super) probe: Option, @@ -240,9 +240,12 @@ impl ImportJob { continue; } if let Source::File { path } = &p.source { - self.by_path.insert(path.clone(), (p.id, p.local)); + self.by_path.insert(path.clone(), (p.id, p.local, p.content_hash.clone())); } - if let Some(h) = &p.content_hash { + // (a copy that was only browsed in Local isn't in the library) + if !p.local + && let Some(h) = &p.content_hash + { self.by_hash.insert(h.clone(), Some(p.id)); } } @@ -259,14 +262,24 @@ impl ImportJob { let mut out = Prepared { scanned: files.len(), items: Vec::new() }; let mut todo = Vec::new(); for f in files { - match self.by_path.get(f.as_str()).copied() { - Some((id, true)) if !opts.local => { + match self.by_path.get(f.as_str()).cloned() { + Some((id, true, hash)) if !opts.local => { + // a library photo with the same content comes first, and a file promoted earlier + // (here or in a previous batch) counts as the library's from then on + if let Some(h) = &hash { + if let Some(existing) = self.by_hash.get(h) { + out.items.push(PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash }); + self.done.fetch_add(1, Relaxed); + continue; + } + self.by_hash.insert(h.clone(), Some(id)); + } // a file that was only browsed (Local) joins the library when it is imported for real - self.by_path.insert(f, (id, false)); + self.by_path.insert(f, (id, false, hash)); out.items.push(PreparedItem::Promote(id)); self.done.fetch_add(1, Relaxed); } - Some((id, _)) => { + Some((id, _, _)) => { out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file: None }); self.done.fetch_add(1, Relaxed); } diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index aaae16c7a4..adaa088f25 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -17,7 +17,7 @@ pub struct ScanInput { /// The library's photos of `files`: path → (photo, its summary as a candidate that is there /// already). One pass over the library, and a record only for a file that was found: a folder of /// a hundred files in a library of millions costs a hundred records. -pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[String]) -> HashMap { +pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[String]) -> HashMap)> { let found: std::collections::HashSet<&Path> = files.iter().map(Path::new).collect(); let mut by_path = HashMap::new(); if found.is_empty() { @@ -35,18 +35,21 @@ pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[Stri height: p.height, file_size: p.file_size, captured: p.captured.clone(), - duplicate: Some("path".into()), + // a file that was only browsed (Local) is not in the library: importing it promotes it + // (a trashed browse record still counts as the path's) + duplicate: (!p.local || p.deleted).then(|| "path".into()), existing: Some(p.id.0), + local: p.local && !p.deleted, ..Default::default() }; - by_path.insert(PathBuf::from(path), (p.id, c)); + by_path.insert(PathBuf::from(path), (p.id, c, p.content_hash.clone())); } } by_path } /// Which photo of the library has each of the contents `hashes` (the later one where several -/// have it). One pass over the library, and an entry only for a content that was asked about. +/// have it; a copy that was only browsed in Local isn't in the library). One pass over the library, and an entry only for a content that was asked about. pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes: impl Iterator) -> HashMap { let wanted: std::collections::HashSet<&str> = hashes.collect(); let mut by_hash = HashMap::new(); @@ -54,7 +57,8 @@ pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes: return by_hash; } for p in library.photos() { - if let Some(h) = &p.content_hash + if !p.local + && let Some(h) = &p.content_hash && wanted.contains(h.as_str()) { by_hash.insert(h.clone(), p.id); @@ -336,15 +340,34 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc crate::memory::release(); let mut probes: HashMap> = todo.into_iter().zip(probed).collect(); // (who in the library has a content that was probed: asked once the probes are in) - let probed_hashes = probes.values().filter_map(|r| r.as_ref().ok()).filter_map(|info| info.content_hash.as_deref()); + let probed_hashes = probes + .values() + .filter_map(|r| r.as_ref().ok()) + .filter_map(|info| info.content_hash.as_deref()) + // (and the browsed files the library has by path: they are offered unless it has the content too) + .chain(by_path.values().filter(|(_, c, _)| c.local).filter_map(|(_, _, h)| h.as_deref())); let mut seen_hash: HashMap> = library_hashes(&input.library, probed_hashes).into_iter().map(|(h, id)| (h, Some(id.0))).collect(); let mut out = Vec::with_capacity(files.len()); let mut kept = HashMap::new(); for f in files { - if let Some((_, c)) = by_path.get(Path::new(&f)) { + if let Some((id, c, hash)) = by_path.get(Path::new(&f)) { let mut c = c.clone(); c.name = Path::new(&f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| f.clone()); + // a browsed file the library has the content of (or an earlier file here promotes) is a duplicate + if c.local + && let Some(h) = hash + { + match seen_hash.get(h) { + Some(existing) => { + c.duplicate = Some("content".into()); + c.existing = *existing; + } + None => { + seen_hash.insert(h.clone(), Some(id.0)); + } + } + } out.push(c); continue; } diff --git a/crates/engine/src/import/tests_known.rs b/crates/engine/src/import/tests_known.rs index 9adadca8a3..3814dc5440 100644 --- a/crates/engine/src/import/tests_known.rs +++ b/crates/engine/src/import/tests_known.rs @@ -28,7 +28,7 @@ fn a_scan_knows_the_library_photos_of_the_files_it_found() { let files: Vec = ["/pics/007/a.jpg", "/pics/007/b.jpg", "/pics/007/new.jpg", "/pics/007//c.jpg"].map(String::from).to_vec(); let known = library_files(&c, &files); assert_eq!(known.len(), 3, "the three the library has (a path is compared as a path, not as text)"); - let (id, as_found) = known.get(Path::new("/pics/007/b.jpg")).expect("b"); + let (id, as_found, _) = known.get(Path::new("/pics/007/b.jpg")).expect("b"); let p = c.photo(*id).unwrap(); assert_eq!((as_found.path.as_str(), as_found.existing, as_found.duplicate.as_deref()), ("/pics/007/b.jpg", Some(id.0), Some("path"))); assert_eq!((as_found.format.as_str(), as_found.width, as_found.height, as_found.file_size), (p.format.as_str(), p.width, p.height, p.file_size)); @@ -39,7 +39,7 @@ fn a_scan_knows_the_library_photos_of_the_files_it_found() { let copy = c.alloc_photo_id(); c.apply(Op::AddPhoto { photo: Box::new(Photo::new(copy, Source::File { path: "/pics/007/a.jpg".into() }, "a.jpg", "JPEG", 6, 4, "2026-01-02")) }) .unwrap(); - assert_eq!(library_files(&c, &files).get(Path::new("/pics/007/a.jpg")).map(|(id, _)| *id), Some(copy)); + assert_eq!(library_files(&c, &files).get(Path::new("/pics/007/a.jpg")).map(|(id, _, _)| *id), Some(copy)); } /// Given a library and a folder on disk that holds a file the library has by its path, one it diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index aab839931b..4e06d6846a 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -137,8 +137,12 @@ pub struct ImportCandidate { /// `"path"` (already in the library), `"content"` (same bytes in the library or earlier in this /// list): skipped by the import. pub duplicate: Option, - /// The photo that already has it. + /// The photo that already has it. On a browsed candidate (`local`): its record. pub existing: Option, + /// The file was only browsed in Local: the library has a record of it (`existing`) that is not in + /// the library, so it is not a duplicate and importing it promotes that record. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub local: bool, /// Not readable. pub error: Option, /// A raw variant that can't be decoded yet (why): it imports as preview only. diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 6b09ed09f5..0451b37310 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -280,14 +280,12 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges { if moved_from.values().any(|to| *to == c.path) { continue; } - let browsed = c.existing.and_then(|id| labels.photo(PhotoId(id))).is_some_and(|p| p.local && !p.deleted); match (c.duplicate.as_deref(), &c.error) { - // a file only looked at in Local is not in the library yet: it is new - (Some("path"), _) if browsed => changes.new.push(ImportCandidate { duplicate: None, existing: None, ..c }), (Some("path"), _) => {} (Some(_), _) => changes.duplicates += 1, (None, Some(_)) => changes.unreadable.push(c), - (None, None) => changes.new.push(c), + // (a file only looked at in Local is not in the library yet: it is new) + (None, None) => changes.new.push(ImportCandidate { existing: None, local: false, ..c }), } } let missing = std::mem::take(&mut changes.missing); @@ -346,7 +344,7 @@ fn match_moved( by_hash.entry(base_hash(h)).or_default().push_back(path); } } - let usable = |c: &&ImportCandidate| c.error.is_none() && c.duplicate.as_deref() != Some("path"); + let usable = |c: &&ImportCandidate| c.error.is_none() && c.duplicate.as_deref() != Some("path") && !c.local; let mut moved: HashMap = HashMap::new(); for c in candidates.iter().filter(usable) { let hash = probes.get(&c.path).and_then(|i| i.content_hash.as_deref()); @@ -895,3 +893,7 @@ impl SyncCommit { #[cfg(test)] #[path = "sync/tests_listing.rs"] mod tests_listing; + +#[cfg(test)] +#[path = "sync/tests_browsed.rs"] +mod tests_browsed; diff --git a/crates/engine/src/sync/tests_browsed.rs b/crates/engine/src/sync/tests_browsed.rs new file mode 100644 index 0000000000..fa66ec3373 --- /dev/null +++ b/crates/engine/src/sync/tests_browsed.rs @@ -0,0 +1,22 @@ +//! Synchronize Folder's "moved" match never takes a file that is only browsed in Local as the new +//! place of a missing photo: that file already has a record of its own. +use super::*; +use lightcraft_catalog::{Catalog, Op}; + +/// Given a missing photo with no hash on record and one file of the folder with its size and +/// dimensions, when the files are matched, then the file is its new place, unless the file is one +/// the library only browsed. +#[test] +fn a_browsed_file_is_not_where_a_missing_photo_went() { + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/pics/old.jpg".into() }, "old.jpg", "JPEG", 6, 4, "2026-01-01"); + p.file_size = 1000; + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let missing = [FolderPhoto { id: id.0, path: "/pics/old.jpg".into() }]; + let mut found = ImportCandidate { path: "/pics/new.jpg".into(), width: 6, height: 4, file_size: 1000, existing: Some(99), ..Default::default() }; + let moved = match_moved(&missing, std::slice::from_ref(&found), &HashMap::new(), &c); + assert_eq!(moved.get("/pics/old.jpg").map(String::as_str), Some("/pics/new.jpg"), "a new file is where it went"); + found.local = true; + assert!(match_moved(&missing, &[found], &HashMap::new(), &c).is_empty(), "a browsed file has a record already"); +} diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 4885b5d30b..f83ee8c154 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -86,6 +86,222 @@ fn recursive_discovery_includes_sony_sr2_and_srf_case_insensitively() { std::fs::remove_dir_all(src).unwrap(); } +/// A file that was only browsed (Local) is not "already in the library": the scan offers it, and +/// importing it brings the browsed record (with its edits) into the library. +#[test] +fn a_browsed_photos_own_file_is_offered_and_joins_the_library_when_imported() { + let src = temp_dir("browsed-own"); + let f = src.join("a.png"); + write_png(&f, 75); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [f], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.rate", &json!({"ids": [id], "rating": 3})).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [f]})).unwrap(); + assert_eq!(scan["duplicates"], 0, "{scan}"); + assert_eq!(scan["candidates"][0]["duplicate"], Value::Null, "{scan}"); + assert_eq!(scan["candidates"][0]["existing"], id, "the candidate still names the browsed record: {scan}"); + assert_eq!(scan["candidates"][0]["local"], true, "and says it was only browsed: {scan}"); + let r = s.execute("library.import", &json!({"paths": [f]})).unwrap(); + assert_eq!(r["imported"], json!([id]), "{r}"); + let p = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap(); + assert!(!p.local && p.rating == 3, "the same record, now in the library, edits kept"); + let scan = s.execute("library.importPreview", &json!({"paths": [f]})).unwrap(); + assert_eq!(scan["duplicates"], 1, "now it is in the library: {scan}"); + let _ = std::fs::remove_dir_all(src); +} + +/// A browse record in Recently Deleted still counts as the path's: the scan lists the file as it did, +/// not as a new browsed file. +#[test] +fn a_deleted_browse_record_still_counts_as_the_files_own() { + let src = temp_dir("browsed-deleted"); + let f = src.join("a.png"); + write_png(&f, 76); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [f], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.delete", &json!({"ids": [id]})).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [f]})).unwrap(); + assert_eq!(scan["candidates"][0]["duplicate"], "path", "{scan}"); + assert_eq!(scan["candidates"][0].get("local"), None, "{scan}"); + let _ = std::fs::remove_dir_all(src); +} + +/// "Import as new" replaces the trashed library photo with the same content when the browsed twin +/// is promoted, as it does for a new file. +#[test] +fn promoting_a_browsed_twin_as_new_replaces_the_trashed_library_photo() { + let src = temp_dir("browsed-fresh"); + let original = src.join("original.png"); + let twin = src.join("browsed.png"); + write_png(&original, 77); + std::fs::copy(&original, &twin).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [original]})).unwrap(); + let old = r["imported"][0].as_u64().unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "local": true})).unwrap(); + let local = r["imported"][0].as_u64().unwrap(); + s.execute("photo.delete", &json!({"ids": [old]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "onDeleted": "fresh"})).unwrap(); + assert_eq!(r["imported"], json!([local]), "{r}"); + let trashed = s.catalog.photos().filter(|p| p.deleted).count(); + assert_eq!(trashed, 0, "the trashed twin is gone"); + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(local)).is_some_and(|p| p.in_library())); + let _ = std::fs::remove_dir_all(src); +} + +/// Restoring a trashed library photo by the content of a browsed file doesn't relink it onto the +/// path the browse record holds: that would leave two records on one file. +#[test] +fn restoring_by_a_browsed_twin_does_not_relink_onto_its_path() { + let src = temp_dir("browsed-restore"); + let original = src.join("original.png"); + let renamed = src.join("renamed.png"); + write_png(&original, 78); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [original]})).unwrap(); + let old = r["imported"][0].as_u64().unwrap(); + std::fs::rename(&original, &renamed).unwrap(); + s.execute("photo.delete", &json!({"ids": [old]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [renamed], "local": true})).unwrap(); + let local = r["imported"][0].as_u64().unwrap(); + let r = s.execute("library.import", &json!({"paths": [renamed]})).unwrap(); + assert_eq!(r["restored"], json!([old]), "{r}"); + let on_path = s.catalog.photos().filter(|p| matches!(&p.source, lightcraft_catalog::Source::File { path } if Path::new(path) == renamed)).count(); + assert_eq!(on_path, 1, "one record holds the renamed file"); + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(local)).is_some_and(|p| p.local), "the browse record is left alone"); + let _ = std::fs::remove_dir_all(src); +} + +#[test] +fn local_twin_does_not_block_reimport_after_permanent_delete_and_restart() { + use lightcraft_catalog::PhotoId; + for mode in ["add", "copy"] { + let src = temp_dir(&format!("local-twin-src-{mode}")); + let lib = temp_dir(&format!("local-twin-lib-{mode}")); + let original = src.join("original.png"); + let twin = src.join("browsed.png"); + write_png(&original, 71); + std::fs::copy(&original, &twin).unwrap(); + let bytes = std::fs::read(&original).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [original], "mode": mode})).unwrap(); + let old = r["imported"][0].as_u64().unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "local": true})).unwrap(); + let local = PhotoId(r["imported"][0].as_u64().unwrap()); + let before = s.catalog.photo(local).unwrap().clone(); + s.execute("photo.delete", &json!({"ids": [old]})).unwrap(); + s.execute("library.source", &json!({"kind": "recentlyDeleted"})).unwrap(); + s.execute("library.select", &json!({"ids": [old]})).unwrap(); + s.execute("photo.deletePermanently", &json!({"ids": [old]})).unwrap(); + s.close_library().unwrap(); + s.open_library(&lib, false).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [original]})).unwrap(); + assert_eq!(scan["duplicates"], 0, "a browsed copy is not a library duplicate: {scan}"); + let r = s.execute("library.import", &json!({"paths": [original], "mode": mode})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(ids(&r, "restored"), 0); + assert_eq!(ids(&r, "duplicates"), 0); + assert_ne!(r["imported"][0], old); + assert_eq!(s.catalog.photo(local).unwrap(), &before, "leave the other path's browse record alone"); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1); + let scan = s.execute("library.importPreview", &json!({"paths": [original]})).unwrap(); + assert_eq!(scan["duplicates"], 1, "the actual library photo still counts"); + assert_eq!(std::fs::read(&original).unwrap(), bytes); + assert_eq!(std::fs::read(&twin).unwrap(), bytes); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(src); + let _ = std::fs::remove_dir_all(lib); + } +} + +#[test] +fn local_twin_import_matches_the_library_photo_before_promoting() { + use lightcraft_catalog::PhotoId; + let src = temp_dir("local-twin-priority"); + let original = src.join("original.png"); + let twin = src.join("browsed.png"); + write_png(&original, 72); + std::fs::copy(&original, &twin).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [original]})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.rate", &json!({"ids": [id], "rating": 5})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "local": true})).unwrap(); + let local = PhotoId(r["imported"][0].as_u64().unwrap()); + let scan = s.execute("library.importPreview", &json!({"paths": [twin]})).unwrap(); + assert_eq!(scan["duplicates"], 1, "{scan}"); + assert_eq!(scan["candidates"][0]["existing"], id); + let r = s.execute("library.import", &json!({"paths": [twin]})).unwrap(); + assert_eq!(ids(&r, "imported"), 0); + assert_eq!(r["duplicates"][0]["existing"], id); + s.execute("photo.delete", &json!({"ids": [id]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "onDeleted": "skip"})).unwrap(); + assert_eq!(ids(&r, "imported"), 0, "skip must not promote the local twin: {r}"); + assert_eq!(r["duplicates"][0]["existingDeleted"], true); + let r = s.execute("library.import", &json!({"paths": [twin]})).unwrap(); + assert_eq!(r["restored"], json!([id])); + assert!(s.catalog.photo(local).unwrap().local); + assert_eq!(s.catalog.photo(PhotoId(id)).unwrap().rating, 5); + let _ = std::fs::remove_dir_all(src); +} + +#[test] +fn local_twins_are_deduplicated_when_promoted_in_one_import() { + let src = temp_dir("local-twin-batch"); + let a = src.join("a.png"); + let b = src.join("b.png"); + let c = src.join("c.png"); + write_png(&a, 73); + std::fs::copy(&a, &b).unwrap(); + std::fs::copy(&a, &c).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap(); + assert_eq!(ids(&r, "imported"), 2, "browsing shows both paths: {r}"); + let scan = s.execute("library.importPreview", &json!({"paths": [a, b, c]})).unwrap(); + assert_eq!(scan["duplicates"], 2, "only one candidate per content: {scan}"); + let r = s.execute("library.import", &json!({"paths": [a, b, c]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(ids(&r, "duplicates"), 2); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1); + assert_eq!(s.catalog.photos().filter(|p| p.local).count(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 0); + assert_eq!(s.catalog.photos().filter(|p| p.local).count(), 2); + let _ = std::fs::remove_dir_all(src); +} + +#[test] +fn local_twin_promotion_counts_across_background_import_batches() { + use crate::import::{ImportJob, ImportOptions, commit_prepared}; + let src = temp_dir("local-twin-worker"); + let a = src.join("a.png"); + let b = src.join("b.png"); + let c = src.join("c.png"); + write_png(&a, 74); + std::fs::copy(&a, &b).unwrap(); + std::fs::copy(&a, &c).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.rate", &json!({"ids": [id], "rating": 4})).unwrap(); + let mut job = ImportJob::new(&mut s, ImportOptions::default()).unwrap(); + let cancel = std::sync::atomic::AtomicBool::new(false); + let first = job.prepare(&[a.to_string_lossy().to_string()], &cancel); + let report = commit_prepared(&mut s, &job.opts, job.now(), first).unwrap(); + assert_eq!(report.imported, [id], "promote the existing record with its edits"); + assert_eq!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().rating, 4); + let next = job.prepare(&[b.to_string_lossy().to_string(), c.to_string_lossy().to_string()], &cancel); + let report = commit_prepared(&mut s, &job.opts, job.now(), next).unwrap(); + assert!(report.imported.is_empty()); + assert_eq!(report.duplicates.len(), 2); + assert!(report.duplicates.iter().all(|d| d.existing == Some(id))); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1); + let _ = std::fs::remove_dir_all(src); +} + #[test] fn recursive_import_with_duplicates() { let src = temp_dir("src"); diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index ea10219217..61854e37c4 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2472,5 +2472,6 @@ "Welcome": "Vítejte", "Next": "Další", "Get Started": "Začít", - "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie" + "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie", + "Keywords and presets apply to new files only, not to photos already in Local": "Klíčová slova a předvolby se použijí jen u nových souborů, ne u fotografií, které už jsou v Místních souborech" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index bc67606eb6..a85865e2a2 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3507,5 +3507,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Starten Sie die App mit --control 7980 (oder LIGHTCRAFT_CONTROL_PORT), dann verbindet lightcraft-cli mcp --connect einen Agenten mit ihr.", "Welcome": "Willkommen", "Next": "Weiter", - "Get Started": "Loslegen" + "Get Started": "Loslegen", + "Keywords and presets apply to new files only, not to photos already in Local": "Stichwörter und Vorgaben gelten nur für neue Dateien, nicht für Fotos, die schon in „Lokal“ sind" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index c34057bdfe..86f9d05066 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2426,5 +2426,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicia la aplicación con --control 7980 (o LIGHTCRAFT_CONTROL_PORT), y lightcraft-cli mcp --connect conecta un agente a ella.", "Welcome": "Bienvenido", "Next": "Siguiente", - "Get Started": "Empezar" + "Get Started": "Empezar", + "Keywords and presets apply to new files only, not to photos already in Local": "Las palabras clave y los ajustes preestablecidos solo se aplican a archivos nuevos, no a fotos que ya están en Local" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 59cc611cd6..fbc07fdb3c 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2383,5 +2383,6 @@ "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", "Bottom bar": "Alapalkki", - "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää" + "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", + "Keywords and presets apply to new files only, not to photos already in Local": "Avainsanat ja esiasetukset koskevat vain uusia tiedostoja, eivät kuvia, jotka ovat jo Paikallisessa" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 31e6814b6d..0d77a834c9 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3609,5 +3609,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Démarrez l'application avec --control 7980 (ou LIGHTCRAFT_CONTROL_PORT), puis lightcraft-cli mcp --connect y connecte un agent.", "Welcome": "Bienvenue", "Next": "Suivant", - "Get Started": "Commencer" + "Get Started": "Commencer", + "Keywords and presets apply to new files only, not to photos already in Local": "Les mots-clés et les préréglages ne s'appliquent qu'aux nouveaux fichiers, pas aux photos déjà dans Local" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 52705328cc..ac0c504495 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2397,5 +2397,6 @@ "Top bar": "Bilah atas", "Tool strip": "Bilah alat", "Bottom bar": "Bilah bawah", - "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto" + "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", + "Keywords and presets apply to new files only, not to photos already in Local": "Kata kunci dan prasetel hanya berlaku untuk berkas baru, bukan foto yang sudah ada di Lokal" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 5b0ccc0cee..414618c1ca 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2590,5 +2590,6 @@ "Welcome": "Benvenuto", "Next": "Avanti", "Get Started": "Inizia", - "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto" + "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto", + "Keywords and presets apply to new files only, not to photos already in Local": "Parole chiave e preset si applicano solo ai file nuovi, non alle foto già in Locale" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 97c15dd019..5ad60f83f7 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2424,5 +2424,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "アプリを --control 7980 (または LIGHTCRAFT_CONTROL_PORT) で起動してから、lightcraft-cli mcp --connect でエージェントを接続できます。", "Welcome": "ようこそ", "Next": "次へ", - "Get Started": "始める" + "Get Started": "始める", + "Keywords and presets apply to new files only, not to photos already in Local": "キーワードとプリセットは新しいファイルにのみ適用され、すでにローカルにある写真には適用されません" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 30769b60fa..2040de0f9b 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3692,5 +3692,6 @@ "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", - "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის" + "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", + "Keywords and presets apply to new files only, not to photos already in Local": "საკვანძო სიტყვები და პრესეტები მხოლოდ ახალ ფაილებზე მოქმედებს და არა იმ ფოტოებზე, რომლებიც უკვე ლოკალშია" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index dbc29a1941..9bdecc918e 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2348,5 +2348,6 @@ "Welcome": "Witamy", "Next": "Dalej", "Get Started": "Zaczynamy", - "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć" + "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć", + "Keywords and presets apply to new files only, not to photos already in Local": "Słowa kluczowe i ustawienia predefiniowane dotyczą tylko nowych plików, nie zdjęć, które już są w Lokalnych" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 3aedd82906..9dd4d50965 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2270,5 +2270,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicie o aplicativo com --control 7980 (ou LIGHTCRAFT_CONTROL_PORT) e o lightcraft-cli mcp --connect conecta um agente a ele.", "Welcome": "Bem-vindo", "Next": "Próximo", - "Get Started": "Começar" + "Get Started": "Começar", + "Keywords and presets apply to new files only, not to photos already in Local": "Palavras-chave e predefinições valem só para arquivos novos, não para fotos que já estão em Local" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index b3df02470e..81d8ebe482 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2632,5 +2632,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустите приложение с --control 7980 (или LIGHTCRAFT_CONTROL_PORT), и команда lightcraft-cli mcp --connect подключит к нему одного агента.", "Welcome": "Добро пожаловать", "Next": "Далее", - "Get Started": "Начать" + "Get Started": "Начать", + "Keywords and presets apply to new files only, not to photos already in Local": "Ключевые слова и пресеты применяются только к новым файлам, а не к фото, которые уже есть в «Локальных»" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 94b9e30333..c1e08f5245 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2486,5 +2486,6 @@ "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", "Bottom bar": "Nedre fältet", - "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton" + "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", + "Keywords and presets apply to new files only, not to photos already in Local": "Nyckelord och förinställningar gäller bara nya filer, inte foton som redan finns i Lokalt" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 09b78fab1e..4cc5718792 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2422,5 +2422,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустіть програму з --control 7980 (або LIGHTCRAFT_CONTROL_PORT), і lightcraft-cli mcp --connect під'єднає до неї одного агента.", "Welcome": "Ласкаво просимо", "Next": "Далі", - "Get Started": "Почати" + "Get Started": "Почати", + "Keywords and presets apply to new files only, not to photos already in Local": "Ключові слова та пресети застосовуються лише до нових файлів, а не до фото, що вже є в «Локальних»" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index af27e9aa0a..75b8d72cb2 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2711,5 +2711,6 @@ "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", "Bottom bar": "Thanh dưới cùng", - "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác" + "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác", + "Keywords and presets apply to new files only, not to photos already in Local": "Từ khóa và cài đặt sẵn chỉ áp dụng cho tệp mới, không áp dụng cho ảnh đã có trong Cục bộ" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ca13d782a5..0afa044018 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2425,5 +2425,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 启动应用,lightcraft-cli mcp --connect 即可将一个智能体接入其中。", "Welcome": "欢迎", "Next": "下一步", - "Get Started": "开始使用" + "Get Started": "开始使用", + "Keywords and presets apply to new files only, not to photos already in Local": "关键词和预设仅应用于新文件,不适用于已在“本地”中的照片" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index f3dfc422ec..1b88ea6d80 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2426,5 +2426,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 啟動應用程式,lightcraft-cli mcp --connect 即可將一個代理程式連接到其中。", "Welcome": "歡迎", "Next": "下一步", - "Get Started": "開始使用" + "Get Started": "開始使用", + "Keywords and presets apply to new files only, not to photos already in Local": "關鍵字和預設集僅套用於新檔案,不適用於已在「本機」中的照片" } diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index 5ce31dacce..8a1c5fd914 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -150,10 +150,18 @@ impl ImportDialog { } } } + /// Candidate `i` is a file whose photo is only browsed (Local): the scan offers it (it isn't in the + /// library). Importing it brings that record into the library where + /// the file is, whatever the transfer mode. + pub fn is_browsed(&self, i: usize) -> bool { + self.candidates.get(i).is_some_and(|c| c.error.is_none() && c.duplicate.is_none() && c.local) + } /// Candidate `i` can be checked: a readable file the library doesn't have, or one whose photo - /// is in Recently Deleted — even with "Leave them", a click picks it (issue #1285). + /// is in Recently Deleted — even with "Leave them", a click picks it (issue #1285). A browsed + /// photo can't be copied or moved: the engine would add it in place, so copying leaves it out. pub fn importable(&self, i: usize) -> bool { self.candidates.get(i).is_some_and(|c| c.error.is_none() && (c.duplicate.is_none() || self.is_trashed(i))) + && !(self.copy && self.candidates.get(i).is_some_and(|c| c.local)) } /// Candidate `i` is checked by Check All and the file type toggles: with "Leave them", a file in /// Recently Deleted is only checked by hand. @@ -170,7 +178,7 @@ impl ImportDialog { } /// Any file of type `ty` is checked. pub fn type_checked(&self, ty: &str) -> bool { - self.candidates.iter().zip(&self.checked).any(|(c, on)| *on && file_type(c) == ty) + self.candidates.iter().zip(&self.checked).enumerate().any(|(i, (c, on))| *on && self.importable(i) && file_type(c) == ty) } /// Check (the importable ones) or uncheck every file of type `ty`: the raws only, say, and not /// the JPEGs kept beside them (issue #344). @@ -251,6 +259,12 @@ impl ImportDialog { o => Ok(Some(o.to_string())), } } + /// Keywords or a preset are set while a checked browsed photo would join the library as it is: + /// the engine applies them to new files only, so the review says so. + fn options_skip_browsed(&self) -> bool { + let has_options = !self.keywords().is_empty() || !self.preset.is_empty() || !self.metadata_preset.is_empty(); + has_options && !self.copy && (0..self.candidates.len()).any(|i| self.checked.get(i).copied().unwrap_or(false) && self.is_browsed(i)) + } fn keywords(&self) -> Vec { self.keywords.split(',').map(str::trim).filter(|k| !k.is_empty()).map(str::to_string).collect() } @@ -280,6 +294,57 @@ mod tests { ImportDialog::new(candidates) } + /// A file whose photo is only browsed (Local) comes from the scan as an ordinary candidate that + /// still names its record: offered when adding in place; copying or moving would not copy it + /// (the engine adds it where it is), so there it counts as already in the library. + #[test] + fn a_browsed_photo_is_importable_only_when_adding_in_place() { + let mut d = dialog(); + d.candidates[5].local = true; + assert!(d.is_browsed(5) && d.importable(5)); + assert_eq!(dup_counts(&d), (0, 1, 0), "adding in place: not skipped"); + d.copy = true; + assert!(!d.importable(5), "copying leaves it where it is"); + assert!(!d.selected_paths().contains(&"img5.jpg".to_string())); + assert_eq!(dup_counts(&d), (1, 1, 0)); + assert!(!d.is_browsed(3), "a duplicate isn't browsed"); + // its library twin is in Recently Deleted: still offered in place ("Import as new" brings it in), never copied + d.copy = false; + d.candidates[4].local = true; + d.candidates[4].duplicate = Some("content".into()); + d.set_trashed(vec![false, false, false, false, true, false]); + assert!(d.importable(4)); + d.copy = true; + assert!(!d.importable(4), "copying would add it where it is"); + } + + /// A file type's toggle is on only for files that can be imported now. + #[test] + fn a_file_type_toggle_ignores_browsed_photos_that_copying_cannot_import() { + let mut c = ImportCandidate { path: "a.png".into(), local: true, ..Default::default() }; + c.format = "PNG".into(); + let mut d = ImportDialog::new(vec![c]); + d.copy = true; + assert!(!d.type_checked("PNG")); + d.copy = false; + assert!(d.type_checked("PNG")); + } + + /// The review warns that keywords and presets skip a browsed photo only when it matters. + #[test] + fn keywords_and_presets_are_flagged_only_when_a_browsed_photo_would_skip_them() { + let c = ImportCandidate { path: "a.png".into(), local: true, ..Default::default() }; + let mut d = ImportDialog::new(vec![c]); + assert!(!d.options_skip_browsed(), "nothing set, nothing to skip"); + d.keywords = "beach".into(); + assert!(d.options_skip_browsed()); + d.checked[0] = false; + assert!(!d.options_skip_browsed(), "unchecked: not imported anyway"); + d.checked[0] = true; + d.copy = true; + assert!(!d.options_skip_browsed(), "copying doesn't offer it"); + } + /// Identical copies inside the source folder are not "already in the library" (a fresh library /// said "8 already in the library"). #[test] diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 5228f7b95b..007c2247c1 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -74,7 +74,9 @@ pub(crate) fn note_dialog_bottom(ui: &egui::Ui) { pub(super) fn dup_counts(d: &ImportDialog) -> (usize, usize, usize) { let trashed = d.trashed.iter().filter(|t| **t).count(); let in_source = d.candidates.iter().filter(|c| c.duplicate.as_deref() == Some("content") && c.existing.is_none()).count(); - let dups = d.candidates.iter().filter(|c| c.duplicate.is_some()).count().saturating_sub(trashed).saturating_sub(in_source); + // (a browsed photo isn't offered while copying: it counts as already there) + let browsed = if d.copy { (0..d.candidates.len()).filter(|i| d.is_browsed(*i)).count() } else { 0 }; + let dups = (d.candidates.iter().filter(|c| c.duplicate.is_some()).count() + browsed).saturating_sub(trashed).saturating_sub(in_source); (dups, in_source, trashed) } @@ -337,6 +339,14 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { ); } } + if d.options_skip_browsed() { + let t = Tokens::get(ui.ctx()); + ui.label( + egui::RichText::new(crate::i18n::tr("Keywords and presets apply to new files only, not to photos already in Local")) + .color(t.text_dim) + .small(), + ); + } if d.trashed.iter().any(|t| *t) { field(ui, "In Recently Deleted", |ui| { let cur = match d.on_deleted.as_str() { @@ -583,6 +593,7 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial (Some(_), _) if in_trash => Some("In Recently Deleted"), (Some(r), _) if r == "path" => Some("In library"), (Some(_), _) => Some("Duplicate"), + (None, None) if d.copy && d.is_browsed(i) => Some("In library"), (None, Some(_)) => Some("Unreadable"), _ => None, }; diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index f4d22079a4..895156b186 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -356,7 +356,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { } // what the library doesn't know yet joins the Local view let queue: Vec = - out.candidates.iter().filter(|c| c.duplicate != Some("path".into()) && c.error.is_none()).map(|c| c.path.clone()).collect(); + out.candidates.iter().filter(|c| c.duplicate != Some("path".into()) && !c.local && c.error.is_none()).map(|c| c.path.clone()).collect(); if !queue.is_empty() { let undo0 = app.session.undo.len(); let total = queue.len(); diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index eb05be0c4c..fe819ae15f 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -3246,6 +3246,41 @@ fn cmd_q_quits() { assert!(h.quit_requested()); } +/// File → Import from Folder… on a folder that was browsed in Local offers its photos, adding +/// them in place (they aren't "In library" yet), and confirming brings them into the library. +#[test] +fn import_from_folder_offers_the_photos_browsed_in_local() { + let mut h = demo([1300.0, 900.0]); + let t = Duration::from_secs(10); + let dir = std::env::temp_dir().join(format!("lc-ui-browsed-import-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8::from_fn(24, 16, |x, y| [(x * 9) as u8, (y * 12) as u8, 80, 255]); + let o = lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }; + for (i, name) in ["a.png", "b.png"].iter().enumerate() { + let mut img = img.clone(); + img.data[0][0] = i as u8; // different bytes per file + std::fs::write(dir.join(name), lightcraft_engine::export::encode_image(&img, &o).unwrap()).unwrap(); + } + let library_before = h.app.session.catalog.photos().filter(|p| !p.local).count(); + let r = h.request("engine.execute", json!({"command": "library.browse", "params": {"path": dir.to_string_lossy()}}), t); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(h.app.session.catalog.photos().filter(|p| p.local).count(), 2, "both browsed"); + let r = h.request("engine.execute", json!({"command": "file.addFolder", "params": {"path": dir.to_string_lossy()}}), t); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let Some(crate::state::Dialog::Import { opts }) = &h.app.ui.dialog else { panic!("no import review: {:?}", h.app.ui.dialog) }; + assert_eq!(opts.candidates.len(), 2); + assert!(opts.candidates.iter().all(|c| c.duplicate.is_none()), "browsed is not \"In library\": {:?}", opts.candidates); + assert_eq!(opts.selected_paths().len(), 2, "both offered, checked"); + assert_eq!(h.request("ui.dialog.confirm", json!({}), t)["ok"], true); + h.settle(SETTLE); + assert_eq!(h.app.session.catalog.photos().filter(|p| !p.local).count(), library_before + 2, "both joined the library"); + assert_eq!(h.app.session.catalog.photos().filter(|p| p.local).count(), 0); + let _ = std::fs::remove_dir_all(&dir); +} + /// File → Import from Folder… opens the import review for a folder (searched recursively). #[test] fn add_folder_opens_the_import_review() { diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 49bfe4ec9c..236fedcf39 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -71,7 +71,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with a remembered 80–320 pt thumbnail-size slider (default 116, independent of the library grid), density-aware previews capped at 1024 px and retention limited to nearby cells; tiny sources are tried once per requested size bucket; renderable raws use a sharper render when the camera JPEG is undersized, retaining the JPEG for preview-only raws or an unavailable/failed render; the pre-import loupe and keyboard culling remain open under #2056; thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step; when a Copy rename sequence runs out, remaining files are reported as failed and earlier completed transfers stay accounted for. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`). An import (and a scan of a folder scanned before) checks that each file a scan already probed is as it was by asking the disk about up to 16 files at a time (an import batch's files, at most), not one after another (`stat_all`, `crates/engine/src/import/files.rs`), and looks up the sidecars of a batch's photos the same way (`sidecars_of`); on a network share each file was a round trip When the scan left something out, one line under the count says so: the folder walk stopped at its depth or entry limit (“Stopped at the scan limit: there may be more photos”), folders it could not read, and files in the folders that are not a supported photo type (XMP sidecars, which the import reads with their photos, and hidden files are never counted; a file named on its own is always tried); nothing is shown when nothing was left out. `library.importPreview` returns the same as `scanLimited` and `skipped` (`unreadable`, `unsupported`). Browse Folder, Find Missing Photos and the command-line / MCP folder expansion walk with the same limits but do not report these counts (`crates/engine/src/walk.rs`, `crates/engine/src/import.rs`) | | LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → the import review), `crates/ui-egui/src/drop_overlay.rs`, `crates/ui-egui/src/tests/drop_import.rs` | while files are dragged over the window a veil and a card say what dropping does (review N items for import, import N presets, open the face model; a note to close the open dialog first when one is open); photos and folders open the import review as File ▸ Import does (Settings ▸ Import ▸ Import dropped files without review imports them at once; the web build always does); with no library open on the desktop (the launch list, a library that couldn't open) photos wait for the library opened and presets are refused, and the card says so; a drop while a dialog is open (also in the web build) or while an import is running is refused with a toast, and the card says so; a finished scan waits for an open dialog to close before its review opens; the control channel's `ui.dropFiles` hovers or drops files for scripts; dropping onto a specific album not supported | -| LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests/import.rs` | | +| LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests/import.rs`, `crates/ui-egui/src/dialogs/import.rs`, `crates/ui-egui/src/headless/tests.rs` | Only library records (including Recently Deleted) count as existing content; a copy merely browsed in Local does not block importing another path. A browsed file at the same path is offered by the scan (not "In library") and promoted with its edits, unless a library match or an earlier promotion already has its content; background import batches deduplicate promoted files too. The review offers such a file only when adding in place (copy and move would add it where it is), and notes that keywords and presets apply to new files only. | | LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/dialogs/import.rs`) | | LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/dialogs/settings.rs` | Settings ▸ Import ▸ Auto Import: a watched folder whose new photos are added (in place or copied) once complete, into an optional album; scanned every 3 s | | LR-IMP-PRESET | Preset on import | P2 | ✅ | `cmd:library.import` (`preset`) | chosen in the import review; one History entry | @@ -1013,6 +1013,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | | 2026-10-28 | patch | LR-VIEW-PHOTOGRID: the grid's empty-view message (shown when a view other than the library is empty) used a fixed "Cmd+Shift+I" (or a translation's fixed copy of it) whatever the platform or the binding, on one line that ran out of a narrow window; it now shows Import Photos' shortcut as the menu bar writes it and as it is bound on its own line, and none when it is unbound, and the sentence wraps; status unchanged (✅) | +| 2026-10-25 | minor | LR-IMP-DUPES: the Import review offers a file that was only browsed in Local (adding in place; copy and move leave it out) instead of listing it as "In library", and a copy browsed under another path no longer blocks importing the library's own file, including after permanent deletion and a restart; a library match is checked before a browsed copy is promoted, and promoted content counts across background batches. Ported from #1433 (Clearfall); status unchanged (✅) | | 2026-10-22 | patch | LRC-LIB-MISSING: `library.missing` from the control channel (an agent, `mcp --connect`) checks the photos' files on a worker thread under a "Missing Photos" row in the activity stack (counts the files, ✕ stops it) and is answered when the check ends, instead of freezing the window while the UI thread looked at every file (minutes on a large library on a network share); status unchanged (✅) | | 2026-10-27 | patch | MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Select Only Active Photo and Paste Settings from Previous were not in the Edit menu's layout and ended up after Settings…, near the end of the menu; they now sit with the other Select and Paste rows. On macOS the Edit menu no longer shows two separators in a row where Settings… moved to the app menu; status unchanged (✅) | | 2026-10-27 | patch | MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say that Close Window and the red close button of the main window quit the app, after the check Quit makes; kept on purpose; a user page says so; status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index ab0f90c033..9691bb0b40 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -193,6 +193,12 @@ selected Object mask, and a click on the selected mask's own pin adds nothing. Subject, Sky, Background and the range masks still have no pin. +### A dialog no longer dims the macOS title bar +- On macOS the top bar is the window's title bar, and the window buttons drawn over it stayed bright while a dialog dimmed + the bar under them. As under a macOS sheet, the dialog's backdrop now leaves the bar alone: its buttons are inactive, a + click on it does not close the dialog, and dragging its empty space still moves the window. Windows, Linux and full + screen are unchanged. + ## 2026-10-28 ### The empty photo grid names Import Photos' shortcut as it is bound @@ -215,6 +221,26 @@ `folder.rename` and `folder.move` commands now refuse the home folder and its Pictures, Desktop and Downloads too, so a script or an agent can't do it either. +### The window's parts are named for screen readers +- The top bar, the tool strip and the bottom bar are now announced as toolbars (Top bar, Tool strip, Bottom bar), and the + sidebar (Library), the photos, the Tools panel (or Presets) and the filmstrip as landmarks, so a screen reader can list + them and jump to one instead of walking every control. Nothing on screen changes. Not yet tried with a real VoiceOver session. + +### Dialogs are exposed to screen readers as dialogs +- Export, Settings and the other dialogs, the library chooser and the prompts that stop the window (the quit question, a + library that could not be opened, a settings file problem) are now exposed to screen readers as dialogs: modal ones, so the + rest of the window is marked as blocked while one is open, and an alert dialog for the prompts. The answer to Check for + Updates is a dialog too, but not a modal one. Before, each was a plain group that only carried the dialog's title. +- An alert dialog also carries what it says as its description: a screen reader can read the library problem's path, error and + explanation, or a prompt's text, together with the dialog. + +### Screen readers no longer read the shortcut with every button name +- Icon-only buttons (the tool strip, the view buttons and Before/After and Filmstrip in the bottom bar, the top bar's + Import Photos…, the mask overlay and White Balance Selector buttons, the slideshow controls) are now announced by + their label alone ("Edit", "Presets", "Photo Grid"), and the shortcut is the button's description ("E", "Shift+P", + "G"), which VoiceOver reads after a pause or on request. Before, it read "Edit (E)" every time it landed on the + button. This holds in every language, including Japanese and Traditional Chinese, which write the shortcut in + full-width brackets. The tooltip you see on hover is unchanged. ## 2026-10-27 @@ -259,39 +285,17 @@ drag to change it" is its description. It was named "Exposure: Click to type a value, drag to change it", so VoiceOver read the whole sentence each time it reached the field, once for every slider in the Edit panel. -## 2026-10-29 - -### A dialog no longer dims the macOS title bar -- On macOS the top bar is the window's title bar, and the window buttons drawn over it stayed bright while a dialog dimmed - the bar under them. As under a macOS sheet, the dialog's backdrop now leaves the bar alone: its buttons are inactive, a - click on it does not close the dialog, and dragging its empty space still moves the window. Windows, Linux and full - screen are unchanged. - -## 2026-10-28 - -### The window's parts are named for screen readers -- The top bar, the tool strip and the bottom bar are now announced as toolbars (Top bar, Tool strip, Bottom bar), and the - sidebar (Library), the photos, the Tools panel (or Presets) and the filmstrip as landmarks, so a screen reader can list - them and jump to one instead of walking every control. Nothing on screen changes. Not yet tried with a real VoiceOver session. - -### Dialogs are exposed to screen readers as dialogs -- Export, Settings and the other dialogs, the library chooser and the prompts that stop the window (the quit question, a - library that could not be opened, a settings file problem) are now exposed to screen readers as dialogs: modal ones, so the - rest of the window is marked as blocked while one is open, and an alert dialog for the prompts. The answer to Check for - Updates is a dialog too, but not a modal one. Before, each was a plain group that only carried the dialog's title. -- An alert dialog also carries what it says as its description: a screen reader can read the library problem's path, error and - explanation, or a prompt's text, together with the dialog. - -### Screen readers no longer read the shortcut with every button name -- Icon-only buttons (the tool strip, the view buttons and Before/After and Filmstrip in the bottom bar, the top bar's - Import Photos…, the mask overlay and White Balance Selector buttons, the slideshow controls) are now announced by - their label alone ("Edit", "Presets", "Photo Grid"), and the shortcut is the button's description ("E", "Shift+P", - "G"), which VoiceOver reads after a pause or on request. Before, it read "Edit (E)" every time it landed on the - button. This holds in every language, including Japanese and Traditional Chinese, which write the shortcut in - full-width brackets. The tooltip you see on hover is unchanged. - ## 2026-10-25 +### Import from Folder… offers the photos you browsed in Local +- A folder you browsed in Local no longer shows its photos as "In library" and out of reach in the Import review: + they are offered, checked, and importing them brings the browsed photos (with their edits) into the library where + they are. Copy and Move still leave them out, since they can't be copied from where they already are, and the + review says keywords and presets apply to new files only when they are set for such photos. +- A copy you only browsed in Local (another path with the same content) no longer makes the import report "already in + the library", even after the library photo was permanently deleted and the library reopened, and a library photo + with the same content is matched before a browsed copy is promoted. Several browsed copies of one file import once. + ### A one-field white balance edit no longer shifts the other one - Settings that name only a white balance temperature, or only a tint — `develop.merge`, `lightcraft-cli render --settings `, an MCP `set_develop {settings: …}` call, or a hand-written @@ -313,9 +317,6 @@ declared totals agree, and every APP2 segment is complete. Reordered valid chunks still work. An invalid sequence uses the existing unsupported-profile sRGB fallback, including when the JPEG is a raw preview. - -## 2026-10-25 - ### `>=` and `<=` work in the search box - Fielded search tokens now take inclusive comparisons: `rating:>=3`, `iso:<=400`, `f:>=2.8`, `focal:<=50`. Before, the `=` was read as part of the number, so such a search quietly showed no photos at all. @@ -343,7 +344,6 @@ a second. On a Mac the window also holds one drawable less: its width × height × 4 bytes, 15–22 MB for a 1200–1500-point-wide window on a Retina display. - ## 2026-10-24 ### AI Denoise follows the photo's real noise From 37ee678a12ac97d07130242c3e069580fb16a695 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 08:56:48 -0400 Subject: [PATCH 02/11] LR-IMP-DUPES: the options notice also shows when Import as new promotes a browsed photo whose content is in Recently Deleted --- crates/ui-egui/src/dialogs/import.rs | 32 +++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index 8a1c5fd914..5d08dee41f 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -259,11 +259,21 @@ impl ImportDialog { o => Ok(Some(o.to_string())), } } + /// Importing checked candidate `i` as it stands joins the library with the browsed record it + /// names, as the engine's `Promote` does: a browsed file the library doesn't have, or one whose + /// content is in Recently Deleted under "Import as new" (which replaces the trashed photo). + /// "Restore them" brings the trashed photo back instead and "Leave them" skips the file. + fn promotes_browsed(&self, i: usize) -> bool { + !self.copy + && self.checked.get(i).copied().unwrap_or(false) + && self.candidates.get(i).is_some_and(|c| c.local && c.error.is_none()) + && (self.is_browsed(i) || (self.is_trashed(i) && self.on_deleted == "fresh")) + } /// Keywords or a preset are set while a checked browsed photo would join the library as it is: /// the engine applies them to new files only, so the review says so. fn options_skip_browsed(&self) -> bool { let has_options = !self.keywords().is_empty() || !self.preset.is_empty() || !self.metadata_preset.is_empty(); - has_options && !self.copy && (0..self.candidates.len()).any(|i| self.checked.get(i).copied().unwrap_or(false) && self.is_browsed(i)) + has_options && (0..self.candidates.len()).any(|i| self.promotes_browsed(i)) } fn keywords(&self) -> Vec { self.keywords.split(',').map(str::trim).filter(|k| !k.is_empty()).map(str::to_string).collect() @@ -345,6 +355,26 @@ mod tests { assert!(!d.options_skip_browsed(), "copying doesn't offer it"); } + /// A browsed photo whose content is in Recently Deleted is promoted only by "Import as new" (the + /// engine's `Fresh`, which purges the trashed twin); "Restore them" brings the trashed photo back + /// and "Leave them" skips the file, so neither imports the browsed record and the notice stays off. + #[test] + fn the_notice_follows_the_engines_promotion_of_a_browsed_photo_with_a_trashed_twin() { + let c = ImportCandidate { path: "a.png".into(), local: true, duplicate: Some("content".into()), existing: Some(7), ..Default::default() }; + let mut d = ImportDialog::new(vec![c]); + d.set_trashed(vec![true]); + d.keywords = "beach".into(); + d.set_on_deleted("restore"); + assert!(d.checked[0] && !d.options_skip_browsed(), "Restore brings the trashed photo back, not the browsed one"); + d.set_on_deleted("fresh"); + assert!(d.checked[0] && d.options_skip_browsed(), "Import as new promotes the browsed record without the keywords"); + d.set_on_deleted(""); + assert!(!d.checked[0] && !d.options_skip_browsed(), "Leave them: unchecked"); + d.set_on_deleted("fresh"); + d.copy = true; + assert!(!d.options_skip_browsed(), "copying doesn't offer it"); + } + /// Identical copies inside the source folder are not "already in the library" (a fresh library /// said "8 already in the library"). #[test] From 5f3f4352b5ba953a154e4da7a2c791494e69a5ab Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 10:56:22 -0400 Subject: [PATCH 03/11] LR-IMP-DUPES: twins of a browsed photo in one scan are identical copies in the source, not photos the library has; Copy brings in the first of them --- crates/engine/src/import/scan.rs | 15 +++- crates/engine/src/import/types.rs | 6 ++ crates/engine/src/tests/import.rs | 24 +++++++ crates/ui-egui/src/dialogs/import.rs | 83 ++++++++++++++++++++++- crates/ui-egui/src/dialogs/import/body.rs | 16 ++--- docs/parity-checklist.md | 3 +- docs/whats-new.md | 3 + 7 files changed, 137 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index adaa088f25..61ffff0bea 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -350,8 +350,10 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc library_hashes(&input.library, probed_hashes).into_iter().map(|(h, id)| (h, Some(id.0))).collect(); let mut out = Vec::with_capacity(files.len()); let mut kept = HashMap::new(); + // (a content's first copy when it is a browsed file: its path, for the copies that follow it) + let mut browsed_first: HashMap = HashMap::new(); for f in files { - if let Some((id, c, hash)) = by_path.get(Path::new(&f)) { + if let Some((_, c, hash)) = by_path.get(Path::new(&f)) { let mut c = c.clone(); c.name = Path::new(&f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| f.clone()); // a browsed file the library has the content of (or an earlier file here promotes) is a duplicate @@ -362,9 +364,15 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc Some(existing) => { c.duplicate = Some("content".into()); c.existing = *existing; + if existing.is_none() { + c.browsed_twin = browsed_first.get(h).cloned(); + } } None => { - seen_hash.insert(h.clone(), Some(id.0)); + // (the library doesn't have it: a browsed record isn't a library photo, and + // the import looks the library up when it runs) + seen_hash.insert(h.clone(), None); + browsed_first.insert(h.clone(), f.clone()); } } } @@ -385,6 +393,9 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc Some(existing) => { c.duplicate = Some("content".into()); c.existing = *existing; + if existing.is_none() { + c.browsed_twin = browsed_first.get(h).cloned(); + } } None => { seen_hash.insert(h.clone(), None); diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index 4e06d6846a..e13347faa4 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -143,6 +143,12 @@ pub struct ImportCandidate { /// the library, so it is not a duplicate and importing it promotes that record. #[serde(skip_serializing_if = "std::ops::Not::not")] pub local: bool, + /// On a `"content"` duplicate that no library photo accounts for: the path of the browsed + /// candidate (`local`) earlier in this list that has the same bytes. It is the one the import + /// brings in (adding in place), so this one is a copy in the source; when copying leaves that + /// browsed photo out, the first such copy is what comes in instead. + #[serde(skip_serializing_if = "Option::is_none")] + pub browsed_twin: Option, /// Not readable. pub error: Option, /// A raw variant that can't be decoded yet (why): it imports as preview only. diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index f83ee8c154..d6e6a52666 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -273,6 +273,30 @@ fn local_twins_are_deduplicated_when_promoted_in_one_import() { let _ = std::fs::remove_dir_all(src); } +#[test] +fn twins_of_a_browsed_photo_are_copies_in_the_source_not_library_duplicates() { + let src = temp_dir("local-twin-scan"); + let a = src.join("a.png"); + let b = src.join("b.png"); + let c = src.join("c.png"); + write_png(&a, 75); + std::fs::copy(&a, &b).unwrap(); + std::fs::copy(&a, &c).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [a, b, c]})).unwrap(); + let found = scan["candidates"].as_array().unwrap(); + assert_eq!(found.len(), 3, "{scan}"); + assert_eq!(found[0]["local"], true, "{scan}"); + assert!(found[0]["duplicate"].is_null(), "the first browsed copy is offered: {scan}"); + for twin in &found[1..] { + assert_eq!(twin["duplicate"], "content", "{scan}"); + assert!(twin["existing"].is_null(), "no library photo has these bytes, a browsed record isn't one: {scan}"); + assert_eq!(twin["browsedTwin"], found[0]["path"], "a copy of what the first browsed photo is: {scan}"); + } + let _ = std::fs::remove_dir_all(src); +} + #[test] fn local_twin_promotion_counts_across_background_import_batches() { use crate::import::{ImportJob, ImportOptions, commit_prepared}; diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index 5d08dee41f..bf5b9541f3 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -158,10 +158,39 @@ impl ImportDialog { } /// Candidate `i` can be checked: a readable file the library doesn't have, or one whose photo /// is in Recently Deleted — even with "Leave them", a click picks it (issue #1285). A browsed - /// photo can't be copied or moved: the engine would add it in place, so copying leaves it out. + /// photo can't be copied or moved: the engine would add it in place, so copying leaves it out + /// (and brings in its first twin instead, [`ImportDialog::is_copy_twin`]). pub fn importable(&self, i: usize) -> bool { self.candidates.get(i).is_some_and(|c| c.error.is_none() && (c.duplicate.is_none() || self.is_trashed(i))) && !(self.copy && self.candidates.get(i).is_some_and(|c| c.local)) + || self.is_copy_twin(i) + } + /// Copying leaves a browsed photo out, so a file with the same bytes that no library photo has + /// is what brings that content in: candidate `i` is the first such file of its browsed twin. + /// (The scan lists it as a copy in the source of the browsed photo, `browsed_twin`.) + pub fn is_copy_twin(&self, i: usize) -> bool { + if !self.copy { + return false; + } + let Some(c) = self.candidates.get(i) else { return false }; + let Some(twin) = &c.browsed_twin else { return false }; + c.error.is_none() + && !c.local + && c.duplicate.as_deref() == Some("content") + && c.existing.is_none() + && self.candidates.iter().any(|b| b.local && b.path == *twin) + && !self.candidates[..i].iter().any(|e| !e.local && e.error.is_none() && e.browsed_twin.as_ref() == Some(twin)) + } + /// Choose how the files are brought in. Copying offers the twins that stand in for browsed photos + /// ([`ImportDialog::is_copy_twin`]), checked; adding in place takes them away again. + pub fn set_transfer(&mut self, copy: bool, move_files: bool) { + self.copy = copy; + self.move_files = copy && move_files; + for i in 0..self.candidates.len() { + if self.candidates[i].browsed_twin.is_some() && !self.candidates[i].local { + self.checked[i] = self.is_copy_twin(i); + } + } } /// Candidate `i` is checked by Check All and the file type toggles: with "Leave them", a file in /// Recently Deleted is only checked by hand. @@ -328,6 +357,58 @@ mod tests { assert!(!d.importable(4), "copying would add it where it is"); } + /// a.png and b.png are browsed copies of one content, c.png a new file with it (the scan reads + /// them as in `twins_of_a_browsed_photo_are_copies_in_the_source_not_library_duplicates`). + fn browsed_twins() -> ImportDialog { + let a = ImportCandidate { path: "a.png".into(), local: true, existing: Some(1), ..Default::default() }; + let twin = |path: &str, local: bool| ImportCandidate { + path: path.into(), + local, + duplicate: Some("content".into()), + browsed_twin: Some("a.png".into()), + ..Default::default() + }; + ImportDialog::new(vec![a, twin("b.png", true), twin("c.png", false), twin("d.png", false)]) + } + + /// Adding in place the browsed photo is the one brought in and its twins are copies in the + /// source, not photos the library has. + #[test] + fn twins_of_a_browsed_photo_are_copies_in_the_source_not_in_the_library() { + let d = browsed_twins(); + assert_eq!(d.selected_paths(), ["a.png"]); + assert_eq!(dup_counts(&d), (0, 3, 0), "three identical copies, none already in the library"); + } + + /// Copying leaves the browsed photo out (the engine would add it where it is), so the first + /// twin that is a file of its own is what copying brings in: the content isn't in the library. + #[test] + fn copying_brings_in_the_first_twin_of_a_browsed_photo() { + let mut d = browsed_twins(); + d.copy = true; + assert!(!d.importable(0) && !d.importable(1), "browsed photos are not copied"); + assert!(d.importable(2), "the first copy that is a file of its own is"); + assert!(!d.importable(3), "the next one is a copy of it"); + d.checked[2] = true; + assert_eq!(d.selected_paths(), ["c.png"]); + assert_eq!(dup_counts(&d), (1, 2, 0), "a (browsed) counts as there already; b and d are copies; c is offered"); + // back in place: it is a copy again + d.copy = false; + assert!(!d.importable(2)); + assert_eq!(d.selected_paths(), ["a.png"]); + } + + /// Switching to Copy checks the twin that copying brings in, and switching back unchecks it. + #[test] + fn switching_the_transfer_checks_the_twin_that_copying_brings_in() { + let mut d = browsed_twins(); + d.set_transfer(true, false); + assert_eq!(d.selected_paths(), ["c.png"]); + d.set_transfer(false, false); + assert_eq!(d.selected_paths(), ["a.png"]); + assert!(!d.checked[2]); + } + /// A file type's toggle is on only for files that can be imported now. #[test] fn a_file_type_toggle_ignores_browsed_photos_that_copying_cannot_import() { diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 007c2247c1..2dc4adc3c9 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -73,10 +73,12 @@ pub(crate) fn note_dialog_bottom(ui: &egui::Ui) { /// the same bytes as one earlier in the list (no library photo) is a copy in the source. pub(super) fn dup_counts(d: &ImportDialog) -> (usize, usize, usize) { let trashed = d.trashed.iter().filter(|t| **t).count(); - let in_source = d.candidates.iter().filter(|c| c.duplicate.as_deref() == Some("content") && c.existing.is_none()).count(); + // (a copy of a browsed photo that copying brings in, because it leaves the browsed one out, is neither) + let twins = (0..d.candidates.len()).filter(|i| d.is_copy_twin(*i)).count(); + let in_source = d.candidates.iter().filter(|c| c.duplicate.as_deref() == Some("content") && c.existing.is_none()).count() - twins; // (a browsed photo isn't offered while copying: it counts as already there) let browsed = if d.copy { (0..d.candidates.len()).filter(|i| d.is_browsed(*i)).count() } else { 0 }; - let dups = (d.candidates.iter().filter(|c| c.duplicate.is_some()).count() + browsed).saturating_sub(trashed).saturating_sub(in_source); + let dups = (d.candidates.iter().filter(|c| c.duplicate.is_some()).count() + browsed).saturating_sub(trashed + twins).saturating_sub(in_source); (dups, in_source, trashed) } @@ -206,23 +208,20 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { .on_hover_text(crate::i18n::tr("Reference the files where they are")) .clicked() { - d.copy = false; - d.move_files = false; + d.set_transfer(false, false); } let can_copy = app.session.library.as_ref().is_some_and(|l| l.on_disk) || app.services.pick_folder.is_some(); let r = ui.add_enabled_ui(can_copy, |ui| crate::widgets::text_button(ui, "importCopy", crate::i18n::tr("Copy"), d.copy && !d.move_files)).inner; if r.on_hover_text(crate::i18n::tr("Copy the files (into the library's Originals/, or a folder you choose)")).clicked() { - d.copy = true; - d.move_files = false; + d.set_transfer(true, false); } let r = ui.add_enabled_ui(can_copy, |ui| crate::widgets::text_button(ui, "importMove", crate::i18n::tr("Move"), d.copy && d.move_files)).inner; if r.on_hover_text(crate::i18n::tr("Move the files (into the library's Originals/, or a folder you choose), removing them from the source")) .clicked() { - d.copy = true; - d.move_files = true; + d.set_transfer(true, true); } }); let r = ui.label( @@ -590,6 +589,7 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial let badge = match (&c.duplicate, &c.error) { // checked with "Leave them", the file goes without `onDeleted`: the engine restores it (Some(_), _) if in_trash && on => Some(if d.on_deleted == "fresh" { "Will be replaced" } else { "Will be restored" }), + (Some(_), _) if d.is_copy_twin(i) => None, (Some(_), _) if in_trash => Some("In Recently Deleted"), (Some(r), _) if r == "path" => Some("In library"), (Some(_), _) => Some("Duplicate"), diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 236fedcf39..e592c8815c 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1013,8 +1013,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | | 2026-10-28 | patch | LR-VIEW-PHOTOGRID: the grid's empty-view message (shown when a view other than the library is empty) used a fixed "Cmd+Shift+I" (or a translation's fixed copy of it) whatever the platform or the binding, on one line that ran out of a narrow window; it now shows Import Photos' shortcut as the menu bar writes it and as it is bound on its own line, and none when it is unbound, and the sentence wraps; status unchanged (✅) | -| 2026-10-25 | minor | LR-IMP-DUPES: the Import review offers a file that was only browsed in Local (adding in place; copy and move leave it out) instead of listing it as "In library", and a copy browsed under another path no longer blocks importing the library's own file, including after permanent deletion and a restart; a library match is checked before a browsed copy is promoted, and promoted content counts across background batches. Ported from #1433 (Clearfall); status unchanged (✅) | -| 2026-10-22 | patch | LRC-LIB-MISSING: `library.missing` from the control channel (an agent, `mcp --connect`) checks the photos' files on a worker thread under a "Missing Photos" row in the activity stack (counts the files, ✕ stops it) and is answered when the check ends, instead of freezing the window while the UI thread looked at every file (minutes on a large library on a network share); status unchanged (✅) | +| 2026-10-25 | minor | LR-IMP-DUPES: the Import review offers a file that was only browsed in Local (adding in place; copy and move leave it out) instead of listing it as "In library", and a copy browsed under another path no longer blocks importing the library's own file, including after permanent deletion and a restart; a library match is checked before a browsed copy is promoted, and promoted content counts across background batches; files with a browsed photo's content are identical copies in the source, not library duplicates, and Copy or Move (which leave the browsed photo out) offer the first of them. Ported from #1433 (Clearfall); status unchanged (✅) | | 2026-10-27 | patch | MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Select Only Active Photo and Paste Settings from Previous were not in the Edit menu's layout and ended up after Settings…, near the end of the menu; they now sit with the other Select and Paste rows. On macOS the Edit menu no longer shows two separators in a row where Settings… moved to the app menu; status unchanged (✅) | | 2026-10-27 | patch | MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say that Close Window and the red close button of the main window quit the app, after the check Quit makes; kept on purpose; a user page says so; status unchanged (✅) | | 2026-10-17 | minor | LR-VIEW-PHOTOGRID, LR-VIEW-SQUAREGRID, LR-VIEW-FILMSTRIP, LR-VIEW-SURVEY, LR-VIEW-COMPARE, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: selection rings are theme tokens (3:1 or more against the grid; the active photo's 3 pt two-tone ring against the others' 1.5 pt), so the active photo is no longer a white ring lost on the light themes' grid; Compare, Reference and Survey frame their active photo and the People view its chosen person the same way; statuses unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index 9691bb0b40..70fc815b9e 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -295,6 +295,9 @@ - A copy you only browsed in Local (another path with the same content) no longer makes the import report "already in the library", even after the library photo was permanently deleted and the library reopened, and a library photo with the same content is matched before a browsed copy is promoted. Several browsed copies of one file import once. +- Files with the same content as a browsed photo are listed as identical copies in the folder, not as already in the + library, which doesn't have them. With Copy or Move, which leave the browsed photo out, the first of those files is + offered and checked instead, so that content can still be copied in from the folder. ### A one-field white balance edit no longer shifts the other one - Settings that name only a white balance temperature, or only a tint — `develop.merge`, From 6816af47c734b9feec8f183c89a580764f4a6a22 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 11:27:04 -0400 Subject: [PATCH 04/11] LR-IMP-DUPES: only the first file that stands in for a browsed photo is named in the scan, and the review opens in Copy mode with it checked --- crates/engine/src/import/scan.rs | 9 ++--- crates/engine/src/import/types.rs | 9 +++-- crates/engine/src/tests/import.rs | 11 ++++-- crates/ui-egui/src/dialogs/import.rs | 47 +++++++++++++---------- crates/ui-egui/src/dialogs/import/scan.rs | 2 +- 5 files changed, 44 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 61ffff0bea..071def6236 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -350,7 +350,7 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc library_hashes(&input.library, probed_hashes).into_iter().map(|(h, id)| (h, Some(id.0))).collect(); let mut out = Vec::with_capacity(files.len()); let mut kept = HashMap::new(); - // (a content's first copy when it is a browsed file: its path, for the copies that follow it) + // (a content's browsed first copy: its path, until the first file of its own with that content stands in for it) let mut browsed_first: HashMap = HashMap::new(); for f in files { if let Some((_, c, hash)) = by_path.get(Path::new(&f)) { @@ -364,9 +364,6 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc Some(existing) => { c.duplicate = Some("content".into()); c.existing = *existing; - if existing.is_none() { - c.browsed_twin = browsed_first.get(h).cloned(); - } } None => { // (the library doesn't have it: a browsed record isn't a library photo, and @@ -393,8 +390,10 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc Some(existing) => { c.duplicate = Some("content".into()); c.existing = *existing; + // (the first copy of a browsed photo that is a file of its own stands in for it when + // copying leaves the browsed one out: said once per content) if existing.is_none() { - c.browsed_twin = browsed_first.get(h).cloned(); + c.browsed_twin = browsed_first.remove(h); } } None => { diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index e13347faa4..7bab21b9f7 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -143,10 +143,11 @@ pub struct ImportCandidate { /// the library, so it is not a duplicate and importing it promotes that record. #[serde(skip_serializing_if = "std::ops::Not::not")] pub local: bool, - /// On a `"content"` duplicate that no library photo accounts for: the path of the browsed - /// candidate (`local`) earlier in this list that has the same bytes. It is the one the import - /// brings in (adding in place), so this one is a copy in the source; when copying leaves that - /// browsed photo out, the first such copy is what comes in instead. + /// On the first `"content"` duplicate that is a file of its own, when no library photo has its + /// bytes but a browsed candidate (`local`) earlier in this list does: the path of that browsed + /// candidate. Adding in place the browsed photo is the one brought in, and this is a copy in the + /// source; copying and moving leave the browsed photo out (the engine would add it where it is), + /// and this file is what they bring in instead. #[serde(skip_serializing_if = "Option::is_none")] pub browsed_twin: Option, /// Not readable. diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index d6e6a52666..b54960ae5a 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -279,21 +279,26 @@ fn twins_of_a_browsed_photo_are_copies_in_the_source_not_library_duplicates() { let a = src.join("a.png"); let b = src.join("b.png"); let c = src.join("c.png"); + let d = src.join("d.png"); write_png(&a, 75); std::fs::copy(&a, &b).unwrap(); std::fs::copy(&a, &c).unwrap(); + std::fs::copy(&a, &d).unwrap(); let mut s = Session::new().with_fs(); s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap(); - let scan = s.execute("library.importPreview", &json!({"paths": [a, b, c]})).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [a, b, c, d]})).unwrap(); let found = scan["candidates"].as_array().unwrap(); - assert_eq!(found.len(), 3, "{scan}"); + assert_eq!(found.len(), 4, "{scan}"); assert_eq!(found[0]["local"], true, "{scan}"); assert!(found[0]["duplicate"].is_null(), "the first browsed copy is offered: {scan}"); for twin in &found[1..] { assert_eq!(twin["duplicate"], "content", "{scan}"); assert!(twin["existing"].is_null(), "no library photo has these bytes, a browsed record isn't one: {scan}"); - assert_eq!(twin["browsedTwin"], found[0]["path"], "a copy of what the first browsed photo is: {scan}"); } + // (copying leaves the browsed photo out: the first file of its own stands in for it, once) + assert!(found[1]["browsedTwin"].is_null(), "a browsed twin doesn't: {scan}"); + assert_eq!(found[2]["browsedTwin"], found[0]["path"], "{scan}"); + assert!(found[3]["browsedTwin"].is_null(), "{scan}"); let _ = std::fs::remove_dir_all(src); } diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index bf5b9541f3..fc29b87bbe 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -166,27 +166,22 @@ impl ImportDialog { || self.is_copy_twin(i) } /// Copying leaves a browsed photo out, so a file with the same bytes that no library photo has - /// is what brings that content in: candidate `i` is the first such file of its browsed twin. - /// (The scan lists it as a copy in the source of the browsed photo, `browsed_twin`.) + /// is what brings that content in: candidate `i` is that file (the scan names the browsed photo + /// it stands in for, `browsed_twin`, on the first one only). pub fn is_copy_twin(&self, i: usize) -> bool { - if !self.copy { - return false; - } - let Some(c) = self.candidates.get(i) else { return false }; - let Some(twin) = &c.browsed_twin else { return false }; - c.error.is_none() - && !c.local - && c.duplicate.as_deref() == Some("content") - && c.existing.is_none() - && self.candidates.iter().any(|b| b.local && b.path == *twin) - && !self.candidates[..i].iter().any(|e| !e.local && e.error.is_none() && e.browsed_twin.as_ref() == Some(twin)) + self.copy + && self.candidates.get(i).is_some_and(|c| { + c.browsed_twin.is_some() && !c.local && c.error.is_none() && c.duplicate.as_deref() == Some("content") && c.existing.is_none() + }) } - /// Choose how the files are brought in. Copying offers the twins that stand in for browsed photos - /// ([`ImportDialog::is_copy_twin`]), checked; adding in place takes them away again. + /// Choose how the files are brought in. Switching to copying offers the file that stands in for + /// a browsed photo ([`ImportDialog::is_copy_twin`]), checked; switching to adding in place takes + /// it away again. pub fn set_transfer(&mut self, copy: bool, move_files: bool) { + let switched = copy != self.copy; self.copy = copy; self.move_files = copy && move_files; - for i in 0..self.candidates.len() { + for i in (0..self.candidates.len()).filter(|_| switched) { if self.candidates[i].browsed_twin.is_some() && !self.candidates[i].local { self.checked[i] = self.is_copy_twin(i); } @@ -357,18 +352,18 @@ mod tests { assert!(!d.importable(4), "copying would add it where it is"); } - /// a.png and b.png are browsed copies of one content, c.png a new file with it (the scan reads - /// them as in `twins_of_a_browsed_photo_are_copies_in_the_source_not_library_duplicates`). + /// a.png and b.png are browsed copies of one content, c.png and d.png new files with it; the scan + /// names a.png on c.png only (as in `twins_of_a_browsed_photo_are_copies_in_the_source_not_library_duplicates`). fn browsed_twins() -> ImportDialog { let a = ImportCandidate { path: "a.png".into(), local: true, existing: Some(1), ..Default::default() }; - let twin = |path: &str, local: bool| ImportCandidate { + let twin = |path: &str, local: bool, stands_in: bool| ImportCandidate { path: path.into(), local, duplicate: Some("content".into()), - browsed_twin: Some("a.png".into()), + browsed_twin: stands_in.then(|| "a.png".into()), ..Default::default() }; - ImportDialog::new(vec![a, twin("b.png", true), twin("c.png", false), twin("d.png", false)]) + ImportDialog::new(vec![a, twin("b.png", true, false), twin("c.png", false, true), twin("d.png", false, false)]) } /// Adding in place the browsed photo is the one brought in and its twins are copies in the @@ -409,6 +404,16 @@ mod tests { assert!(!d.checked[2]); } + /// Choosing the transfer already chosen doesn't undo what was checked by hand. + #[test] + fn choosing_the_transfer_again_keeps_a_manual_uncheck() { + let mut d = browsed_twins(); + d.set_transfer(true, false); + d.checked[2] = false; + d.set_transfer(true, true); + assert!(d.selected_paths().is_empty(), "Move after Copy keeps the choice"); + } + /// A file type's toggle is on only for files that can be imported now. #[test] fn a_file_type_toggle_ignores_browsed_photos_that_copying_cannot_import() { diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index 895156b186..1eaa61cd98 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -388,7 +388,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { }) .collect(); d.set_trashed(trashed); - d.copy = task.copy; + d.set_transfer(task.copy, false); // only an album the review offers (it may have been deleted while the scan ran) d.album = task.album.filter(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_some_and(|a| !a.folder && !a.is_smart())); d.sources = task.sources; From 0e5ece401cb3e2ab38616c4058138433b726d5da Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 11:43:09 -0400 Subject: [PATCH 05/11] LR-IMP-DUPES: the docs say the file Copy offers is the first one that isn't browsed itself --- docs/parity-checklist.md | 2 +- docs/whats-new.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e592c8815c..47e949b85c 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1013,7 +1013,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | | 2026-10-28 | patch | LR-VIEW-PHOTOGRID: the grid's empty-view message (shown when a view other than the library is empty) used a fixed "Cmd+Shift+I" (or a translation's fixed copy of it) whatever the platform or the binding, on one line that ran out of a narrow window; it now shows Import Photos' shortcut as the menu bar writes it and as it is bound on its own line, and none when it is unbound, and the sentence wraps; status unchanged (✅) | -| 2026-10-25 | minor | LR-IMP-DUPES: the Import review offers a file that was only browsed in Local (adding in place; copy and move leave it out) instead of listing it as "In library", and a copy browsed under another path no longer blocks importing the library's own file, including after permanent deletion and a restart; a library match is checked before a browsed copy is promoted, and promoted content counts across background batches; files with a browsed photo's content are identical copies in the source, not library duplicates, and Copy or Move (which leave the browsed photo out) offer the first of them. Ported from #1433 (Clearfall); status unchanged (✅) | +| 2026-10-25 | minor | LR-IMP-DUPES: the Import review offers a file that was only browsed in Local (adding in place; copy and move leave it out) instead of listing it as "In library", and a copy browsed under another path no longer blocks importing the library's own file, including after permanent deletion and a restart; a library match is checked before a browsed copy is promoted, and promoted content counts across background batches; files with a browsed photo's content are identical copies in the source, not library duplicates, and Copy or Move (which leave the browsed photo out) offer the first of them that isn't browsed itself. Ported from #1433 (Clearfall); status unchanged (✅) | | 2026-10-27 | patch | MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Select Only Active Photo and Paste Settings from Previous were not in the Edit menu's layout and ended up after Settings…, near the end of the menu; they now sit with the other Select and Paste rows. On macOS the Edit menu no longer shows two separators in a row where Settings… moved to the app menu; status unchanged (✅) | | 2026-10-27 | patch | MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say that Close Window and the red close button of the main window quit the app, after the check Quit makes; kept on purpose; a user page says so; status unchanged (✅) | | 2026-10-17 | minor | LR-VIEW-PHOTOGRID, LR-VIEW-SQUAREGRID, LR-VIEW-FILMSTRIP, LR-VIEW-SURVEY, LR-VIEW-COMPARE, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: selection rings are theme tokens (3:1 or more against the grid; the active photo's 3 pt two-tone ring against the others' 1.5 pt), so the active photo is no longer a white ring lost on the light themes' grid; Compare, Reference and Survey frame their active photo and the People view its chosen person the same way; statuses unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index 70fc815b9e..f74393eca8 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -296,8 +296,8 @@ the library", even after the library photo was permanently deleted and the library reopened, and a library photo with the same content is matched before a browsed copy is promoted. Several browsed copies of one file import once. - Files with the same content as a browsed photo are listed as identical copies in the folder, not as already in the - library, which doesn't have them. With Copy or Move, which leave the browsed photo out, the first of those files is - offered and checked instead, so that content can still be copied in from the folder. + library, which doesn't have them. With Copy or Move, which leave the browsed photo out, the first of those files + that isn't browsed itself is offered and checked instead, so that content can still be copied in from the folder. ### A one-field white balance edit no longer shifts the other one - Settings that name only a white balance temperature, or only a tint — `develop.merge`, From 6d4c305f5c68e90da15eeb191c4345ca4668d8a9 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 13:00:30 -0400 Subject: [PATCH 06/11] LR-IMP-DUPES: a browsed file replaced since it was browsed is read again before it joins the library --- crates/engine/src/import/commit.rs | 10 +++- crates/engine/src/import/job.rs | 34 +++++++++++-- crates/engine/src/import/scan.rs | 31 +++++++++++- crates/engine/src/tests/import.rs | 81 +++++++++++++++++++++++++++++- docs/whats-new.md | 3 ++ 5 files changed, 152 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 97e427b139..2e6863d5ce 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -208,12 +208,18 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut purged: std::collections::HashSet = Default::default(); for it in prepared.items { match it { - PreparedItem::Promote(id) => { + PreparedItem::Promote(id, fresh) => { + // the file was replaced since it was browsed: the record takes what it is now before it joins the library + if let Some(info) = &fresh { + crate::cmd::convert::reload_ops(&s.catalog, id, info, &mut ops, &mut Vec::new()); + } if s.catalog.photo(id).is_some_and(|p| p.local) { ops.push(Op::SetLocal { id, local: false }); } // "Import as new": a trashed photo with the same content is replaced, as for a new file - if let Some(old) = s.catalog.photo(id).and_then(|p| p.content_hash.as_ref()).and_then(|h| trash_hash.get(h)) + let content = + fresh.as_ref().and_then(|i| i.content_hash.clone()).or_else(|| s.catalog.photo(id).and_then(|p| p.content_hash.clone())); + if let Some(old) = content.as_ref().and_then(|h| trash_hash.get(h)) && purged.insert(*old) { purge.push(*old); diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index f84fc901a4..ee75d460c9 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -39,6 +39,9 @@ pub struct ImportJob { pub(super) library: Option<(lightcraft_catalog::Catalog, bool)>, /// path → (photo, a Local browse record?) pub(super) by_path: HashMap)>, + /// path → the size the record of a browsed (Local) file has: a file of another size has been replaced since + /// it was browsed ([`super::scan::local_file_changed`]) + local_sizes: HashMap, /// content hash → the photo that has it (`None`: a file earlier in this import) pub(super) by_hash: HashMap>, pub(super) probe: Option, @@ -67,8 +70,9 @@ pub struct Prepared { #[derive(Debug)] pub(super) enum PreparedItem { - /// A Local (browsed) record imported for real. - Promote(PhotoId), + /// A Local (browsed) record imported for real; with what its file is now when the file was replaced since it was + /// browsed (the record is brought up to date). + Promote(PhotoId, Option>), Duplicate { path: String, existing: Option, @@ -193,6 +197,7 @@ impl ImportJob { copy_root, library: Some((s.catalog.clone(), fresh)), by_path: HashMap::new(), + local_sizes: HashMap::new(), by_hash: HashMap::new(), probe: s.media.file_probe.clone(), file_bytes: s.media.file_bytes.clone(), @@ -241,6 +246,9 @@ impl ImportJob { } if let Source::File { path } = &p.source { self.by_path.insert(path.clone(), (p.id, p.local, p.content_hash.clone())); + if p.local { + self.local_sizes.insert(path.clone(), p.file_size); + } } // (a copy that was only browsed in Local isn't in the library) if !p.local @@ -261,9 +269,16 @@ impl ImportJob { let mode = self.mode; let mut out = Prepared { scanned: files.len(), items: Vec::new() }; let mut todo = Vec::new(); + // browsed files replaced since: probed again with `todo`, their records brought up to date as they join the library + let mut changed: HashMap = HashMap::new(); for f in files { match self.by_path.get(f.as_str()).cloned() { Some((id, true, hash)) if !opts.local => { + if super::scan::local_file_changed(&f, self.local_sizes.get(f.as_str()).copied().unwrap_or(0)) { + changed.insert(f.clone(), id); + todo.push(f); + continue; + } // a library photo with the same content comes first, and a file promoted earlier // (here or in a previous batch) counts as the library's from then on if let Some(h) = &hash { @@ -276,7 +291,7 @@ impl ImportJob { } // a file that was only browsed (Local) joins the library when it is imported for real self.by_path.insert(f, (id, false, hash)); - out.items.push(PreparedItem::Promote(id)); + out.items.push(PreparedItem::Promote(id, None)); self.done.fetch_add(1, Relaxed); } Some((id, _, _)) => { @@ -354,6 +369,19 @@ impl ImportJob { // same bytes as a library photo: skipped below, once its capture time is known let duplicate_of = info.content_hash.as_ref().filter(|_| !opts.local).and_then(|h| self.by_hash.get(h).map(|existing| (h.clone(), *existing))); + // a browsed file replaced since it was browsed, and not a copy of what the library has: its record takes what the + // file is now (size, dimensions, content) as it joins the library + if duplicate_of.is_none() + && let Some(id) = changed.remove(&path) + { + if let Some(h) = &info.content_hash { + self.by_hash.insert(h.clone(), Some(id)); + } + self.by_path.insert(path, (id, false, info.content_hash.clone())); + self.done.fetch_add(1, Relaxed); + plan.slots.push(Slot::Item(PreparedItem::Promote(id, Some(Box::new(info))))); + continue; + } // the XMP sidecar (or a raw's embedded XMP), read before copying: its capture time files // and names the copy when the file itself has none (a duplicate needs only that time) let raw = info.kind == MediaKind::Raw; diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 071def6236..7a9ab2ce50 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -48,6 +48,13 @@ pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[Stri by_path } +/// Whether the file of a browsed (Local) record is no longer the one that was browsed: its size on disk is not the +/// recorded one, the check the probes kept from a scan go by. A record without a size and a file that can't be read +/// count as unchanged (a file that is gone is the record's own business). +pub(super) fn local_file_changed(path: &str, recorded: u64) -> bool { + !cfg!(target_arch = "wasm32") && recorded > 0 && std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() != recorded) +} + /// Which photo of the library has each of the contents `hashes` (the later one where several /// have it; a copy that was only browsed in Local isn't in the library). One pass over the library, and an entry only for a content that was asked about. pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes: impl Iterator) -> HashMap { @@ -321,7 +328,18 @@ pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> /// them ([`expand_report`]). pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &ScanProgress) -> ScanOutput { use std::sync::atomic::Ordering::Relaxed; - let by_path = library_files(&input.library, &files); + let mut by_path = library_files(&input.library, &files); + // a browsed file that was replaced since is not the one its record describes: it is read again like a new file + // (the record's stored content, kept from the browse, would give the wrong answer against the library), and + // its candidate still names the record and says it was only browsed, unless the library has that content + let mut replaced: HashMap = HashMap::new(); + by_path.retain(|path, (id, c, _)| { + let changed = c.local && local_file_changed(&path.to_string_lossy(), c.file_size); + if changed { + replaced.insert(path.clone(), *id); + } + !changed + }); let todo: Vec = files.iter().filter(|f| !by_path.contains_key(Path::new(f))).cloned().collect(); progress.total.store(todo.len(), Relaxed); // probes from a preceding `scan` are reused when the file is unchanged (same size); a file that @@ -401,6 +419,17 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc } } } + if let Some(id) = replaced.get(Path::new(&f)) { + // still the browsed record's file, as for one that is as browsed: Copy and Move leave it out, and the + // first twin of its own stands in for it there + c.local = true; + if c.duplicate.is_none() { + c.existing = Some(id.0); + if let Some(h) = &info.content_hash { + browsed_first.insert(h.clone(), f.clone()); + } + } + } kept.insert(f, info); } Some(Err(e)) => c.error = Some(e), diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index b54960ae5a..eda7717688 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -22,7 +22,11 @@ fn temp_dir(tag: &str) -> std::path::PathBuf { /// A small procedural PNG (distinct per seed). fn write_png(path: &Path, seed: u8) { - let (w, h) = (48usize, 32usize); + write_png_sized(path, seed, 48, 32); +} + +/// [`write_png`] of another size: a replaced file is noticed by its size, as probes kept from a scan are. +fn write_png_sized(path: &Path, seed: u8, w: usize, h: usize) { let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 5) as u8, (i / w * 7) as u8, seed, 255]).collect(); let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); @@ -128,6 +132,81 @@ fn a_deleted_browse_record_still_counts_as_the_files_own() { let _ = std::fs::remove_dir_all(src); } +/// A browsed file that another application replaced since (it has another size) is not what its record says: the scan +/// reads it again, so the content stored at the browse (the old file's, which the library also has) doesn't make it a +/// duplicate, and importing it brings the record up to date as it joins the library. +#[test] +fn a_browsed_file_replaced_since_is_read_again_before_it_joins_the_library() { + let src = temp_dir("browsed-replaced"); + let (a, b) = (src.join("a.png"), src.join("b.png")); + write_png(&a, 75); + std::fs::copy(&a, &b).unwrap(); + let mut s = Session::new().with_fs(); + // b is in the library; a was only browsed, with the same bytes + s.execute("library.import", &json!({"paths": [b]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + let old = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().content_hash.clone(); + let scan = s.execute("library.importPreview", &json!({"paths": [a]})).unwrap(); + assert_eq!(scan["candidates"][0]["duplicate"], "content", "the file is what was browsed, and the library has its bytes: {scan}"); + write_png_sized(&a, 9, 64, 40); + let scan = s.execute("library.importPreview", &json!({"paths": [a]})).unwrap(); + assert!(scan["candidates"][0]["duplicate"].is_null(), "the file that is there now is new to the library: {scan}"); + assert_eq!(scan["candidates"][0]["width"], 64, "{scan}"); + assert_eq!(scan["candidates"][0]["local"], true, "it still says it was only browsed (Copy and Move leave it out): {scan}"); + assert_eq!(scan["candidates"][0]["existing"], id, "and names the record: {scan}"); + let r = s.execute("library.import", &json!({"paths": [a]})).unwrap(); + assert_eq!(r["imported"], json!([id]), "the same record joins the library: {r}"); + let p = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap(); + assert!(!p.local, "it is in the library now"); + assert_eq!((p.width, p.height, p.file_size), (64, 40, std::fs::metadata(&a).unwrap().len()), "the record describes the file it has now"); + assert_ne!(p.content_hash, old, "and holds its content, not the old file's"); + let _ = std::fs::remove_dir_all(src); +} + +/// A browsed file replaced by a copy of a photo the library has is a duplicate of that photo, and its record stays +/// browsed. +#[test] +fn a_browsed_file_replaced_by_a_copy_of_a_library_photo_is_a_duplicate() { + let src = temp_dir("browsed-replaced-dup"); + let (a, c) = (src.join("a.png"), src.join("c.png")); + write_png(&a, 75); + write_png_sized(&c, 9, 64, 40); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [c]})).unwrap(); + let library_id = r["imported"][0].as_u64().unwrap(); + let r = s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + std::fs::copy(&c, &a).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [a]})).unwrap(); + assert_eq!(scan["candidates"][0]["duplicate"], "content", "{scan}"); + assert_eq!(scan["candidates"][0]["existing"], library_id, "of the library's photo: {scan}"); + assert_eq!(scan["candidates"][0]["local"], true, "it is still the browsed record's file (Copy and Move leave it out): {scan}"); + let r = s.execute("library.import", &json!({"paths": [a]})).unwrap(); + assert_eq!(ids(&r, "imported"), 0, "{r}"); + assert_eq!(r["duplicates"][0]["existing"], library_id, "{r}"); + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().local, "the record was not brought in"); + let _ = std::fs::remove_dir_all(src); +} + +/// A file of its own with the new content of a replaced browsed file stands in for it when copying leaves it out. +#[test] +fn a_twin_of_a_replaced_browsed_file_stands_in_for_it_when_copying() { + let src = temp_dir("browsed-replaced-twin"); + let (a, d) = (src.join("a.png"), src.join("d.png")); + write_png(&a, 75); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + write_png_sized(&a, 9, 64, 40); + std::fs::copy(&a, &d).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [a, d]})).unwrap(); + let found = scan["candidates"].as_array().unwrap(); + assert_eq!(found[0]["local"], true, "{scan}"); + assert_eq!(found[1]["duplicate"], "content", "{scan}"); + assert_eq!(found[1]["browsedTwin"], found[0]["path"], "{scan}"); + let _ = std::fs::remove_dir_all(src); +} + /// "Import as new" replaces the trashed library photo with the same content when the browsed twin /// is promoted, as it does for a new file. #[test] diff --git a/docs/whats-new.md b/docs/whats-new.md index f74393eca8..0986faf62a 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -298,6 +298,9 @@ - Files with the same content as a browsed photo are listed as identical copies in the folder, not as already in the library, which doesn't have them. With Copy or Move, which leave the browsed photo out, the first of those files that isn't browsed itself is offered and checked instead, so that content can still be copied in from the folder. +- A browsed file that another application replaced since (its size on disk is no longer the one that was browsed) is + read again: it is compared with the library by what it is now, and importing it brings its record up to date (size, + dimensions, content) as it joins the library. ### A one-field white balance edit no longer shifts the other one - Settings that name only a white balance temperature, or only a tint — `develop.merge`, From df0b076db357c0c9e24fb25e9b16e0ee5c984961 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 13:23:33 -0400 Subject: [PATCH 07/11] LR-IMP-DUPES: a replaced browsed file does not take the stand-in of another browsed file --- crates/engine/src/import/scan.rs | 4 ++-- crates/engine/src/tests/import.rs | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 7a9ab2ce50..34a402a1ac 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -409,8 +409,8 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc c.duplicate = Some("content".into()); c.existing = *existing; // (the first copy of a browsed photo that is a file of its own stands in for it when - // copying leaves the browsed one out: said once per content) - if existing.is_none() { + // copying leaves the browsed one out: said once per content; a browsed file doesn't) + if existing.is_none() && !replaced.contains_key(Path::new(&f)) { c.browsed_twin = browsed_first.remove(h); } } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index eda7717688..a4840fbb11 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -207,6 +207,24 @@ fn a_twin_of_a_replaced_browsed_file_stands_in_for_it_when_copying() { let _ = std::fs::remove_dir_all(src); } +/// A browsed file replaced by a copy of another browsed file isn't a stand-in: the first file of its own is. +#[test] +fn a_replaced_browsed_file_does_not_take_the_stand_in_of_another_browsed_file() { + let src = temp_dir("browsed-replaced-standin"); + let (a, b, d) = (src.join("a.png"), src.join("b.png"), src.join("d.png")); + write_png(&a, 75); + write_png_sized(&b, 9, 64, 40); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap(); + std::fs::copy(&a, &b).unwrap(); + std::fs::copy(&a, &d).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [a, b, d]})).unwrap(); + let found = scan["candidates"].as_array().unwrap(); + assert!(found[1]["browsedTwin"].is_null(), "a browsed file doesn't stand in: {scan}"); + assert_eq!(found[2]["browsedTwin"], found[0]["path"], "the file of its own does: {scan}"); + let _ = std::fs::remove_dir_all(src); +} + /// "Import as new" replaces the trashed library photo with the same content when the browsed twin /// is promoted, as it does for a new file. #[test] From 1060c378d193bd103444710181884529c88cb43f Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 2 Nov 2026 17:29:59 -0500 Subject: [PATCH 08/11] integration: main's 10-22 revision row restored; the content-duplicate carries file: None (rebuild reference) --- crates/engine/src/import/job.rs | 2 +- docs/parity-checklist.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index ee75d460c9..c6d8b91009 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -283,7 +283,7 @@ impl ImportJob { // (here or in a previous batch) counts as the library's from then on if let Some(h) = &hash { if let Some(existing) = self.by_hash.get(h) { - out.items.push(PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash }); + out.items.push(PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, file: None }); self.done.fetch_add(1, Relaxed); continue; } diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 47e949b85c..b6863d4573 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1013,6 +1013,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | | 2026-10-28 | patch | LR-VIEW-PHOTOGRID: the grid's empty-view message (shown when a view other than the library is empty) used a fixed "Cmd+Shift+I" (or a translation's fixed copy of it) whatever the platform or the binding, on one line that ran out of a narrow window; it now shows Import Photos' shortcut as the menu bar writes it and as it is bound on its own line, and none when it is unbound, and the sentence wraps; status unchanged (✅) | +| 2026-10-22 | patch | LRC-LIB-MISSING: `library.missing` from the control channel (an agent, `mcp --connect`) checks the photos' files on a worker thread under a "Missing Photos" row in the activity stack (counts the files, ✕ stops it) and is answered when the check ends, instead of freezing the window while the UI thread looked at every file (minutes on a large library on a network share); status unchanged (✅) | | 2026-10-25 | minor | LR-IMP-DUPES: the Import review offers a file that was only browsed in Local (adding in place; copy and move leave it out) instead of listing it as "In library", and a copy browsed under another path no longer blocks importing the library's own file, including after permanent deletion and a restart; a library match is checked before a browsed copy is promoted, and promoted content counts across background batches; files with a browsed photo's content are identical copies in the source, not library duplicates, and Copy or Move (which leave the browsed photo out) offer the first of them that isn't browsed itself. Ported from #1433 (Clearfall); status unchanged (✅) | | 2026-10-27 | patch | MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Select Only Active Photo and Paste Settings from Previous were not in the Edit menu's layout and ended up after Settings…, near the end of the menu; they now sit with the other Select and Paste rows. On macOS the Edit menu no longer shows two separators in a row where Settings… moved to the app menu; status unchanged (✅) | | 2026-10-27 | patch | MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say that Close Window and the red close button of the main window quit the app, after the check Quit makes; kept on purpose; a user page says so; status unchanged (✅) | From 7f56f6a9ee34cbbb9a6fa02477f30ac94bafff82 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 6 Nov 2026 12:05:10 -0500 Subject: [PATCH 09/11] LR-IMP-DUPES: the sizes of browsed files are looked at several at once, and stop at the cancel A browsed file's size on disk was asked one file at a time, by the scan (before its progress total is set) and by every import batch: a round trip each on a network share. They go through stat_all like the probes kept from a scan, and a file not looked at before the cancel is not promoted (import) or offered as the record's own (scan). --- crates/engine/src/import/files.rs | 64 +++++++++++++++++++++++++++++++ crates/engine/src/import/job.rs | 26 +++++++++---- crates/engine/src/import/scan.rs | 33 ++++++++-------- crates/engine/src/tests/import.rs | 39 +++++++++++++++++++ 4 files changed, 140 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index d6a9c6eea9..c46d43219b 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -458,6 +458,44 @@ pub(super) fn reusable_probes( held.into_iter().map(|h| h.filter(|info| seen.next().is_some_and(|s| s != Seen::Unchecked && ok(s, info)))).collect() } +/// What looking at the file of a browsed (Local) record found ([`browsed_files_changed`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BrowsedFile { + /// As it was browsed, or not to be told: a record without a size, and a file that can't be read (one that is + /// gone is the record's own business) count as unchanged. + Unchanged, + /// Its size on disk is not the recorded one: another application replaced it since it was browsed (the check the + /// probes kept from a scan go by). + Changed, + /// Not looked at: `cancel` was set first. + Unchecked, +} + +/// Look at the file of each of `files` (path, the size its browsed record has), several at once ([`stat_all`]: one +/// at a time, each is a round trip to a network share, and thousands of browsed photos waited minutes for them). +/// The answers come in the order of `files`; a record with no size is not asked about. +pub(super) fn browsed_files_changed(files: &[(&str, u64)], cancel: &std::sync::atomic::AtomicBool) -> Vec { + // (the web's files are not std::fs files) + if cfg!(target_arch = "wasm32") { + return vec![BrowsedFile::Unchanged; files.len()]; + } + let asked: Vec<&str> = files.iter().filter(|(_, recorded)| *recorded > 0).map(|(path, _)| *path).collect(); + let mut seen = stat_all(&asked, cancel, stat_file).into_iter(); + files + .iter() + .map(|(_, recorded)| { + if *recorded == 0 { + return BrowsedFile::Unchanged; + } + match seen.next() { + Some(Seen::At { is_file: true, len }) if len != *recorded => BrowsedFile::Changed, + Some(Seen::Unchecked) | None => BrowsedFile::Unchecked, + Some(_) => BrowsedFile::Unchanged, + } + }) + .collect() +} + /// Copy `src` into `dir` as `name` (default: its own name), made unique with -1, -2…; returns the /// new path. The copy is verified ([`crate::import_move::copy_new`]: a new file, synced and /// checked against `probe_hash`, the content hash the probe computed — or compared byte for byte @@ -696,6 +734,32 @@ mod prepared_tests { assert!(seen.iter().all(|s| matches!(s, Seen::Gone | Seen::Unchecked))); } + /// The files of browsed records are looked at together, and only a file of another size than its record has is changed: + /// a record with no size, a file that is gone and a folder in its place count as unchanged, and ✕ leaves them all unchecked. + #[test] + fn browsed_files_are_told_changed_by_their_size() { + let dir = temp_dir("browsed-sizes"); + let name = |n: &str| dir.join(n).to_string_lossy().into_owned(); + std::fs::write(dir.join("same.jpg"), [0u8; 10]).unwrap(); + std::fs::write(dir.join("bigger.jpg"), [0u8; 20]).unwrap(); + std::fs::write(dir.join("unsized.jpg"), [0u8; 5]).unwrap(); + std::fs::create_dir(dir.join("folder.jpg")).unwrap(); + let names = ["same.jpg", "bigger.jpg", "unsized.jpg", "gone.jpg", "folder.jpg"].map(name); + let files: Vec<(&str, u64)> = names.iter().map(String::as_str).zip([10, 10, 0, 10, 10]).collect(); + let cancel = std::sync::atomic::AtomicBool::new(false); + let found = browsed_files_changed(&files, &cancel); + use BrowsedFile::{Changed, Unchanged, Unchecked}; + assert_eq!(found, [Unchanged, Changed, Unchanged, Unchanged, Unchanged]); + cancel.store(true, std::sync::atomic::Ordering::Relaxed); + let found = browsed_files_changed(&files, &cancel); + assert_eq!( + found, + [Unchecked, Unchecked, Unchanged, Unchecked, Unchecked], + "a record with no size isn't asked about, so ✕ doesn't matter to it" + ); + let _ = std::fs::remove_dir_all(dir); + } + /// A probe a scan left is used again for a file that is as it was, and only for it: a file that /// changed size, one that is gone and one with no probe are read. #[test] diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index c6d8b91009..fc1c7ff974 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -1,5 +1,5 @@ use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock}; -use super::files::{Seen, expand, probe_all, reusable_probes, sidecars_of}; +use super::files::{BrowsedFile, Seen, browsed_files_changed, expand, probe_all, reusable_probes, sidecars_of}; use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted}; use super::{HashMap, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; @@ -40,7 +40,7 @@ pub struct ImportJob { /// path → (photo, a Local browse record?) pub(super) by_path: HashMap)>, /// path → the size the record of a browsed (Local) file has: a file of another size has been replaced since - /// it was browsed ([`super::scan::local_file_changed`]) + /// it was browsed ([`super::files::browsed_files_changed`]) local_sizes: HashMap, /// content hash → the photo that has it (`None`: a file earlier in this import) pub(super) by_hash: HashMap>, @@ -271,13 +271,25 @@ impl ImportJob { let mut todo = Vec::new(); // browsed files replaced since: probed again with `todo`, their records brought up to date as they join the library let mut changed: HashMap = HashMap::new(); - for f in files { + // the sizes of the browsed files this import would promote, looked at together before they are decided one by one + // (a file promoted earlier, here or in a previous batch, isn't asked about again) + let is_browsed = |f: &String| !opts.local && matches!(self.by_path.get(f.as_str()), Some((_, true, _))); + let browsed: Vec<(&str, u64)> = + files.iter().filter(|f| is_browsed(f)).map(|f| (f.as_str(), self.local_sizes.get(f.as_str()).copied().unwrap_or(0))).collect(); + let mut looked_at = browsed_files_changed(&browsed, cancel).into_iter(); + let verdicts: Vec> = files.iter().map(|f| is_browsed(f).then(|| looked_at.next()).flatten()).collect(); + for (f, verdict) in files.into_iter().zip(verdicts) { match self.by_path.get(f.as_str()).cloned() { Some((id, true, hash)) if !opts.local => { - if super::scan::local_file_changed(&f, self.local_sizes.get(f.as_str()).copied().unwrap_or(0)) { - changed.insert(f.clone(), id); - todo.push(f); - continue; + match verdict { + // ✕ before its size was looked at: nothing is decided about it, so it isn't promoted + Some(BrowsedFile::Unchecked) => continue, + Some(BrowsedFile::Changed) => { + changed.insert(f.clone(), id); + todo.push(f); + continue; + } + Some(BrowsedFile::Unchanged) | None => {} } // a library photo with the same content comes first, and a file promoted earlier // (here or in a previous batch) counts as the library's from then on diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 34a402a1ac..2adda54a69 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -1,4 +1,4 @@ -use super::files::{Seen, expand, expand_report, is_supported, probe_all, reusable_probes}; +use super::files::{BrowsedFile, Seen, browsed_files_changed, expand, expand_report, is_supported, probe_all, reusable_probes}; use super::types::ImportCandidate; use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; @@ -48,13 +48,6 @@ pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[Stri by_path } -/// Whether the file of a browsed (Local) record is no longer the one that was browsed: its size on disk is not the -/// recorded one, the check the probes kept from a scan go by. A record without a size and a file that can't be read -/// count as unchanged (a file that is gone is the record's own business). -pub(super) fn local_file_changed(path: &str, recorded: u64) -> bool { - !cfg!(target_arch = "wasm32") && recorded > 0 && std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() != recorded) -} - /// Which photo of the library has each of the contents `hashes` (the later one where several /// have it; a copy that was only browsed in Local isn't in the library). One pass over the library, and an entry only for a content that was asked about. pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes: impl Iterator) -> HashMap { @@ -331,15 +324,25 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc let mut by_path = library_files(&input.library, &files); // a browsed file that was replaced since is not the one its record describes: it is read again like a new file // (the record's stored content, kept from the browse, would give the wrong answer against the library), and - // its candidate still names the record and says it was only browsed, unless the library has that content + // its candidate still names the record and says it was only browsed, unless the library has that content. + // Their sizes are looked at together; ✕ while that goes on leaves the files not reached to be read (and so + // reported as not probed) like the ones after them, never vouched for as the record's own. let mut replaced: HashMap = HashMap::new(); - by_path.retain(|path, (id, c, _)| { - let changed = c.local && local_file_changed(&path.to_string_lossy(), c.file_size); - if changed { - replaced.insert(path.clone(), *id); + let browsed: Vec<(&str, u64)> = + files.iter().filter_map(|f| by_path.get(Path::new(f)).filter(|(_, c, _)| c.local).map(|(_, c, _)| (f.as_str(), c.file_size))).collect(); + for ((f, _), checked) in browsed.iter().zip(browsed_files_changed(&browsed, &progress.cancel)) { + match checked { + BrowsedFile::Unchanged => {} + BrowsedFile::Changed => { + if let Some((id, ..)) = by_path.remove(Path::new(f)) { + replaced.insert(PathBuf::from(f), id); + } + } + BrowsedFile::Unchecked => { + by_path.remove(Path::new(f)); + } } - !changed - }); + } let todo: Vec = files.iter().filter(|f| !by_path.contains_key(Path::new(f))).cloned().collect(); progress.total.store(todo.len(), Relaxed); // probes from a preceding `scan` are reused when the file is unchanged (same size); a file that diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index a4840fbb11..f6d9e3e5f8 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -189,6 +189,45 @@ fn a_browsed_file_replaced_by_a_copy_of_a_library_photo_is_a_duplicate() { let _ = std::fs::remove_dir_all(src); } +/// ✕ while the sizes of browsed files are checked: a file that wasn't checked is not promoted (it stays a browsed record), +/// where the check used to run for every file whatever the ✕ said. +#[test] +fn a_cancelled_import_does_not_promote_a_browsed_file_it_did_not_check() { + use crate::import::{ImportJob, ImportOptions, commit_prepared}; + let src = temp_dir("browsed-cancel-import"); + let a = src.join("a.png"); + write_png(&a, 75); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + let mut job = ImportJob::new(&mut s, ImportOptions::default()).unwrap(); + let cancel = std::sync::atomic::AtomicBool::new(true); + let prepared = job.prepare(&[a.to_string_lossy().to_string()], &cancel); + let report = commit_prepared(&mut s, &job.opts, job.now(), prepared).unwrap(); + assert!(report.imported.is_empty() && report.duplicates.is_empty(), "nothing was decided about the file: {report:?}"); + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().local, "the record is still only browsed"); + let _ = std::fs::remove_dir_all(src); +} + +/// ✕ while a scan checks the sizes of browsed files: a file that wasn't checked is not offered as the record's own (it is +/// one of the files the scan didn't reach, like the ones after it). +#[test] +fn a_cancelled_scan_does_not_vouch_for_a_browsed_file_it_did_not_check() { + use crate::import::{ScanInput, ScanProgress, scan_with}; + let src = temp_dir("browsed-cancel-scan"); + let a = src.join("a.png"); + write_png(&a, 75); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + let (input, paths) = ScanInput::new(&mut s, &[a.to_string_lossy().to_string()]); + let progress = ScanProgress::default(); + progress.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + let out = scan_with(input, &paths, &progress); + assert_eq!(out.candidates.len(), 1); + assert!(!out.candidates[0].local && out.candidates[0].error.is_some(), "not vouched for as the browsed record's file: {:?}", out.candidates[0]); + let _ = std::fs::remove_dir_all(src); +} + /// A file of its own with the new content of a replaced browsed file stands in for it when copying leaves it out. #[test] fn a_twin_of_a_replaced_browsed_file_stands_in_for_it_when_copying() { From e2d5c32550567920a9b4b503710a8a4b83d7e428 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 6 Nov 2026 12:11:56 -0500 Subject: [PATCH 10/11] LR-IMP-DUPES: the comment on the browsed files' size check says what it asks about twice --- crates/engine/src/import/job.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index fc1c7ff974..dee5abcaa6 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -272,7 +272,7 @@ impl ImportJob { // browsed files replaced since: probed again with `todo`, their records brought up to date as they join the library let mut changed: HashMap = HashMap::new(); // the sizes of the browsed files this import would promote, looked at together before they are decided one by one - // (a file promoted earlier, here or in a previous batch, isn't asked about again) + // (a file promoted in an earlier batch isn't asked about again; one path twice in a batch is, and its second answer is unused) let is_browsed = |f: &String| !opts.local && matches!(self.by_path.get(f.as_str()), Some((_, true, _))); let browsed: Vec<(&str, u64)> = files.iter().filter(|f| is_browsed(f)).map(|f| (f.as_str(), self.local_sizes.get(f.as_str()).copied().unwrap_or(0))).collect(); From 27eda067f66d49dcd50e15f9c59b0c37be3c10a9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:49:28 +0700 Subject: [PATCH 11/11] import review: refuse OK while a Lightroom import runs; set_transfer tolerates a short checked list (CodeRabbit on #2971) --- crates/ui-egui/src/dialogs/import.rs | 6 +++++- crates/ui-egui/src/dialogs/import/task.rs | 4 ++++ crates/ui-egui/src/tests/drop_import.rs | 17 +++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index ea4b27cd1a..86dc4e01eb 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -183,7 +183,11 @@ impl ImportDialog { self.move_files = copy && move_files; for i in (0..self.candidates.len()).filter(|_| switched) { if self.candidates[i].browsed_twin.is_some() && !self.candidates[i].local { - self.checked[i] = self.is_copy_twin(i); + // (a dialog read back may hold fewer check marks than candidates) + let twin = self.is_copy_twin(i); + if let Some(checked) = self.checked.get_mut(i) { + *checked = twin; + } } } } diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index 18179685f3..c0fcabdc26 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -204,6 +204,10 @@ impl ImportRun { /// import runs: replacing `app.import` would stop its worker. pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result { busy_synchronizing(app)?; + // a Lightroom catalog import owns the catalog until it ends (its photos may share a file's content), as for a drop + if app.lightroom.is_some() { + return Err(crate::i18n::tr("Finish Lightroom catalog import before adding photos").to_string()); + } if !d.in_library(app) { return Err("another library was opened since the photos were scanned: nothing was imported".into()); } diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index 7dffeb491c..1a8e83f7fd 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -657,6 +657,23 @@ fn a_queued_drop_waits_for_a_running_lightroom_import_instead_of_being_refused() ); } +/// The review's OK is refused while a Lightroom catalog import owns the catalog, as a drop is: nothing is imported +/// beside it (CodeRabbit on #2971). +#[test] +fn an_import_review_is_not_confirmed_while_a_lightroom_import_runs() { + let dir = Scratch::new("review-lightroom"); + let mut h = app_with_library(&dir); + h.app.ui.settings.import_dropped_directly = false; + drop_files(&mut h, &[dir.path("trip/a.png")], false); + assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens"); + let task = crate::lightroom_import::stall_import(&mut h.app); + let reply = h.request("ui.dialog.confirm", json!({}), T); + assert_ne!(reply["ok"], true, "{reply}"); + assert!(h.app.import.is_none(), "no import started"); + assert_eq!(photos(&h), 0); + drop(task); +} + /// Cancelling Open Another…'s asynchronous picker keeps the launch list up; the queued photo is /// then held for the library chosen rather than dropped behind the cancelling picker. #[test]