From 944f4ded5b1a76c82823fa304d6d923cb1457c42 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Tue, 13 Oct 2026 00:21:12 -0400 Subject: [PATCH 01/12] LR-IMP-DUPLICATES: say what a duplicate matches and let content duplicates be imported anyway The import review showed an unexplained red "Duplicate" badge for files whose content is already known, and they could not be imported. - Each duplicate now names what it matches: the library file path, or "same file as earlier in this import" (scan keeps the first batch path per content hash). - The summary splits into already in the library (same path), copies of library photos and repeated in this import. - A content duplicate can be ticked by hand to import it anyway (explicit per-file importAnyway through prepare/commit). Path duplicates stay unselectable and the default stays unchecked. - Photos sharing a content hash are kept apart with the existing hash:dup suffix; convert's content check compares base hashes. - The completion message counts the ones imported anyway. - Engine and UI tests, locale catalogs and the parity row updated. --- crates/engine/src/cmd/convert.rs | 4 +- crates/engine/src/cmd/library/import.rs | 1 + crates/engine/src/cmd/library/specs.rs | 2 +- crates/engine/src/import.rs | 4 +- crates/engine/src/import/commit.rs | 21 +++- crates/engine/src/import/job.rs | 35 +++++-- crates/engine/src/import/scan.rs | 31 ++++-- crates/engine/src/import/types.rs | 41 ++++++++ crates/engine/src/sync.rs | 2 +- crates/engine/src/tests/import.rs | 101 ++++++++++++++++++++ crates/ui-egui/locales/cs-formats.json | 7 +- crates/ui-egui/locales/de-formats.json | 5 + crates/ui-egui/locales/es-formats.json | 5 + crates/ui-egui/locales/fr-formats.json | 5 + crates/ui-egui/locales/it-formats.json | 7 +- crates/ui-egui/locales/ja-formats.json | 5 + crates/ui-egui/locales/ka-formats.json | 7 +- crates/ui-egui/locales/pl-formats.json | 7 +- crates/ui-egui/locales/pt-br-formats.json | 5 + crates/ui-egui/locales/ru-formats.json | 5 + crates/ui-egui/locales/uk-formats.json | 5 + crates/ui-egui/locales/zh-hans-formats.json | 5 + crates/ui-egui/locales/zh-hant-formats.json | 5 + crates/ui-egui/src/dialogs/import.rs | 74 ++++++++++++-- crates/ui-egui/src/dialogs/import/body.rs | 29 ++++-- crates/ui-egui/src/dialogs/import/task.rs | 10 ++ docs/parity-checklist.md | 2 +- 27 files changed, 387 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index cf0991f4e3d..4345abfd0c8 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -207,7 +207,9 @@ fn edit_copy(s: &mut Session, p: &Value, id: lightcraft_catalog::PhotoId, opts: /// again (see [`lightcraft_catalog::Photo::preview_checked`]). pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: crate::media::ProbeInfo) -> Option { let preview_checked = ph.preview_stamp(&info.preview_only); - let same = info.content_hash == ph.content_hash + // (a Duplicate's hash is its original's plus a suffix: the same content) + let base = |h: &Option| h.as_deref().map(crate::sync::base_hash).map(str::to_string); + let same = base(&info.content_hash) == base(&ph.content_hash) && info.file_size == ph.file_size && (info.width, info.height) == (ph.width, ph.height) && info.preview_only == ph.preview_only diff --git a/crates/engine/src/cmd/library/import.rs b/crates/engine/src/cmd/library/import.rs index 5e496811ad1..cb8fe29a6de 100644 --- a/crates/engine/src/cmd/library/import.rs +++ b/crates/engine/src/cmd/library/import.rs @@ -96,6 +96,7 @@ pub fn import_params(s: &Session, p: &Value) -> Result { metadata_preset, convert_dng: bool_or(p, "dng", false), backup, + import_anyway: strs(p, "importAnyway").into_iter().collect(), local: bool_or(p, "local", false), // (only the Lightroom import makes records of duplicates) read_duplicates: false, diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index b366069fe2e..7b9f09b2991 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1525,7 +1525,7 @@ pub fn specs() -> Vec { "Import Photos", ["File"], Some("Cmd+Shift+I"), - "{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), backup?: folder (copy or move: each file the import copies or moves is also copied here, under the same folders and name as in the destination — a mirror of it — and verified like the main copy; a bad backup copy is removed and reported, a different file already at its place is left alone and reported; must be outside the destination and not contain it; a move keeps the original of a photo with no backup copy), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has — a duplicate, one restored from Recently Deleted, one joined from a browsed folder — is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, skipped: {unreadable, unsupported} (what the folder walk left out, as library.importPreview counts it; a file named in paths is always tried, so it is never counted here), warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), backups?: [{path, to}] (backup: the copy in the destination and its backup), backupFailed?: [{path, reason}] (backup: imported photos with no backup copy, and why), album?}", + "{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), backup?: folder (copy or move: each file the import copies or moves is also copied here, under the same folders and name as in the destination — a mirror of it — and verified like the main copy; a bad backup copy is removed and reported, a different file already at its place is left alone and reported; must be outside the destination and not contain it; a move keeps the original of a photo with no backup copy), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has — a duplicate, one restored from Recently Deleted, one joined from a browsed folder — is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], importAnyway?: [paths] (files whose content another photo already has, imported as new photos anyway; a file already in the library from the same path never is; they count in `importedAnyway`), onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, importedAnyway?, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, skipped: {unreadable, unsupported} (what the folder walk left out, as library.importPreview counts it; a file named in paths is always tried, so it is never counted here), warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), backups?: [{path, to}] (backup: the copy in the destination and its backup), backupFailed?: [{path, reason}] (backup: imported photos with no backup copy, and why), album?}", always, |s, p| { let req = import_params(s, p)?; diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index dbdc6d25745..edddde3ceca 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -67,8 +67,8 @@ pub use scan::{ #[cfg(test)] use scan::{library_files, library_hashes}; pub use types::{ - BackupCopy, Duplicate, FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, ImportUprightMode, ImportWarning, ImportWarningCode, - Kept, Moved, OnDeleted, Organize, Skipped, + BackupCopy, Duplicate, DuplicateCounts, FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, ImportUprightMode, ImportWarning, + ImportWarningCode, Kept, Moved, OnDeleted, Organize, Skipped, }; mod listed_folders; diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 450b77f5db5..f22e90c49b3 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -1,6 +1,6 @@ use super::defaults::apply_import_defaults; use super::files::copy_into; -use super::job::{Prepared, PreparedItem, ReadyFile}; +use super::job::{Prepared, PreparedItem, ReadyFile, normalize_import_path}; use super::types::{BackupCopy, Duplicate, FileFacts, ImportOptions, ImportReport, Kept, Moved, OnDeleted}; use super::{HashMap, Op, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; @@ -261,6 +261,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let now = now.to_string(); let mut report = ImportReport { scanned: prepared.scanned, skipped: prepared.skipped, ..Default::default() }; let mut default_denoiser = None; + let anyway = prepared.anyway; let mut ops = Vec::new(); // Move: placed at the destination, sources untouched until the records are committed // (with its backup: where it was made, or why it wasn't, so the source stays) @@ -341,20 +342,34 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare placed.extend(pl.map(|p| (p, backed_up))); let id = s.catalog.alloc_photo_id(); if let Some(h) = &info.content_hash { - new_hash.insert(h.clone(), id); + new_hash.entry(h.clone()).or_insert(id); } for old in info.content_hash.as_ref().and_then(|h| trash_hash.get(h)).into_iter().chain(trash_path.get(&stored)) { if purged.insert(*old) { purge.push(*old); } } + // ticked by hand although another photo has this content: a Duplicate's hash + // (`:dup`), so the two photos can be told apart and neither is mistaken for the other + let mut hash = info.content_hash.clone(); + if anyway.contains(&normalize_import_path(&path)) + && let Some(h) = &mut hash + && (new_hash.get(h.as_str()).is_some_and(|first| *first != id) + || s.catalog + .photos() + .any(|p| !purged.contains(&p.id) && p.content_hash.as_deref().map(crate::sync::base_hash) == Some(h.as_str()))) + { + *h = format!("{h}:dup{}", id.0); + report.imported_anyway += 1; + } + let sidecar = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default()); // a copy is catalogued under its new name let name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone()); let mut p = Photo::new(id, Source::File { path: stored }, &name, &info.format, info.width, info.height, &now); p.kind = info.kind; p.file_size = info.file_size; p.as_shot_wb = info.as_shot_wb; - p.content_hash = info.content_hash; + p.content_hash = hash; p.embedded_lens = info.embedded_lens.map(Box::new); p.set_preview_only(info.preview_only.clone()); if let Some(sc) = diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 96781be7a4a..0b7f4e91812 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -1,6 +1,7 @@ use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock}; use super::files::{BrowsedFile, Seen, browsed_files_changed, expand_report_knowing, probe_all, reusable_probes, sidecars_of}; use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted}; +use super::scan::index_hash; use super::{HashMap, ListedFolders, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; /// Import files/folders. See the module docs. @@ -46,6 +47,9 @@ pub struct ImportJob { local_sizes: HashMap, /// content hash → the photo that has it (`None`: a file earlier in this import) pub(super) by_hash: HashMap>, + /// Files to import although their content is known ([`ImportOptions::import_anyway`]), by + /// [`normalize_import_path`]. + anyway: std::collections::HashSet, pub(super) probe: Option, file_bytes: Option, /// Probes from a preceding scan (not read again). @@ -71,6 +75,9 @@ pub struct Prepared { pub scanned: usize, /// What [`ImportJob::prepare`]'s folder walk left out. pub skipped: super::types::Skipped, + /// Files imported although their content is in the library ([`ImportOptions::import_anyway`]), + /// by [`normalize_import_path`]. + pub(super) anyway: std::collections::HashSet, pub(super) items: Vec, } @@ -135,7 +142,7 @@ impl Prepared { paths.insert(normalize_import_path(path), photo.id); } if let Some(hash) = &photo.content_hash { - hashes.insert(hash.clone(), photo.id); + index_hash(&mut hashes, hash, photo.id); } } let mut items = Vec::with_capacity(self.items.len()); @@ -146,7 +153,8 @@ impl Prepared { }; let ReadyFile { path, stored, info, sidecar, placed, backup } = *ready; let existing_path = paths.get(&normalize_import_path(&stored)).copied().or_else(|| paths.get(&normalize_import_path(&path)).copied()); - let existing_hash = info.content_hash.as_ref().and_then(|hash| hashes.get(hash).copied()); + let anyway = self.anyway.contains(&normalize_import_path(&path)); + let existing_hash = info.content_hash.as_ref().filter(|_| !anyway).and_then(|hash| hashes.get(hash).copied()); if let Some(existing) = existing_path.or(existing_hash) { if let Some(placed) = &placed { crate::import_move::rollback(placed); @@ -200,7 +208,7 @@ pub fn backup_refusal(s: &Session, opts: &ImportOptions) -> Option { backup_folder_error(mode, transfer, root.as_deref(), Path::new(backup)) } -fn normalize_import_path(path: &str) -> String { +pub(super) fn normalize_import_path(path: &str) -> String { let path = path.replace('\\', "/"); if cfg!(windows) { path.to_lowercase() } else { path } } @@ -208,10 +216,11 @@ fn normalize_import_path(path: &str) -> String { impl ImportJob { /// Snapshot what an import with `opts` needs from the session (no file-system calls). Takes /// the probes a preceding scan left ([`Session::import_probes`]). - pub fn new(s: &mut Session, opts: ImportOptions) -> crate::Result { + pub fn new(s: &mut Session, mut opts: ImportOptions) -> crate::Result { // a recipe is checked before any file is read or placed, not when the photos are committed crate::cmd::check_recipe(&opts.recipe).map_err(|e| crate::cmd::bad("library.import", e))?; let mode = opts.mode; + let anyway = std::mem::take(&mut opts.import_anyway).iter().map(|p| normalize_import_path(p)).collect(); // Only a library on disk has an `Originals/` folder. The browser build keeps the bytes of // every added file in its own storage already, so "copy" there means "add". let transfer = matches!(mode, ImportMode::Copy | ImportMode::Move); @@ -246,6 +255,7 @@ impl ImportJob { by_path: HashMap::new(), local_sizes: HashMap::new(), by_hash: HashMap::new(), + anyway, probe: s.media.file_probe.clone(), file_bytes: s.media.file_bytes.clone(), cache: std::mem::take(&mut s.import_probes), @@ -334,7 +344,7 @@ impl ImportJob { if !p.local && let Some(h) = &p.content_hash { - self.by_hash.insert(h.clone(), Some(p.id)); + index_hash(&mut self.by_hash, h, Some(p.id)); } } Some(library) @@ -443,7 +453,11 @@ impl ImportJob { let known: std::collections::HashSet<&str> = todo .iter() .zip(&probed) - .filter(|(_, p)| skipped && p.as_ref().is_ok_and(|i| i.content_hash.as_ref().is_some_and(|h| self.by_hash.contains_key(h)))) + .filter(|(f, p)| { + skipped + && !self.anyway.contains(&normalize_import_path(f)) + && p.as_ref().is_ok_and(|i| i.content_hash.as_ref().is_some_and(|h| self.by_hash.contains_key(h))) + }) .map(|(f, _)| f.as_str()) .collect(); let mut found = @@ -467,8 +481,13 @@ impl ImportJob { }; // (this file's place in the lookups above: files that failed to probe have none) let found_sidecar = found.next().flatten(); + let anyway = !opts.local && self.anyway.contains(&normalize_import_path(&path)); + if anyway { + out.anyway.insert(normalize_import_path(&path)); + } // a copy of a file whose transfer is still pending: a duplicate only if that one succeeds if !opts.local + && !anyway && let Some(h) = &info.content_hash && plan.pending_hashes.contains(h) { @@ -621,7 +640,7 @@ impl ImportJob { _ => path.clone(), }; if let Some(h) = &info.content_hash { - self.by_hash.insert(h.clone(), None); + self.by_hash.entry(h.clone()).or_insert(None); } self.done.fetch_add(1, Relaxed); // (a file already inside the destination or the library is added where it is: nothing was copied to back up) @@ -652,7 +671,7 @@ impl ImportJob { if let PreparedItem::Ready(r) = &item && let Some(h) = &r.info.content_hash { - self.by_hash.insert(h.clone(), None); + self.by_hash.entry(h.clone()).or_insert(None); } out.items.push(item); } diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 8e322f726e7..227cca35166 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -53,7 +53,7 @@ pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[Stri /// 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 { - let wanted: std::collections::HashSet<&str> = hashes.collect(); + let wanted: std::collections::HashSet<&str> = hashes.map(crate::sync::base_hash).collect(); let mut by_hash = HashMap::new(); if wanted.is_empty() { return by_hash; @@ -61,9 +61,9 @@ pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes: for p in library.photos() { if !p.local && let Some(h) = &p.content_hash - && wanted.contains(h.as_str()) + && wanted.contains(crate::sync::base_hash(h)) { - by_hash.insert(h.clone(), p.id); + index_hash(&mut by_hash, h, p.id); } } by_hash @@ -93,6 +93,17 @@ pub struct ScanOutput { pub listed: ListedFolders, } +/// Remember `hash` (a Duplicate's carries a `:dup` suffix) under its content, the original +/// winning. +pub(super) fn index_hash(map: &mut HashMap, hash: &str, v: V) { + let base = crate::sync::base_hash(hash); + if base.len() == hash.len() { + map.insert(base.to_string(), v); + } else { + map.entry(base.to_string()).or_insert(v); + } +} + impl ScanInput { pub fn new(s: &mut Session, paths: &[String]) -> (Self, Vec) { let skip = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()); @@ -390,8 +401,8 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc .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 seen_hash: HashMap, Option)> = + library_hashes(&input.library, probed_hashes).into_iter().map(|(h, id)| (h, (Some(id.0), None))).collect(); let mut out = Vec::with_capacity(files.len()); let mut kept = HashMap::new(); // (a content's browsed first copy: its path, until the first file of its own with that content stands in for it) @@ -405,14 +416,15 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc && let Some(h) = hash { match seen_hash.get(h) { - Some(existing) => { + Some((existing, earlier)) => { + c.earlier = earlier.clone(); c.duplicate = Some("content".into()); c.existing = *existing; } None => { // (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); + seen_hash.insert(h.clone(), (None, Some(f.clone()))); browsed_first.insert(h.clone(), f.clone()); } } @@ -431,9 +443,10 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc c.preview_only = info.preview_only.clone(); if let Some(h) = &info.content_hash { match seen_hash.get(h) { - Some(existing) => { + Some((existing, earlier)) => { c.duplicate = Some("content".into()); c.existing = *existing; + c.earlier = earlier.clone(); // (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; a browsed file doesn't) if existing.is_none() && !replaced.contains_key(Path::new(&f)) { @@ -441,7 +454,7 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc } } None => { - seen_hash.insert(h.clone(), None); + seen_hash.insert(h.clone(), (None, Some(f.clone()))); } } } diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index b2f017fd802..6dd982ca6a6 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -86,6 +86,9 @@ pub struct ImportOptions { /// one skipped as a duplicate, restored from Recently Deleted, or joined from a browsed /// folder (Local) is never touched, as the preset and keywords never are. pub recipe: Vec<(String, f64)>, + /// Files to import although another photo has the same content (the review's hand-ticked + /// "Duplicate"s): each becomes a new photo. A file whose path is in the library is never one. + pub import_anyway: std::collections::HashSet, } /// How copies are filed in the destination. The date is the capture time, else the time of the @@ -159,6 +162,10 @@ pub struct ImportCandidate { /// and this file is what they bring in instead. #[serde(skip_serializing_if = "Option::is_none")] pub browsed_twin: Option, + /// A `"content"` duplicate of a file earlier in this list rather than of a library photo: that + /// file's path. + #[serde(skip_serializing_if = "Option::is_none")] + pub earlier: Option, /// Not readable. pub error: Option, /// A raw variant that can't be decoded yet (why): it imports as preview only. @@ -207,9 +214,43 @@ pub struct Skipped { pub unsupported: usize, } +fn is_zero(n: &usize) -> bool { + *n == 0 +} + +/// What the duplicates among [`ImportCandidate`]s are, for the review's summary. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct DuplicateCounts { + /// Already in the library from the same path. + pub in_library: usize, + /// The same content as a library photo, from another path. + pub copies: usize, + /// The same content as a file earlier in this import. + pub repeated: usize, +} + +impl DuplicateCounts { + pub fn of<'a>(candidates: impl IntoIterator) -> Self { + let mut n = Self::default(); + for c in candidates { + match c.duplicate.as_deref() { + Some("path") => n.in_library += 1, + Some(_) if c.earlier.is_some() => n.repeated += 1, + Some(_) => n.copies += 1, + None => {} + } + } + n + } +} + #[derive(Clone, Debug, Default, Serialize)] pub struct ImportReport { pub imported: Vec, + /// How many of `imported` have the content of another photo, ticked by hand + /// ([`ImportOptions::import_anyway`]). + #[serde(rename = "importedAnyway", skip_serializing_if = "is_zero")] + pub imported_anyway: usize, pub duplicates: Vec, /// [`OnDeleted::Restore`]: photos brought back from Recently Deleted instead of imported. #[serde(skip_serializing_if = "Vec::is_empty")] diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 04db8219dc3..4fb0b38b944 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -313,7 +313,7 @@ fn same_for_sync(a: &Arc, b: &Arc) -> bool { } /// The content a hash stands for: a Duplicate's own hash is the original's plus `:dup`. -fn base_hash(h: &str) -> &str { +pub(crate) fn base_hash(h: &str) -> &str { h.split(':').next().unwrap_or(h) } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 3b65dbae9a3..9998ff73d8d 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -4800,3 +4800,104 @@ fn a_broken_link_before_dotdot_is_an_error() { assert_eq!(crate::import::browse_spelling(&link.join("..")).unwrap(), dir); let _ = std::fs::remove_dir_all(&dir); } + +/// Issue #1401: a duplicate by content says what it matches, the summary counts the three kinds +/// apart, and one ticked by hand imports as a new photo. +#[test] +fn content_duplicates_name_their_match_and_can_be_imported_anyway() { + let src = temp_dir("dup-anyway"); + write_png(&src.join("a.png"), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap(); + // a copy of the library photo, and two identical new files + std::fs::copy(src.join("a.png"), src.join("lib-copy.png")).unwrap(); + write_png(&src.join("n1.png"), 2); + std::fs::copy(src.join("n1.png"), src.join("n2.png")).unwrap(); + let paths = [src.to_string_lossy().to_string()]; + + let found = crate::import::scan(&mut s, &paths); + let by = |n: &str| found.iter().find(|c| c.name == n).unwrap_or_else(|| panic!("{n} missing")); + assert_eq!(by("a.png").duplicate.as_deref(), Some("path")); + assert_eq!(by("lib-copy.png").duplicate.as_deref(), Some("content")); + assert!(by("lib-copy.png").existing.is_some() && by("lib-copy.png").earlier.is_none()); + assert_eq!(by("n1.png").duplicate, None); + assert_eq!(by("n2.png").duplicate.as_deref(), Some("content")); + assert_eq!(by("n2.png").earlier.as_deref(), Some(by("n1.png").path.as_str()), "names the file earlier in this import"); + assert_eq!(by("n2.png").existing, None); + assert_eq!(crate::import::DuplicateCounts::of(&found), crate::import::DuplicateCounts { in_library: 1, copies: 1, repeated: 1 }); + + // without the flag nothing changes; a path duplicate is never overridden + let all = |s: &mut Session, extra: Value| { + let mut p = json!({"paths": paths}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute("library.import", &p).unwrap() + }; + let key = |n: &str| src.join(n).to_string_lossy().to_string(); + let r = all(&mut s, json!({"importAnyway": [key("a.png")], "onDeleted": "skip"})); + assert_eq!(ids(&r, "imported"), 1, "only n1: {r}"); + assert_eq!(r.get("importedAnyway"), None, "{r}"); + assert_eq!(s.catalog.len(), 2); + s.execute("edit.undo", &json!({})).unwrap(); + + // tick the library copy and the second of the identical pair + let r = all(&mut s, json!({"importAnyway": [key("lib-copy.png"), key("n2.png")]})); + assert_eq!(ids(&r, "imported"), 3, "n1, lib-copy and n2: {r}"); + assert_eq!(r["importedAnyway"], 2, "{r}"); + assert_eq!(ids(&r, "duplicates"), 1, "only a.png (same path) is left: {r}"); + assert_eq!(s.catalog.len(), 4); + let hashes: Vec = s.catalog.photos().filter_map(|p| p.content_hash.clone()).collect(); + assert_eq!(hashes.iter().collect::>().len(), 4, "each photo has its own hash: {hashes:?}"); + assert_eq!(hashes.iter().filter(|h| h.contains(":dup")).count(), 2, "{hashes:?}"); + + // the twins still count as the content they copy; importing the folder again finds all of it + let again = crate::import::scan(&mut s, &paths); + assert!(again.iter().all(|c| c.duplicate.as_deref() == Some("path")), "{again:?}"); + let r = all(&mut s, json!({})); + assert_eq!(ids(&r, "imported"), 0, "{r}"); + + // one undo step takes all three back + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.len(), 1); + let _ = std::fs::remove_dir_all(&src); +} + +/// A ticked duplicate of a file in the same batch, with the other one not ticked, imports once. +#[test] +fn import_anyway_in_a_batch_keeps_the_first_file_as_the_original() { + let src = temp_dir("dup-anyway-batch"); + write_png(&src.join("n1.png"), 2); + std::fs::copy(src.join("n1.png"), src.join("n2.png")).unwrap(); + let mut s = Session::new().with_fs(); + let key = src.join("n2.png").to_string_lossy().to_string(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "importAnyway": [key]})).unwrap(); + assert_eq!(ids(&r, "imported"), 2, "{r}"); + assert_eq!(r["importedAnyway"], 1, "{r}"); + let twin = s.catalog.photos().find(|p| p.file_name == "n2.png").unwrap(); + let orig = s.catalog.photos().find(|p| p.file_name == "n1.png").unwrap(); + assert_eq!(twin.content_hash.as_deref(), Some(format!("{}:dup{}", orig.content_hash.clone().unwrap(), twin.id.0).as_str())); + let _ = std::fs::remove_dir_all(&src); +} + +/// A surviving duplicate still represents the content after its original leaves the catalog. +/// Both the background scan's selective lookup and the import job must find the suffixed hash. +#[test] +fn content_duplicate_is_found_after_its_original_leaves_the_catalog() { + let src = temp_dir("dup-anyway-surviving"); + write_png(&src.join("n1.png"), 2); + std::fs::copy(src.join("n1.png"), src.join("n2.png")).unwrap(); + let mut s = Session::new().with_fs(); + let path = |name: &str| src.join(name).to_string_lossy().to_string(); + let r = s.execute("library.import", &json!({"paths": [path("n1.png"), path("n2.png")], "importAnyway": [path("n2.png")]})).unwrap(); + assert_eq!(ids(&r, "imported"), 2, "{r}"); + let original = s.catalog.photos().find(|p| p.file_name == "n1.png").unwrap().id; + let twin = s.catalog.photos().find(|p| p.file_name == "n2.png").unwrap().id; + s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: original }).unwrap(); + std::fs::copy(src.join("n2.png"), src.join("n3.png")).unwrap(); + let found = crate::import::scan(&mut s, &[path("n3.png")]); + assert_eq!(found.len(), 1); + assert_eq!((found[0].duplicate.as_deref(), found[0].existing), (Some("content"), Some(twin.0)), "{found:?}"); + let r = s.execute("library.import", &json!({"paths": [path("n3.png")]})).unwrap(); + assert_eq!(ids(&r, "imported"), 0, "{r}"); + assert_eq!(ids(&r, "duplicates"), 1, "{r}"); + let _ = std::fs::remove_dir_all(&src); +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index afd4435bb89..8a292c57d77 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -334,5 +334,10 @@ "Add “{keyword}” to {n} photo{}": "Přidat „{keyword}“ k fotografiím: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Pravidlo {n} z {m}: {what}. Přesun pomocí šipek", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Skupina {n} z {m}: shoda {mode}, uvnitř {count}. Přesun pomocí šipek", - ", rating {} of 5": ", hodnocení: {} z 5" + ", rating {} of 5": ", hodnocení: {} z 5", + " · {n} imported although another photo has the same content": " · importováno {n}, přestože jiná fotografie má stejný obsah", + "Same content as {path} in the library": "Stejný obsah jako {path} v knihovně", + "Same file as {path} earlier in this import": "Stejný soubor jako {path} dříve v tomto importu", + "· {n} copies of library photos": "· kopie fotografií z knihovny: {n}", + "· {n} repeated in this import": "· opakování v tomto importu: {n}" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 591920bdf87..7779fa25bdb 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -196,6 +196,11 @@ "{} spot(s) on this photo": "{} Retuschierstelle(n) in diesem Foto", "{} — show their photos": "{} – Fotos dieser Person anzeigen", "· {dups} already in the library": "· {dups} bereits in der Bibliothek", + "· {n} copies of library photos": "· {n} Kopien von Bibliotheksfotos", + "· {n} repeated in this import": "· {n} mehrfach in diesem Import", + "Same content as {path} in the library": "Gleicher Inhalt wie {path} in der Bibliothek", + "Same file as {path} earlier in this import": "Dieselbe Datei wie {path} weiter oben in diesem Import", + " · {n} imported although another photo has the same content": " · {n} importiert, obwohl ein anderes Foto denselben Inhalt hat", "· {n} photo{}": "· {n} Foto{}", "· {trashed} in Recently Deleted": "· {trashed} in „Zuletzt gelöscht“", "… and {more} more": "… und {more} weitere", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 54b8c3c2f61..e8b95b787d2 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -197,6 +197,11 @@ "{} spot(s) on this photo": "{} mancha(s) en esta foto", "{} — show their photos": "{}: mostrar sus fotos", "· {dups} already in the library": "· ya en la biblioteca: {dups}", + "· {n} copies of library photos": "· {n} copias de fotos de la biblioteca", + "· {n} repeated in this import": "· {n} repetidas en esta importación", + "Same content as {path} in the library": "Mismo contenido que {path} en la biblioteca", + "Same file as {path} earlier in this import": "El mismo archivo que {path} antes en esta importación", + " · {n} imported although another photo has the same content": " · {n} importadas aunque otra foto tiene el mismo contenido", "· {n} photo{}": "· {n} foto{}", "· {trashed} in Recently Deleted": "· {trashed} en Eliminadas recientemente", "… and {more} more": "… y {more} más", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 4eb8a1384e2..36a7245bb96 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -197,6 +197,11 @@ "{} spot(s) on this photo": "{} tache(s) sur cette photo", "{} — show their photos": "{} — afficher leurs photos", "· {dups} already in the library": "· déjà dans la bibliothèque : {dups}", + "· {n} copies of library photos": "· {n} copies de photos de la bibliothèque", + "· {n} repeated in this import": "· {n} répétées dans cet import", + "Same content as {path} in the library": "Même contenu que {path} dans la bibliothèque", + "Same file as {path} earlier in this import": "Même fichier que {path} plus haut dans cet import", + " · {n} imported although another photo has the same content": " · {n} importées bien qu'une autre photo ait le même contenu", "· {n} photo{}": "· {n} photo{}", "· {trashed} in Recently Deleted": "· {trashed} dans « Supprimés récemment »", "… and {more} more": "… et {more} de plus", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 96a493f446e..f43320eb788 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -334,5 +334,10 @@ "Add “{keyword}” to {n} photo{}": "Aggiungi “{keyword}” a {n} foto{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regola {n} di {m}: {what}. Sposta con le frecce", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppo {n} di {m}: corrispondenza {mode}, {count} all’interno. Sposta con le frecce", - ", rating {} of 5": ", valutazione: {} su 5" + ", rating {} of 5": ", valutazione: {} su 5", + " · {n} imported although another photo has the same content": " · importate {n} anche se un’altra foto ha lo stesso contenuto", + "Same content as {path} in the library": "Stesso contenuto di {path} nella libreria", + "Same file as {path} earlier in this import": "Stesso file di {path} già presente in questa importazione", + "· {n} copies of library photos": "· copie di foto nella libreria: {n}", + "· {n} repeated in this import": "· ripetizioni in questa importazione: {n}" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 9138a78640c..403a9fee0d1 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -117,6 +117,11 @@ "{} photo{} not readable": "{}枚を読み込めません{:.0}", "{} spot(s) on this photo": "この写真に{}か所のスポット", "· {dups} already in the library": "・{dups}枚は読み込み済み", + "· {n} copies of library photos": "・{n}枚はライブラリの写真のコピー", + "· {n} repeated in this import": "・{n}枚はこの読み込み内で重複", + "Same content as {path} in the library": "ライブラリの {path} と同じ内容", + "Same file as {path} earlier in this import": "この読み込みの前にある {path} と同じファイル", + " · {n} imported although another photo has the same content": "・{n}枚は他の写真と同じ内容ですが読み込みました", "· {n} photo{}": "・{n}枚{:.0}", "· {trashed} in Recently Deleted": "・最近削除した写真内 {trashed} 枚", "… and {more} more": "…ほか{more}件", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 46b74662cc6..0c39e99da1d 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -337,5 +337,10 @@ "Add “{keyword}” to {n} photo{}": "დაამატეთ „{keyword}“ ფოტოებს: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "წესი {n}/{m}: {what}. გადაადგილება ისრებით", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "ჯგუფი {n}/{m}: დამთხვევა {mode}, შიგნით {count}. გადაადგილება ისრებით", - ", rating {} of 5": ", შეფასება: {} 5-დან" + ", rating {} of 5": ", შეფასება: {} 5-დან", + " · {n} imported although another photo has the same content": " · იმპორტირებულია {n}, მიუხედავად იმისა, რომ სხვა ფოტოს იგივე შიგთავსი აქვს", + "Same content as {path} in the library": "იგივე შიგთავსი, რაც ბიბლიოთეკაში არსებულ {path}-ს", + "Same file as {path} earlier in this import": "იგივე ფაილი, რაც ამ იმპორტში ადრე არსებულ {path}-ს", + "· {n} copies of library photos": "· ბიბლიოთეკის ფოტოების ასლები: {n}", + "· {n} repeated in this import": "· გამეორებები ამ იმპორტში: {n}" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index ded03cc37f9..7727a9e8420 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -334,5 +334,10 @@ "Add “{keyword}” to {n} photo{}": "Dodaj „{keyword}” do zdjęć: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Reguła {n} z {m}: {what}. Przenoś strzałkami", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupa {n} z {m}: dopasuj {mode}, w środku {count}. Przenoś strzałkami", - ", rating {} of 5": ", ocena: {} na 5" + ", rating {} of 5": ", ocena: {} na 5", + " · {n} imported although another photo has the same content": " · zaimportowano {n}, mimo że inne zdjęcie ma tę samą zawartość", + "Same content as {path} in the library": "Taka sama zawartość jak {path} w bibliotece", + "Same file as {path} earlier in this import": "Taki sam plik jak wcześniejszy {path} w tym imporcie", + "· {n} copies of library photos": "· kopie zdjęć z biblioteki: {n}", + "· {n} repeated in this import": "· powtórzenia w tym imporcie: {n}" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index d6361782ef1..ee0bed1fc42 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -146,6 +146,11 @@ "{} photo{} not readable": "{} foto(s) não legível(is){:.0}", "{} spot(s) on this photo": "{} ponto(s) nesta foto", "· {dups} already in the library": "· {dups} já na biblioteca", + "· {n} copies of library photos": "· {n} cópias de fotos da biblioteca", + "· {n} repeated in this import": "· {n} repetidas nesta importação", + "Same content as {path} in the library": "Mesmo conteúdo que {path} na biblioteca", + "Same file as {path} earlier in this import": "Mesmo arquivo que {path} antes nesta importação", + " · {n} imported although another photo has the same content": " · {n} importadas embora outra foto tenha o mesmo conteúdo", "· {n} photo{}": "· {n} foto{}", "· {trashed} in Recently Deleted": "· {trashed} em Excluídos recentemente", "… and {more} more": "… e mais {more}", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 37053b60f1d..659b3de4e5a 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -203,6 +203,11 @@ "{} spot(s) on this photo": "Пятен на этом фото: {}", "{} — show their photos": "{} — показать фото этого человека", "· {dups} already in the library": "· уже в библиотеке: {dups}", + "· {n} copies of library photos": "· {n} копий фото из библиотеки", + "· {n} repeated in this import": "· {n} повторов в этом импорте", + "Same content as {path} in the library": "То же содержимое, что у {path} в библиотеке", + "Same file as {path} earlier in this import": "Тот же файл, что и {path} выше в этом импорте", + " · {n} imported although another photo has the same content": " · {n} импортировано, хотя у другого фото то же содержимое", "· {n} photo{}": "· фото: {n}{:.0}", "· {trashed} in Recently Deleted": "· в «Недавно удалённых»: {trashed}", "… and {more} more": "… и ещё {more}", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 02d5708de01..1f26a874f60 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -197,6 +197,11 @@ "{} spot(s) on this photo": "Ділянок на цьому фото: {}", "{} — show their photos": "{} — показати фото цієї особи", "· {dups} already in the library": "· уже в бібліотеці: {dups}", + "· {n} copies of library photos": "· {n} копій фото з бібліотеки", + "· {n} repeated in this import": "· {n} повторів у цьому імпорті", + "Same content as {path} in the library": "Той самий вміст, що й у {path} у бібліотеці", + "Same file as {path} earlier in this import": "Той самий файл, що й {path} вище в цьому імпорті", + " · {n} imported although another photo has the same content": " · {n} імпортовано, хоча інше фото має той самий вміст", "· {n} photo{}": "· фото: {n}{:.0}", "· {trashed} in Recently Deleted": "· у нещодавно видалених: {trashed}", "… and {more} more": "… і ще {more}", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 1c4bee97fb4..0e7bf6dcdee 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -117,6 +117,11 @@ "{} photo{} not readable": "{0} 张照片无法读取{1:.0}", "{} spot(s) on this photo": "此照片上有 {0} 处污点", "· {dups} already in the library": "· {dups} 张已在图库中", + "· {n} copies of library photos": "· {n} 张是图库照片的副本", + "· {n} repeated in this import": "· {n} 张在本次导入中重复", + "Same content as {path} in the library": "与图库中的 {path} 内容相同", + "Same file as {path} earlier in this import": "与本次导入中靠前的 {path} 是同一文件", + " · {n} imported although another photo has the same content": " · 已导入 {n} 张,尽管另一张照片内容相同", "· {n} photo{}": "· {n} 张照片{0:.0}", "· {trashed} in Recently Deleted": "· {trashed} 张在“最近删除”中", "… and {more} more": "…以及另外 {more} 项", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 9222de8f8bf..e287ea14f3b 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -142,6 +142,11 @@ "{} photo{} not readable": "{} 張照片無法讀取{:.0}", "{} spot(s) on this photo": "此照片有 {} 個斑點", "· {dups} already in the library": "· {dups} 張已在照片庫中", + "· {n} copies of library photos": "· {n} 張是圖庫照片的副本", + "· {n} repeated in this import": "· {n} 張在本次匯入中重複", + "Same content as {path} in the library": "與圖庫中的 {path} 內容相同", + "Same file as {path} earlier in this import": "與本次匯入中較前的 {path} 是同一檔案", + " · {n} imported although another photo has the same content": " · 已匯入 {n} 張,儘管另一張照片內容相同", "· {n} photo{}": "· {n} 張照片{:.0}", "· {trashed} in Recently Deleted": "· {trashed} 張在「最近刪除」中", "… and {more} more": "…以及另外 {more} 個", diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index 7e0b3e2bda9..ded9b2c6cb0 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -168,7 +168,7 @@ impl ImportDialog { /// 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.candidates.get(i).is_some_and(|c| c.error.is_none() && (c.duplicate.is_none() || self.is_trashed(i) || (c.duplicate.as_deref() == Some("content") && c.browsed_twin.is_none()))) && !(self.copy && self.candidates.get(i).is_some_and(|c| c.local)) || self.is_copy_twin(i) } @@ -198,10 +198,23 @@ impl ImportDialog { } } } - /// 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. + /// Candidate `i` is checked by Check All and by file type: importable, and not a content + /// duplicate (those are only ever ticked by hand). pub fn checked_by_default(&self, i: usize) -> bool { - self.importable(i) && !(self.is_trashed(i) && self.on_deleted.is_empty()) + self.importable(i) + && !(self.is_trashed(i) && self.on_deleted.is_empty()) + && self.candidates.get(i).is_some_and(|c| c.duplicate.is_none() || self.is_trashed(i)) + } + /// The checked files that import although another photo has their content (`importAnyway`). + pub fn import_anyway_paths(&self) -> Vec { + let anyway = |i: usize, c: &ImportCandidate| c.duplicate.as_deref() == Some("content") && !self.is_trashed(i); + self.candidates + .iter() + .zip(&self.checked) + .enumerate() + .filter(|(i, (c, on))| **on && self.importable(*i) && anyway(*i, c)) + .map(|(_, (c, _))| c.path.clone()) + .collect() } /// The file types among the candidates (`ARW`, `JPG`…, upper case, sorted) and how many of each. pub fn file_types(&self) -> Vec<(String, usize)> { @@ -254,7 +267,9 @@ impl ImportDialog { let Some(on) = self.checked.get(i).map(|c| !c) else { return }; let from = if shift { self.last_clicked.filter(|a| *a < self.checked.len()).unwrap_or(i) } else { i }; for k in from.min(i)..=from.max(i) { + // (a range doesn't sweep in the content duplicates it passes over) if self.importable(k) + && (k == i || !on || self.checked_by_default(k)) && let Some(c) = self.checked.get_mut(k) { *c = on; @@ -332,7 +347,7 @@ mod tests { assert_eq!(grid_height(f32::INFINITY, 300.0, 142.0), DIALOG_SIZE[1] - DEFAULT_BELOW_GRID); } - /// Six candidates, all checked; candidate 3 is a duplicate (unchecked, not importable). + /// Six candidates, all checked; candidate 3 is a duplicate by content (unchecked until ticked by hand). fn dialog() -> ImportDialog { let mut candidates: Vec = (0..6).map(|i| ImportCandidate { path: format!("img{i}.jpg"), ..Default::default() }).collect(); candidates[3].duplicate = Some("content".into()); @@ -533,9 +548,53 @@ mod tests { d.click(1, false); assert_eq!(d.checked, [true, true, true, false, true, true]); d.click(3, false); - assert_eq!(d.checked, [true, true, true, false, true, true], "a duplicate can't be checked"); + assert_eq!(d.checked, [true, true, true, true, true, true], "a duplicate by content can be ticked by hand"); + d.click(3, false); + assert_eq!(d.checked, [true, true, true, false, true, true]); } + /// Issue #1401: a duplicate by content is ticked by hand to import it anyway; one by path never is. + #[test] + fn a_content_duplicate_can_be_ticked_by_hand_but_a_path_duplicate_cannot() { + let mut d = dialog(); + d.candidates[2].duplicate = Some("path".into()); + d.checked[2] = false; + d.click(2, false); + assert!(!d.checked[2] && !d.importable(2), "same path: not importable"); + assert!(d.importable(3) && !d.checked[3], "content duplicate: importable, unchecked by default"); + assert!(d.import_anyway_paths().is_empty()); + d.click(3, false); + assert!(d.checked[3]); + assert_eq!(d.import_anyway_paths(), ["img3.jpg"]); + assert!(d.selected_paths().contains(&"img3.jpg".to_string())); + // Check All and the file-type toggles leave it alone; only the hand ticks it + d.checked[3] = false; + for i in 0..d.candidates.len() { + d.checked[i] = d.checked_by_default(i); + } + assert_eq!(d.checked, [true, true, false, false, true, true]); + d.check_type("JPG", true); + assert!(!d.checked[3]); + // a click range passes over it + d.checked.iter_mut().for_each(|c| *c = false); + d.click(0, false); + d.click(5, true); + assert_eq!(d.checked, [true, true, false, false, true, true]); + // one in Recently Deleted follows the choice for those files instead + let mut d = dialog(); + d.set_trashed(vec![false, false, false, true, false, false]); + assert!(d.checked[3] && d.import_anyway_paths().is_empty(), "restored, not imported anyway"); + } + + #[test] + fn the_summary_counts_the_three_kinds_apart() { + let mut d = dialog(); + d.candidates[1].duplicate = Some("path".into()); + d.candidates[4].duplicate = Some("content".into()); + d.candidates[4].earlier = Some("img0.jpg".into()); + let counts = lightcraft_engine::import::DuplicateCounts::of(&d.candidates); + assert_eq!((counts.in_library, counts.copies, counts.repeated), (1, 1, 1)); + } #[test] fn shift_click_sets_the_range_to_the_clicked_state() { let mut d = dialog(); @@ -571,8 +630,9 @@ mod tests { assert!(d.selected_paths().contains(&"img3.jpg".to_string())); d.click(3, false); assert!(!d.checked[3]); - // a plain duplicate (not in Recently Deleted) still can't be checked + // a path duplicate (not in Recently Deleted) still can't be checked d.set_trashed(vec![false; 6]); + d.candidates[3].duplicate = Some("path".into()); d.click(3, false); assert!(!d.checked[3]); } diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 2f39122cad9..2bf48391d6f 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -199,16 +199,20 @@ fn preset_entries(app: &LightcraftApp, ui: &egui::Ui) -> std::sync::Arc 0 { - ui.label(egui::RichText::new(crate::i18n::tr_format!("· {dups} already in the library", dups = dups)).color(t.text_dim)); + if dups.in_library > 0 { + ui.label(egui::RichText::new(crate::i18n::tr_format!("· {dups} already in the library", dups = dups.in_library)).color(t.text_dim)); } - if in_source > 0 { - ui.label(egui::RichText::new(crate::i18n::tr_format!("· {in_source} identical copies", in_source = in_source)).color(t.text_dim)) - .on_hover_text(crate::i18n::tr("Files with the same content as another file in this import: only the first is imported.")); + if dups.copies > 0 { + ui.label(egui::RichText::new(crate::i18n::tr_format!("· {n} copies of library photos", n = dups.copies)).color(t.text_dim)); + } + if dups.repeated > 0 { + ui.label(egui::RichText::new(crate::i18n::tr_format!("· {n} repeated in this import", n = dups.repeated)).color(t.text_dim)); } if trashed > 0 { ui.label(egui::RichText::new(crate::i18n::tr_format!("· {trashed} in Recently Deleted", trashed = trashed)).color(t.text_dim)); @@ -707,6 +711,19 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial c.file_size as f64 / 1e6, c.captured.as_deref().map(|d| format!("\n{}", d.replace('T', " "))).unwrap_or_default() ); + // A duplicate by content says what it matches. + let matches = match (c.duplicate.as_deref(), &c.earlier, c.existing) { + (Some("content"), Some(earlier), _) => Some(crate::i18n::tr_format!("Same file as {path} earlier in this import", path = earlier)), + (Some("content"), None, Some(id)) => match app.session.catalog.photo(lightcraft_catalog::PhotoId(id)).map(|p| &p.source) { + Some(lightcraft_catalog::Source::File { path }) => Some(crate::i18n::tr_format!("Same content as {path} in the library", path = path)), + _ => None, + }, + _ => None, + }; + let tip = match matches { + Some(m) => format!("{m}\n{tip}"), + None => tip, + }; let on = d.checked.get(i).copied().unwrap_or(false) && ok; // The cell is host-painted; the framework senses it (click, tooltip, its accessible node), no Tab stop as before; // none in speculative layout. diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index b3479262559..f15fa55226f 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -20,6 +20,8 @@ pub struct ImportTask { /// What the review that started this import listed, for its job. listed: Option, pub imported: usize, + /// Of `imported`, the files ticked by hand although another photo has their content. + pub imported_anyway: usize, /// Brought back from Recently Deleted (`onDeleted: restore`). pub restored: usize, pub duplicates: usize, @@ -232,6 +234,10 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result if !d.recipe.is_empty() { params["recipe"] = recipe_items(&d.recipe); } + let anyway = d.import_anyway_paths(); + if !anyway.is_empty() { + params["importAnyway"] = json!(anyway); + } if !d.on_deleted.is_empty() { params["onDeleted"] = json!(d.on_deleted); } @@ -384,6 +390,7 @@ fn commit_batch(app: &mut LightcraftApp, task: &mut ImportTask, prepared: lightc let len = |k: &str| v[k].as_array().map_or(0, Vec::len); task.imported += len("imported"); task.restored += len("restored"); + task.imported_anyway += v["importedAnyway"].as_u64().unwrap_or(0) as usize; task.duplicates += len("duplicates"); task.existing.extend(v["duplicates"].as_array().into_iter().flatten().filter_map(|d| d["existing"].as_u64())); task.failed += len("failed"); @@ -536,6 +543,9 @@ fn import_summary(app: &LightcraftApp, task: &ImportTask) -> String { if task.restored > 0 && (task.imported > 0 || task.cancelled) { msg.push_str(&crate::i18n::tr_format!(" · {} restored from Recently Deleted", task.restored)); } + if task.imported_anyway > 0 { + msg.push_str(&crate::i18n::tr_format!(" · {n} imported although another photo has the same content", n = task.imported_anyway)); + } if task.params["mode"] == "move" { msg.push_str(&crate::i18n::tr_format!(" · {} moved", task.moved)); if task.kept > 0 { diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 455157e4acc..49efad08e22 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -76,7 +76,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`, `backup`), `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`), and `library.import` returns `skipped` too (issue #4319). 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`, `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-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.; the review names the matching library photo or earlier file, and a content duplicate may be checked by hand to import it as a second photo (`importAnyway`). | | 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 | From b55421da433bdbcdcf566ad85d045c45ad353884 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Thu, 15 Oct 2026 12:48:47 -0400 Subject: [PATCH 02/12] LR-IMP-DUPLICATES: replace deleted content copies on fresh import --- crates/engine/src/import/commit.rs | 18 +++++++--- crates/engine/src/tests/import.rs | 58 ++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index f22e90c49b3..587230184ed 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -269,11 +269,12 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare // photos added by this batch, by content (a duplicate of a file earlier in the import names it) let mut new_hash: HashMap = HashMap::new(); // Fresh: trashed photos a new import replaces (by content or by file), each removed once - let (mut trash_hash, mut trash_path): (HashMap, HashMap) = Default::default(); + let mut trash_hash: HashMap> = HashMap::new(); + let mut trash_path: HashMap = HashMap::new(); if opts.on_deleted == OnDeleted::Fresh { for p in s.catalog.photos().filter(|p| p.deleted) { if let Some(h) = &p.content_hash { - trash_hash.insert(h.clone(), p.id); + trash_hash.entry(crate::sync::base_hash(h).to_string()).or_default().push(p.id); } if let Source::File { path } = &p.source { trash_path.insert(path.clone(), p.id); @@ -344,9 +345,16 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare if let Some(h) = &info.content_hash { new_hash.entry(h.clone()).or_insert(id); } - for old in info.content_hash.as_ref().and_then(|h| trash_hash.get(h)).into_iter().chain(trash_path.get(&stored)) { - if purged.insert(*old) { - purge.push(*old); + for old in info + .content_hash + .as_deref() + .and_then(|h| trash_hash.remove(crate::sync::base_hash(h))) + .into_iter() + .flatten() + .chain(trash_path.remove(&stored)) + { + if purged.insert(old) { + purge.push(old); } } // ticked by hand although another photo has this content: a Duplicate's hash diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 9998ff73d8d..5d6a340a9a2 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -4901,3 +4901,61 @@ fn content_duplicate_is_found_after_its_original_leaves_the_catalog() { assert_eq!(ids(&r, "duplicates"), 1, "{r}"); let _ = std::fs::remove_dir_all(&src); } + +/// Fresh replaces every deleted instance of the incoming content, including intentional copies. +/// Other deleted content stays available, and undo recovers each replaced photo with its edits. +#[test] +fn fresh_import_replaces_deleted_content_copies_and_undo_restores_them() { + for remove_original in [false, true] { + let src = temp_dir(if remove_original { "fresh-copies-only" } else { "fresh-original-and-copies" }); + write_png(&src.join("original.png"), 1); + for name in ["copy1.png", "copy2.png", "incoming.png"] { + std::fs::copy(src.join("original.png"), src.join(name)).unwrap(); + } + write_png(&src.join("unrelated.png"), 2); + let path = |name: &str| src.join(name).to_string_lossy().to_string(); + let mut s = Session::new().with_fs(); + let mut matching = Vec::new(); + for name in ["original.png", "copy1.png", "copy2.png"] { + let r = s.execute("library.import", &json!({"paths": [path(name)], "importAnyway": [path(name)]})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.rate", &json!({"ids": [id], "rating": 4})).unwrap(); + matching.push(id); + } + let r = s.execute("library.import", &json!({"paths": [path("unrelated.png")]})).unwrap(); + let unrelated = r["imported"][0].as_u64().unwrap(); + let original = remove_original.then(|| matching.remove(0)); + let mut deleted = matching.clone(); + deleted.push(unrelated); + s.execute("photo.delete", &json!({"ids": deleted})).unwrap(); + if let Some(original) = original { + s.execute("photo.deletePermanently", &json!({"ids": [original]})).unwrap(); + } + // Restore still revives one existing record with its edits rather than replacing it. + let r = s.execute("library.import", &json!({"paths": [path("incoming.png")], "onDeleted": "restore"})).unwrap(); + assert_eq!(ids(&r, "restored"), 1, "{r}"); + let restored = r["restored"][0].as_u64().unwrap(); + assert!(matching.contains(&restored)); + assert_eq!(s.catalog.photo(lightcraft_catalog::PhotoId(restored)).unwrap().rating, 4); + s.execute("edit.undo", &json!({})).unwrap(); + let old_hashes: Vec<_> = matching.iter().map(|id| s.catalog.photo(lightcraft_catalog::PhotoId(*id)).unwrap().content_hash.clone()).collect(); + let r = s.execute("library.import", &json!({"paths": [path("incoming.png")], "onDeleted": "fresh"})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(ids(&r, "restored"), 0, "{r}"); + let new = lightcraft_catalog::PhotoId(r["imported"][0].as_u64().unwrap()); + assert!(matching.iter().all(|id| s.catalog.photo(lightcraft_catalog::PhotoId(*id)).is_none()), "all matching trash replaced"); + let p = s.catalog.photo(new).unwrap(); + assert!(!p.deleted && p.rating == 0, "fresh edits"); + assert_eq!(s.catalog.len(), 2); + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(unrelated)).unwrap().deleted); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.photo(new).is_none()); + for (id, hash) in matching.iter().zip(old_hashes) { + let p = s.catalog.photo(lightcraft_catalog::PhotoId(*id)).unwrap(); + assert!(p.deleted && p.rating == 4); + assert_eq!(p.content_hash, hash); + } + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(unrelated)).unwrap().deleted); + let _ = std::fs::remove_dir_all(&src); + } +} From 58443e175d9f222a79ba432144a9c3549669fc3f Mon Sep 17 00:00:00 2001 From: radialmonster Date: Thu, 22 Oct 2026 09:42:48 -0400 Subject: [PATCH 03/12] Add fi/id/sv/vi translations for the duplicate-match strings Main added these locales after the PR was written; the locale check reported the five new duplicate-match strings missing from each. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM --- crates/ui-egui/locales/fi-formats.json | 7 ++++++- crates/ui-egui/locales/id-formats.json | 7 ++++++- crates/ui-egui/locales/sv-formats.json | 7 ++++++- crates/ui-egui/locales/vi-formats.json | 7 ++++++- 4 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 924fce580fd..470d782bd10 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -331,5 +331,10 @@ "{n} already there": "jo albumissa: {n}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Sääntö {n}/{m}: {what}. Siirrä nuolinäppäimillä", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Ryhmä {n}/{m}: täsmää {mode}, sisällä: {count}. Siirrä nuolinäppäimillä", - ", rating {} of 5": ", luokitus: {} / 5" + ", rating {} of 5": ", luokitus: {} / 5", + "· {n} copies of library photos": "· {n} kopiota kirjaston valokuvista", + "· {n} repeated in this import": "· {n} toistuu tässä tuonnissa", + "Same content as {path} in the library": "Sama sisältö kuin tiedostossa {path} kirjastossa", + "Same file as {path} earlier in this import": "Sama tiedosto kuin {path} aiemmin tässä tuonnissa", + " · {n} imported although another photo has the same content": " · {n} tuotu, vaikka toisella valokuvalla on sama sisältö" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index c492fcbb01e..b975d995faf 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -334,5 +334,10 @@ "{n} already there": "{n} sudah ada", "Rule {n} of {m}: {what}. Move with the arrow keys": "Aturan {n} dari {m}: {what}. Pindahkan dengan tombol panah", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grup {n} dari {m}: cocokkan {mode}, isi: {count}. Pindahkan dengan tombol panah", - ", rating {} of 5": ", rating: {} dari 5" + ", rating {} of 5": ", rating: {} dari 5", + "· {n} copies of library photos": "· {n} salinan foto pustaka", + "· {n} repeated in this import": "· {n} berulang dalam impor ini", + "Same content as {path} in the library": "Konten sama dengan {path} di pustaka", + "Same file as {path} earlier in this import": "File sama dengan {path} sebelumnya dalam impor ini", + " · {n} imported although another photo has the same content": " · {n} diimpor meskipun foto lain memiliki konten yang sama" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index c84bcb2bddb..53beebe03ac 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -343,5 +343,10 @@ "{n} already there": "redan i albumet: {n}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} av {m}: {what}. Flytta med piltangenterna", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupp {n} av {m}: matcha {mode}, antal i gruppen: {count}. Flytta med piltangenterna", - ", rating {} of 5": ", betyg: {} av 5" + ", rating {} of 5": ", betyg: {} av 5", + "· {n} copies of library photos": "· {n} kopior av bibliotekets foton", + "· {n} repeated in this import": "· {n} upprepade i denna import", + "Same content as {path} in the library": "Samma innehåll som {path} i biblioteket", + "Same file as {path} earlier in this import": "Samma fil som {path} tidigare i denna import", + " · {n} imported although another photo has the same content": " · {n} importerade fastän ett annat foto har samma innehåll" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 75606d1563d..0cef8385073 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -331,5 +331,10 @@ "{n} already there": "{n} đã có sẵn", "Rule {n} of {m}: {what}. Move with the arrow keys": "Quy tắc {n}/{m}: {what}. Di chuyển bằng phím mũi tên", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Nhóm {n}/{m}: khớp {mode}, bên trong: {count}. Di chuyển bằng phím mũi tên", - ", rating {} of 5": ", xếp hạng: {} trên 5" + ", rating {} of 5": ", xếp hạng: {} trên 5", + "· {n} copies of library photos": "· {n} bản sao của ảnh trong thư viện", + "· {n} repeated in this import": "· {n} lặp lại trong lần nhập này", + "Same content as {path} in the library": "Cùng nội dung với {path} trong thư viện", + "Same file as {path} earlier in this import": "Cùng tệp với {path} trước đó trong lần nhập này", + " · {n} imported although another photo has the same content": " · {n} đã nhập dù ảnh khác có cùng nội dung" } From 5b4dc101d098f4e889a6125611f0dd16bf5e0398 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Thu, 29 Oct 2026 21:48:45 -0400 Subject: [PATCH 04/12] i18n: translate Listing folders in id/fi/sv/vi; fix duplicate-batch test doc comment Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM --- crates/engine/src/tests/import.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 5d6a340a9a2..d14fab8f5e7 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -4861,7 +4861,7 @@ fn content_duplicates_name_their_match_and_can_be_imported_anyway() { let _ = std::fs::remove_dir_all(&src); } -/// A ticked duplicate of a file in the same batch, with the other one not ticked, imports once. +/// A ticked duplicate of a file in the same batch, with the other one not ticked, imports both files: the first stays the original. #[test] fn import_anyway_in_a_batch_keeps_the_first_file_as_the_original() { let src = temp_dir("dup-anyway-batch"); From 59aa0a2ad9ff2ed0b9efd991a4651e3e2ecdf0fe Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sat, 31 Oct 2026 04:06:22 -0400 Subject: [PATCH 05/12] LR-IMP-DUPLICATES: cover sidecars on forced duplicates after rebase Verify that a duplicate explicitly imported after a cached scan retains its own sidecar rating. Keep the merged import exports and imports formatted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM --- crates/engine/src/import/job.rs | 6 +++--- crates/engine/src/tests/import.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 0b7f4e91812..4d78a33b65a 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -394,7 +394,7 @@ impl ImportJob { if let Some(existing) = self.by_hash.get(h) { return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, file: None }; } - self.by_hash.insert(h.clone(), Some(id)); + index_hash(&mut self.by_hash, h, 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, hash)); @@ -499,14 +499,14 @@ impl ImportJob { // same bytes as a library photo: skipped below, once its capture time is known (and, // when the import makes a record of it, once it is read as a file import reads it) let duplicate_of = - info.content_hash.as_ref().filter(|_| !opts.local).and_then(|h| self.by_hash.get(h).map(|existing| (h.clone(), *existing))); + info.content_hash.as_ref().filter(|_| !opts.local && !anyway).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)); + index_hash(&mut self.by_hash, h, Some(id)); } self.by_path.insert(path, (id, false, info.content_hash.clone())); self.done.fetch_add(1, Relaxed); diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index d14fab8f5e7..fa40290d6e8 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -4861,6 +4861,32 @@ fn content_duplicates_name_their_match_and_can_be_imported_anyway() { let _ = std::fs::remove_dir_all(&src); } +/// A forced content duplicate still reads its own sidecar after a scan cached its probe. +#[test] +fn import_anyway_keeps_the_duplicates_own_sidecar() { + let src = temp_dir("dup-anyway-sidecar"); + write_png(&src.join("original.png"), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.join("original.png").to_string_lossy()]})).unwrap(); + std::fs::copy(src.join("original.png"), src.join("copy.png")).unwrap(); + std::fs::write( + src.join("copy.xmp"), + r#" +"#, + ) + .unwrap(); + let path = src.join("copy.png").to_string_lossy().to_string(); + let found = crate::import::scan(&mut s, std::slice::from_ref(&path)); + assert_eq!(found.len(), 1); + assert_eq!(found[0].duplicate.as_deref(), Some("content")); + let r = s.execute("library.import", &json!({"paths": [path], "importAnyway": [path]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(r["importedAnyway"], 1, "{r}"); + assert_eq!(r["sidecars"], 1, "{r}"); + let copy = s.catalog.photos().find(|p| p.file_name == "copy.png").unwrap(); + assert_eq!(copy.rating, 4); +} + /// A ticked duplicate of a file in the same batch, with the other one not ticked, imports both files: the first stays the original. #[test] fn import_anyway_in_a_batch_keeps_the_first_file_as_the_original() { From e111a1c9119b58c4a6c9d76ab8af245ac9894422 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sat, 7 Nov 2026 06:36:47 -0500 Subject: [PATCH 06/12] LR-IMP-DUPLICATES: test an importAnyway entry outside the import; build the base-hash lookup once An importAnyway path that is not part of the import (same name and content in another folder, or a missing file) imports nothing and does not let the in-import content duplicate through. commit_prepared now builds the library's base-hash lookup once per commit, only when files are ticked to import anyway, instead of scanning the catalog for each such file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9Mvap24RDADn7A3Wnwq --- crates/engine/src/import/commit.rs | 20 ++++++++++++++++--- crates/engine/src/tests/import.rs | 32 ++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 587230184ed..535a7dd997d 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -212,6 +212,21 @@ fn back_up( Ok(copy.to_string_lossy().to_string()) } +/// The library's photos by base content hash (a Duplicate's `:dup` dropped), built once per +/// commit for the files ticked to import anyway (`wanted`) instead of a catalog scan per file. +fn photos_by_base_hash(cat: &lightcraft_catalog::Catalog, wanted: bool) -> HashMap> { + let mut by_base: HashMap> = HashMap::new(); + if !wanted { + return by_base; + } + for p in cat.photos() { + if let Some(h) = &p.content_hash { + by_base.entry(crate::sync::base_hash(h).to_string()).or_default().push(p.id); + } + } + by_base +} + /// A trashed photo's file is not where the library had it (never on the web, where paths are /// storage keys, not files). fn trashed_file_is_gone(cat: &lightcraft_catalog::Catalog, id: PhotoId) -> bool { @@ -281,6 +296,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } } } + let by_base = photos_by_base_hash(&s.catalog, !anyway.is_empty()); let mut purge: Vec = Vec::new(); let mut purged: std::collections::HashSet = Default::default(); for it in prepared.items { @@ -363,9 +379,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare if anyway.contains(&normalize_import_path(&path)) && let Some(h) = &mut hash && (new_hash.get(h.as_str()).is_some_and(|first| *first != id) - || s.catalog - .photos() - .any(|p| !purged.contains(&p.id) && p.content_hash.as_deref().map(crate::sync::base_hash) == Some(h.as_str()))) + || by_base.get(h.as_str()).is_some_and(|ids| ids.iter().any(|p| !purged.contains(p)))) { *h = format!("{h}:dup{}", id.0); report.imported_anyway += 1; diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index fa40290d6e8..b2dd7a4740c 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -4861,6 +4861,38 @@ fn content_duplicates_name_their_match_and_can_be_imported_anyway() { let _ = std::fs::remove_dir_all(&src); } +/// An `importAnyway` entry naming a file that is not part of the import changes nothing: that +/// file is not imported, and a content duplicate in the import (even one with the same name and +/// content) is still skipped. The list overrides only the files it names, by their full path. +#[test] +fn import_anyway_entry_outside_the_import_changes_nothing() { + let src = temp_dir("dup-anyway-outside"); + let other = temp_dir("dup-anyway-outside-other"); + write_png(&src.join("a.png"), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap(); + std::fs::copy(src.join("a.png"), src.join("copy.png")).unwrap(); + // the same name and content, in a folder this import does not include + std::fs::copy(src.join("a.png"), other.join("copy.png")).unwrap(); + let inside = src.join("copy.png").to_string_lossy().to_string(); + let outside = other.join("copy.png").to_string_lossy().to_string(); + let missing = other.join("nowhere.png").to_string_lossy().to_string(); + + let found = crate::import::scan(&mut s, std::slice::from_ref(&inside)); + assert_eq!(found.len(), 1); + assert_eq!(found[0].duplicate.as_deref(), Some("content")); + let r = s.execute("library.import", &json!({"paths": [inside], "importAnyway": [outside, missing]})).unwrap(); + assert_eq!(ids(&r, "imported"), 0, "{r}"); + assert_eq!(ids(&r, "failed"), 0, "{r}"); + assert_eq!(r.get("importedAnyway"), None, "{r}"); + assert_eq!(ids(&r, "duplicates"), 1, "{r}"); + assert_eq!(r["duplicates"][0]["reason"], "content", "{r}"); + assert_eq!(s.catalog.len(), 1, "neither the outside file nor the copy is added"); + assert!(s.catalog.photos().all(|p| p.content_hash.as_deref().is_some_and(|h| !h.contains(":dup")))); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&other); +} + /// A forced content duplicate still reads its own sidecar after a scan cached its probe. #[test] fn import_anyway_keeps_the_duplicates_own_sidecar() { From d34d3fe3a26f3099733f7889bfbfd6cca9dfd9c9 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sun, 29 Nov 2026 13:51:23 -0500 Subject: [PATCH 07/12] 1425: preserve Local import behavior when overriding content duplicates --- crates/engine/src/import/commit.rs | 12 ++++++------ crates/engine/src/import/job.rs | 9 ++++++--- crates/ui-egui/src/dialogs/import.rs | 14 +++++++++----- crates/ui-egui/src/dialogs/import/body.rs | 7 ++++++- 4 files changed, 27 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 535a7dd997d..b88b8d162f1 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -219,7 +219,7 @@ fn photos_by_base_hash(cat: &lightcraft_catalog::Catalog, wanted: bool) -> HashM if !wanted { return by_base; } - for p in cat.photos() { + for p in cat.photos().filter(|p| !p.local || p.deleted) { if let Some(h) = &p.content_hash { by_base.entry(crate::sync::base_hash(h).to_string()).or_default().push(p.id); } @@ -313,10 +313,10 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare // "Import as new": a trashed photo with the same content is replaced, as for a new file 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); + for old in content.as_deref().and_then(|h| trash_hash.remove(crate::sync::base_hash(h))).into_iter().flatten() { + if purged.insert(old) { + purge.push(old); + } } report.imported.push(id.0); } @@ -384,7 +384,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare *h = format!("{h}:dup{}", id.0); report.imported_anyway += 1; } - let sidecar = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default()); + // a copy is catalogued under its new name let name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone()); let mut p = Photo::new(id, Source::File { path: stored }, &name, &info.format, info.width, info.height, &now); diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 4d78a33b65a..f6e3cad1436 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -1,7 +1,7 @@ use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock}; use super::files::{BrowsedFile, Seen, browsed_files_changed, expand_report_knowing, probe_all, reusable_probes, sidecars_of}; -use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted}; use super::scan::index_hash; +use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted}; use super::{HashMap, ListedFolders, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; /// Import files/folders. See the module docs. @@ -498,8 +498,11 @@ impl ImportJob { } // same bytes as a library photo: skipped below, once its capture time is known (and, // when the import makes a record of it, once it is read as a file import reads it) - let duplicate_of = - info.content_hash.as_ref().filter(|_| !opts.local && !anyway).and_then(|h| self.by_hash.get(h).map(|existing| (h.clone(), *existing))); + let duplicate_of = info + .content_hash + .as_ref() + .filter(|_| !opts.local && !anyway) + .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() diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index ded9b2c6cb0..b97bf85657e 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -168,8 +168,12 @@ impl ImportDialog { /// 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) || (c.duplicate.as_deref() == Some("content") && c.browsed_twin.is_none()))) - && !(self.copy && self.candidates.get(i).is_some_and(|c| c.local)) + self.candidates.get(i).is_some_and(|c| { + c.error.is_none() + && (c.duplicate.is_none() + || self.is_trashed(i) + || (c.duplicate.as_deref() == Some("content") && !c.local && c.browsed_twin.is_none())) + }) && !(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 @@ -203,11 +207,11 @@ impl ImportDialog { pub fn checked_by_default(&self, i: usize) -> bool { self.importable(i) && !(self.is_trashed(i) && self.on_deleted.is_empty()) - && self.candidates.get(i).is_some_and(|c| c.duplicate.is_none() || self.is_trashed(i)) + && self.candidates.get(i).is_some_and(|c| c.duplicate.is_none() || self.is_trashed(i) || self.is_copy_twin(i)) } /// The checked files that import although another photo has their content (`importAnyway`). pub fn import_anyway_paths(&self) -> Vec { - let anyway = |i: usize, c: &ImportCandidate| c.duplicate.as_deref() == Some("content") && !self.is_trashed(i); + let anyway = |i: usize, c: &ImportCandidate| c.duplicate.as_deref() == Some("content") && !self.is_trashed(i) && !self.is_copy_twin(i); self.candidates .iter() .zip(&self.checked) @@ -423,7 +427,7 @@ mod tests { 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"); + assert!(d.importable(3) && !d.checked_by_default(3), "the next copy is available only by manual override"); 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"); diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 2bf48391d6f..b9d908411e7 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -201,7 +201,12 @@ fn body_inner(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) let n = d.candidates.len(); let (_, _, trashed) = dup_counts(d); // files of photos in Recently Deleted are not "already in the library": they are counted apart - let dups = lightcraft_engine::import::DuplicateCounts::of(d.candidates.iter().enumerate().filter(|(i, _)| !d.is_trashed(*i)).map(|(_, c)| c)); + let mut dups = lightcraft_engine::import::DuplicateCounts::of( + d.candidates.iter().enumerate().filter(|(i, _)| !d.is_trashed(*i) && !d.is_copy_twin(*i)).map(|(_, c)| c), + ); + if d.copy { + dups.in_library += (0..n).filter(|&i| d.is_browsed(i)).count(); + } let sel = d.selected_paths().len(); ui.horizontal(|ui| { ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} found · {sel} selected", n = n, sel = sel)).color(t.text)); From d1ba8c313b044c5547ad322e4ab1d3ff2071f15e Mon Sep 17 00:00:00 2001 From: radialmonster Date: Wed, 2 Dec 2026 08:24:26 -0500 Subject: [PATCH 08/12] 1425: separate Fresh trash and override hash bookkeeping --- crates/engine/src/import/commit.rs | 107 +++++++++++++++++------------ 1 file changed, 62 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index b88b8d162f1..cdcd9081a54 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use super::defaults::apply_import_defaults; use super::files::copy_into; use super::job::{Prepared, PreparedItem, ReadyFile, normalize_import_path}; @@ -269,6 +271,59 @@ impl Session { } } +/// Trashed photos an import set to Fresh replaces, in the order matched, each removed once. +#[derive(Default)] +struct FreshTrash { + by_hash: HashMap>, + by_path: HashMap, + ids: Vec, + purged: HashSet, +} + +impl FreshTrash { + fn new(cat: &lightcraft_catalog::Catalog, on_deleted: OnDeleted) -> Self { + let mut trash = Self::default(); + if on_deleted == OnDeleted::Fresh { + for p in cat.photos().filter(|p| p.deleted) { + if let Some(h) = &p.content_hash { + trash.by_hash.entry(crate::sync::base_hash(h).to_string()).or_default().push(p.id); + } + if let Source::File { path } = &p.source { + trash.by_path.insert(path.clone(), p.id); + } + } + } + trash + } + + fn match_photo(&mut self, hash: Option<&str>, path: Option<&str>) { + let content = hash.and_then(|h| self.by_hash.remove(crate::sync::base_hash(h))); + let file = path.and_then(|p| self.by_path.remove(p)); + self.ids.extend(content.into_iter().flatten().chain(file).filter(|old| self.purged.insert(*old))); + } +} + +/// A hand-ticked content duplicate gets a distinct hash so it isn't mistaken for the first copy. +fn import_content_hash( + id: PhotoId, + path: &str, + mut hash: Option, + anyway: &HashSet, + new_hash: &HashMap, + by_base: &HashMap>, + purged: &HashSet, +) -> (Option, bool) { + if anyway.contains(&normalize_import_path(path)) + && let Some(h) = &mut hash + && (new_hash.get(h.as_str()).is_some_and(|first| *first != id) + || by_base.get(h.as_str()).is_some_and(|ids| ids.iter().any(|p| !purged.contains(p)))) + { + *h = format!("{h}:dup{}", id.0); + return (hash, true); + } + (hash, false) +} + /// The catalog half of an import: add the photos [`ImportJob::prepare`] readied (one undoable op; /// a Move's sources are removed once it is saved). On a failed commit a Move's placed files are /// taken back. @@ -283,22 +338,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut placed: Vec<(crate::import_move::Placed, Option>)> = Vec::new(); // photos added by this batch, by content (a duplicate of a file earlier in the import names it) let mut new_hash: HashMap = HashMap::new(); - // Fresh: trashed photos a new import replaces (by content or by file), each removed once - let mut trash_hash: HashMap> = HashMap::new(); - let mut trash_path: HashMap = HashMap::new(); - if opts.on_deleted == OnDeleted::Fresh { - for p in s.catalog.photos().filter(|p| p.deleted) { - if let Some(h) = &p.content_hash { - trash_hash.entry(crate::sync::base_hash(h).to_string()).or_default().push(p.id); - } - if let Source::File { path } = &p.source { - trash_path.insert(path.clone(), p.id); - } - } - } + let mut trash = FreshTrash::new(&s.catalog, opts.on_deleted); let by_base = photos_by_base_hash(&s.catalog, !anyway.is_empty()); - let mut purge: Vec = Vec::new(); - let mut purged: std::collections::HashSet = Default::default(); for it in prepared.items { match it { PreparedItem::Promote(id, fresh) => { @@ -313,11 +354,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare // "Import as new": a trashed photo with the same content is replaced, as for a new file 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())); - for old in content.as_deref().and_then(|h| trash_hash.remove(crate::sync::base_hash(h))).into_iter().flatten() { - if purged.insert(old) { - purge.push(old); - } - } + trash.match_photo(content.as_deref(), None); report.imported.push(id.0); } PreparedItem::Duplicate { path, existing, reason, hash, file } => { @@ -361,29 +398,9 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare if let Some(h) = &info.content_hash { new_hash.entry(h.clone()).or_insert(id); } - for old in info - .content_hash - .as_deref() - .and_then(|h| trash_hash.remove(crate::sync::base_hash(h))) - .into_iter() - .flatten() - .chain(trash_path.remove(&stored)) - { - if purged.insert(old) { - purge.push(old); - } - } - // ticked by hand although another photo has this content: a Duplicate's hash - // (`:dup`), so the two photos can be told apart and neither is mistaken for the other - let mut hash = info.content_hash.clone(); - if anyway.contains(&normalize_import_path(&path)) - && let Some(h) = &mut hash - && (new_hash.get(h.as_str()).is_some_and(|first| *first != id) - || by_base.get(h.as_str()).is_some_and(|ids| ids.iter().any(|p| !purged.contains(p)))) - { - *h = format!("{h}:dup{}", id.0); - report.imported_anyway += 1; - } + trash.match_photo(info.content_hash.as_deref(), Some(&stored)); + let (hash, forced) = import_content_hash(id, &path, info.content_hash, &anyway, &new_hash, &by_base, &trash.purged); + report.imported_anyway += usize::from(forced); // a copy is catalogued under its new name let name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone()); @@ -444,8 +461,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } } // (built against the catalog as it is: one op list for all of them, ahead of the additions) - if !purge.is_empty() { - ops.insert(0, s.catalog.delete_photos_permanently_ops(&purge)); + if !trash.ids.is_empty() { + ops.insert(0, s.catalog.delete_photos_permanently_ops(&trash.ids)); } let log0 = s.pending_log.len(); let (verb, n) = if report.imported.is_empty() && !report.restored.is_empty() { From 21aaa58d6ed6666383af0d277c8b720cff7360c7 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Wed, 2 Dec 2026 22:17:03 -0500 Subject: [PATCH 09/12] 1425: English keys only here; the duplicate-import translations go to craft-i18n (AGENTS.md rule 16) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9MrskPCnnTeHPsF4a6j --- crates/ui-egui/locales/cs-formats.json | 7 +------ crates/ui-egui/locales/de-formats.json | 5 ----- crates/ui-egui/locales/es-formats.json | 5 ----- crates/ui-egui/locales/fi-formats.json | 7 +------ crates/ui-egui/locales/fr-formats.json | 5 ----- crates/ui-egui/locales/id-formats.json | 7 +------ crates/ui-egui/locales/it-formats.json | 7 +------ crates/ui-egui/locales/ja-formats.json | 5 ----- crates/ui-egui/locales/ka-formats.json | 7 +------ crates/ui-egui/locales/pl-formats.json | 7 +------ crates/ui-egui/locales/pt-br-formats.json | 5 ----- crates/ui-egui/locales/ru-formats.json | 5 ----- crates/ui-egui/locales/sv-formats.json | 7 +------ crates/ui-egui/locales/uk-formats.json | 5 ----- crates/ui-egui/locales/vi-formats.json | 7 +------ crates/ui-egui/locales/zh-hans-formats.json | 5 ----- crates/ui-egui/locales/zh-hant-formats.json | 5 ----- 17 files changed, 8 insertions(+), 93 deletions(-) diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 8a292c57d77..afd4435bb89 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -334,10 +334,5 @@ "Add “{keyword}” to {n} photo{}": "Přidat „{keyword}“ k fotografiím: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Pravidlo {n} z {m}: {what}. Přesun pomocí šipek", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Skupina {n} z {m}: shoda {mode}, uvnitř {count}. Přesun pomocí šipek", - ", rating {} of 5": ", hodnocení: {} z 5", - " · {n} imported although another photo has the same content": " · importováno {n}, přestože jiná fotografie má stejný obsah", - "Same content as {path} in the library": "Stejný obsah jako {path} v knihovně", - "Same file as {path} earlier in this import": "Stejný soubor jako {path} dříve v tomto importu", - "· {n} copies of library photos": "· kopie fotografií z knihovny: {n}", - "· {n} repeated in this import": "· opakování v tomto importu: {n}" + ", rating {} of 5": ", hodnocení: {} z 5" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 7779fa25bdb..591920bdf87 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -196,11 +196,6 @@ "{} spot(s) on this photo": "{} Retuschierstelle(n) in diesem Foto", "{} — show their photos": "{} – Fotos dieser Person anzeigen", "· {dups} already in the library": "· {dups} bereits in der Bibliothek", - "· {n} copies of library photos": "· {n} Kopien von Bibliotheksfotos", - "· {n} repeated in this import": "· {n} mehrfach in diesem Import", - "Same content as {path} in the library": "Gleicher Inhalt wie {path} in der Bibliothek", - "Same file as {path} earlier in this import": "Dieselbe Datei wie {path} weiter oben in diesem Import", - " · {n} imported although another photo has the same content": " · {n} importiert, obwohl ein anderes Foto denselben Inhalt hat", "· {n} photo{}": "· {n} Foto{}", "· {trashed} in Recently Deleted": "· {trashed} in „Zuletzt gelöscht“", "… and {more} more": "… und {more} weitere", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index e8b95b787d2..54b8c3c2f61 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -197,11 +197,6 @@ "{} spot(s) on this photo": "{} mancha(s) en esta foto", "{} — show their photos": "{}: mostrar sus fotos", "· {dups} already in the library": "· ya en la biblioteca: {dups}", - "· {n} copies of library photos": "· {n} copias de fotos de la biblioteca", - "· {n} repeated in this import": "· {n} repetidas en esta importación", - "Same content as {path} in the library": "Mismo contenido que {path} en la biblioteca", - "Same file as {path} earlier in this import": "El mismo archivo que {path} antes en esta importación", - " · {n} imported although another photo has the same content": " · {n} importadas aunque otra foto tiene el mismo contenido", "· {n} photo{}": "· {n} foto{}", "· {trashed} in Recently Deleted": "· {trashed} en Eliminadas recientemente", "… and {more} more": "… y {more} más", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 470d782bd10..924fce580fd 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -331,10 +331,5 @@ "{n} already there": "jo albumissa: {n}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Sääntö {n}/{m}: {what}. Siirrä nuolinäppäimillä", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Ryhmä {n}/{m}: täsmää {mode}, sisällä: {count}. Siirrä nuolinäppäimillä", - ", rating {} of 5": ", luokitus: {} / 5", - "· {n} copies of library photos": "· {n} kopiota kirjaston valokuvista", - "· {n} repeated in this import": "· {n} toistuu tässä tuonnissa", - "Same content as {path} in the library": "Sama sisältö kuin tiedostossa {path} kirjastossa", - "Same file as {path} earlier in this import": "Sama tiedosto kuin {path} aiemmin tässä tuonnissa", - " · {n} imported although another photo has the same content": " · {n} tuotu, vaikka toisella valokuvalla on sama sisältö" + ", rating {} of 5": ", luokitus: {} / 5" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 36a7245bb96..4eb8a1384e2 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -197,11 +197,6 @@ "{} spot(s) on this photo": "{} tache(s) sur cette photo", "{} — show their photos": "{} — afficher leurs photos", "· {dups} already in the library": "· déjà dans la bibliothèque : {dups}", - "· {n} copies of library photos": "· {n} copies de photos de la bibliothèque", - "· {n} repeated in this import": "· {n} répétées dans cet import", - "Same content as {path} in the library": "Même contenu que {path} dans la bibliothèque", - "Same file as {path} earlier in this import": "Même fichier que {path} plus haut dans cet import", - " · {n} imported although another photo has the same content": " · {n} importées bien qu'une autre photo ait le même contenu", "· {n} photo{}": "· {n} photo{}", "· {trashed} in Recently Deleted": "· {trashed} dans « Supprimés récemment »", "… and {more} more": "… et {more} de plus", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index b975d995faf..c492fcbb01e 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -334,10 +334,5 @@ "{n} already there": "{n} sudah ada", "Rule {n} of {m}: {what}. Move with the arrow keys": "Aturan {n} dari {m}: {what}. Pindahkan dengan tombol panah", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grup {n} dari {m}: cocokkan {mode}, isi: {count}. Pindahkan dengan tombol panah", - ", rating {} of 5": ", rating: {} dari 5", - "· {n} copies of library photos": "· {n} salinan foto pustaka", - "· {n} repeated in this import": "· {n} berulang dalam impor ini", - "Same content as {path} in the library": "Konten sama dengan {path} di pustaka", - "Same file as {path} earlier in this import": "File sama dengan {path} sebelumnya dalam impor ini", - " · {n} imported although another photo has the same content": " · {n} diimpor meskipun foto lain memiliki konten yang sama" + ", rating {} of 5": ", rating: {} dari 5" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index f43320eb788..96a493f446e 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -334,10 +334,5 @@ "Add “{keyword}” to {n} photo{}": "Aggiungi “{keyword}” a {n} foto{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regola {n} di {m}: {what}. Sposta con le frecce", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppo {n} di {m}: corrispondenza {mode}, {count} all’interno. Sposta con le frecce", - ", rating {} of 5": ", valutazione: {} su 5", - " · {n} imported although another photo has the same content": " · importate {n} anche se un’altra foto ha lo stesso contenuto", - "Same content as {path} in the library": "Stesso contenuto di {path} nella libreria", - "Same file as {path} earlier in this import": "Stesso file di {path} già presente in questa importazione", - "· {n} copies of library photos": "· copie di foto nella libreria: {n}", - "· {n} repeated in this import": "· ripetizioni in questa importazione: {n}" + ", rating {} of 5": ", valutazione: {} su 5" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 403a9fee0d1..9138a78640c 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -117,11 +117,6 @@ "{} photo{} not readable": "{}枚を読み込めません{:.0}", "{} spot(s) on this photo": "この写真に{}か所のスポット", "· {dups} already in the library": "・{dups}枚は読み込み済み", - "· {n} copies of library photos": "・{n}枚はライブラリの写真のコピー", - "· {n} repeated in this import": "・{n}枚はこの読み込み内で重複", - "Same content as {path} in the library": "ライブラリの {path} と同じ内容", - "Same file as {path} earlier in this import": "この読み込みの前にある {path} と同じファイル", - " · {n} imported although another photo has the same content": "・{n}枚は他の写真と同じ内容ですが読み込みました", "· {n} photo{}": "・{n}枚{:.0}", "· {trashed} in Recently Deleted": "・最近削除した写真内 {trashed} 枚", "… and {more} more": "…ほか{more}件", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 0c39e99da1d..46b74662cc6 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -337,10 +337,5 @@ "Add “{keyword}” to {n} photo{}": "დაამატეთ „{keyword}“ ფოტოებს: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "წესი {n}/{m}: {what}. გადაადგილება ისრებით", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "ჯგუფი {n}/{m}: დამთხვევა {mode}, შიგნით {count}. გადაადგილება ისრებით", - ", rating {} of 5": ", შეფასება: {} 5-დან", - " · {n} imported although another photo has the same content": " · იმპორტირებულია {n}, მიუხედავად იმისა, რომ სხვა ფოტოს იგივე შიგთავსი აქვს", - "Same content as {path} in the library": "იგივე შიგთავსი, რაც ბიბლიოთეკაში არსებულ {path}-ს", - "Same file as {path} earlier in this import": "იგივე ფაილი, რაც ამ იმპორტში ადრე არსებულ {path}-ს", - "· {n} copies of library photos": "· ბიბლიოთეკის ფოტოების ასლები: {n}", - "· {n} repeated in this import": "· გამეორებები ამ იმპორტში: {n}" + ", rating {} of 5": ", შეფასება: {} 5-დან" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 7727a9e8420..ded03cc37f9 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -334,10 +334,5 @@ "Add “{keyword}” to {n} photo{}": "Dodaj „{keyword}” do zdjęć: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Reguła {n} z {m}: {what}. Przenoś strzałkami", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupa {n} z {m}: dopasuj {mode}, w środku {count}. Przenoś strzałkami", - ", rating {} of 5": ", ocena: {} na 5", - " · {n} imported although another photo has the same content": " · zaimportowano {n}, mimo że inne zdjęcie ma tę samą zawartość", - "Same content as {path} in the library": "Taka sama zawartość jak {path} w bibliotece", - "Same file as {path} earlier in this import": "Taki sam plik jak wcześniejszy {path} w tym imporcie", - "· {n} copies of library photos": "· kopie zdjęć z biblioteki: {n}", - "· {n} repeated in this import": "· powtórzenia w tym imporcie: {n}" + ", rating {} of 5": ", ocena: {} na 5" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index ee0bed1fc42..d6361782ef1 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -146,11 +146,6 @@ "{} photo{} not readable": "{} foto(s) não legível(is){:.0}", "{} spot(s) on this photo": "{} ponto(s) nesta foto", "· {dups} already in the library": "· {dups} já na biblioteca", - "· {n} copies of library photos": "· {n} cópias de fotos da biblioteca", - "· {n} repeated in this import": "· {n} repetidas nesta importação", - "Same content as {path} in the library": "Mesmo conteúdo que {path} na biblioteca", - "Same file as {path} earlier in this import": "Mesmo arquivo que {path} antes nesta importação", - " · {n} imported although another photo has the same content": " · {n} importadas embora outra foto tenha o mesmo conteúdo", "· {n} photo{}": "· {n} foto{}", "· {trashed} in Recently Deleted": "· {trashed} em Excluídos recentemente", "… and {more} more": "… e mais {more}", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 659b3de4e5a..37053b60f1d 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -203,11 +203,6 @@ "{} spot(s) on this photo": "Пятен на этом фото: {}", "{} — show their photos": "{} — показать фото этого человека", "· {dups} already in the library": "· уже в библиотеке: {dups}", - "· {n} copies of library photos": "· {n} копий фото из библиотеки", - "· {n} repeated in this import": "· {n} повторов в этом импорте", - "Same content as {path} in the library": "То же содержимое, что у {path} в библиотеке", - "Same file as {path} earlier in this import": "Тот же файл, что и {path} выше в этом импорте", - " · {n} imported although another photo has the same content": " · {n} импортировано, хотя у другого фото то же содержимое", "· {n} photo{}": "· фото: {n}{:.0}", "· {trashed} in Recently Deleted": "· в «Недавно удалённых»: {trashed}", "… and {more} more": "… и ещё {more}", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 53beebe03ac..c84bcb2bddb 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -343,10 +343,5 @@ "{n} already there": "redan i albumet: {n}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} av {m}: {what}. Flytta med piltangenterna", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupp {n} av {m}: matcha {mode}, antal i gruppen: {count}. Flytta med piltangenterna", - ", rating {} of 5": ", betyg: {} av 5", - "· {n} copies of library photos": "· {n} kopior av bibliotekets foton", - "· {n} repeated in this import": "· {n} upprepade i denna import", - "Same content as {path} in the library": "Samma innehåll som {path} i biblioteket", - "Same file as {path} earlier in this import": "Samma fil som {path} tidigare i denna import", - " · {n} imported although another photo has the same content": " · {n} importerade fastän ett annat foto har samma innehåll" + ", rating {} of 5": ", betyg: {} av 5" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 1f26a874f60..02d5708de01 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -197,11 +197,6 @@ "{} spot(s) on this photo": "Ділянок на цьому фото: {}", "{} — show their photos": "{} — показати фото цієї особи", "· {dups} already in the library": "· уже в бібліотеці: {dups}", - "· {n} copies of library photos": "· {n} копій фото з бібліотеки", - "· {n} repeated in this import": "· {n} повторів у цьому імпорті", - "Same content as {path} in the library": "Той самий вміст, що й у {path} у бібліотеці", - "Same file as {path} earlier in this import": "Той самий файл, що й {path} вище в цьому імпорті", - " · {n} imported although another photo has the same content": " · {n} імпортовано, хоча інше фото має той самий вміст", "· {n} photo{}": "· фото: {n}{:.0}", "· {trashed} in Recently Deleted": "· у нещодавно видалених: {trashed}", "… and {more} more": "… і ще {more}", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 0cef8385073..75606d1563d 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -331,10 +331,5 @@ "{n} already there": "{n} đã có sẵn", "Rule {n} of {m}: {what}. Move with the arrow keys": "Quy tắc {n}/{m}: {what}. Di chuyển bằng phím mũi tên", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Nhóm {n}/{m}: khớp {mode}, bên trong: {count}. Di chuyển bằng phím mũi tên", - ", rating {} of 5": ", xếp hạng: {} trên 5", - "· {n} copies of library photos": "· {n} bản sao của ảnh trong thư viện", - "· {n} repeated in this import": "· {n} lặp lại trong lần nhập này", - "Same content as {path} in the library": "Cùng nội dung với {path} trong thư viện", - "Same file as {path} earlier in this import": "Cùng tệp với {path} trước đó trong lần nhập này", - " · {n} imported although another photo has the same content": " · {n} đã nhập dù ảnh khác có cùng nội dung" + ", rating {} of 5": ", xếp hạng: {} trên 5" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 0e7bf6dcdee..1c4bee97fb4 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -117,11 +117,6 @@ "{} photo{} not readable": "{0} 张照片无法读取{1:.0}", "{} spot(s) on this photo": "此照片上有 {0} 处污点", "· {dups} already in the library": "· {dups} 张已在图库中", - "· {n} copies of library photos": "· {n} 张是图库照片的副本", - "· {n} repeated in this import": "· {n} 张在本次导入中重复", - "Same content as {path} in the library": "与图库中的 {path} 内容相同", - "Same file as {path} earlier in this import": "与本次导入中靠前的 {path} 是同一文件", - " · {n} imported although another photo has the same content": " · 已导入 {n} 张,尽管另一张照片内容相同", "· {n} photo{}": "· {n} 张照片{0:.0}", "· {trashed} in Recently Deleted": "· {trashed} 张在“最近删除”中", "… and {more} more": "…以及另外 {more} 项", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index e287ea14f3b..9222de8f8bf 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -142,11 +142,6 @@ "{} photo{} not readable": "{} 張照片無法讀取{:.0}", "{} spot(s) on this photo": "此照片有 {} 個斑點", "· {dups} already in the library": "· {dups} 張已在照片庫中", - "· {n} copies of library photos": "· {n} 張是圖庫照片的副本", - "· {n} repeated in this import": "· {n} 張在本次匯入中重複", - "Same content as {path} in the library": "與圖庫中的 {path} 內容相同", - "Same file as {path} earlier in this import": "與本次匯入中較前的 {path} 是同一檔案", - " · {n} imported although another photo has the same content": " · 已匯入 {n} 張,儘管另一張照片內容相同", "· {n} photo{}": "· {n} 張照片{:.0}", "· {trashed} in Recently Deleted": "· {trashed} 張在「最近刪除」中", "… and {more} more": "…以及另外 {more} 個", From 16c8b7b098bd81000b73003363d6c6fd1aa18651 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Thu, 3 Dec 2026 09:05:30 -0500 Subject: [PATCH 10/12] Keep import duplicate identity separate from byte matching Use the base digest for merge reuse, cross-batch import matches and browsed-copy matching. Keep independent copy identities on reload and do not carry one into a different Lightroom catalog original. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9MrskPCnnTeHPsF4a6j --- crates/engine/src/cmd/convert.rs | 16 +++- crates/engine/src/import/commit.rs | 20 +++-- crates/engine/src/import/job.rs | 2 +- crates/engine/src/import/scan.rs | 5 +- crates/engine/src/lightroom_catalog.rs | 2 +- crates/engine/src/lightroom_catalog/tests.rs | 6 +- crates/engine/src/merge.rs | 2 +- crates/engine/src/tests/import.rs | 77 ++++++++++++++++++++ crates/engine/src/tests/merge.rs | 28 +++++++ 9 files changed, 143 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 4345abfd0c8..503c9175ff1 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -208,18 +208,26 @@ fn edit_copy(s: &mut Session, p: &Value, id: lightcraft_catalog::PhotoId, opts: pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: crate::media::ProbeInfo) -> Option { let preview_checked = ph.preview_stamp(&info.preview_only); // (a Duplicate's hash is its original's plus a suffix: the same content) - let base = |h: &Option| h.as_deref().map(crate::sync::base_hash).map(str::to_string); - let same = base(&info.content_hash) == base(&ph.content_hash) + let same = info.content_hash.as_deref().map(crate::sync::base_hash) == ph.content_hash.as_deref().map(crate::sync::base_hash) && info.file_size == ph.file_size && (info.width, info.height) == (ph.width, ph.height) && info.preview_only == ph.preview_only && preview_checked == ph.preview_checked; - (!same).then_some(Op::SetContent { + if same { + return None; + } + // A fresh byte digest replaces the old digest, not the identity of an independent copy. + let suffix = ph.content_hash.as_deref().and_then(|h| h.split_once(":dup")).map(|(_, suffix)| suffix); + let content_hash = info.content_hash.map(|h| match suffix { + Some(s) => format!("{h}:dup{s}"), + None => h, + }); + Some(Op::SetContent { id, width: info.width, height: info.height, file_size: info.file_size, - content_hash: info.content_hash, + content_hash, preview_only: info.preview_only, preview_checked, }) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index cdcd9081a54..8d5d4378727 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -359,11 +359,21 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } 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.local && p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id)) + let hash = hash?; + let h = crate::sync::base_hash(&hash); + new_hash.get(h).copied().or_else(|| { + let mut suffixed = None; + for p in s.catalog.photos().filter(|p| !p.local) { + let Some(stored) = p.content_hash.as_deref() else { continue }; + if stored == h { + return Some(p.id); + } + if suffixed.is_none() && crate::sync::base_hash(stored) == h { + suffixed = Some(p.id); + } + } + suffixed + }) }); let trashed = existing.filter(|id| s.catalog.photo(*id).is_some_and(|p| p.deleted)); match trashed { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index f6e3cad1436..9fe8bae78f6 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -391,7 +391,7 @@ impl ImportJob { // 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) { + if let Some(existing) = self.by_hash.get(crate::sync::base_hash(h)) { return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, file: None }; } index_hash(&mut self.by_hash, h, Some(id)); diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 227cca35166..5a03a6abc04 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -415,6 +415,7 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc if c.local && let Some(h) = hash { + let h = crate::sync::base_hash(h); match seen_hash.get(h) { Some((existing, earlier)) => { c.earlier = earlier.clone(); @@ -424,8 +425,8 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc None => { // (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, Some(f.clone()))); - browsed_first.insert(h.clone(), f.clone()); + seen_hash.insert(h.to_owned(), (None, Some(f.clone()))); + browsed_first.insert(h.to_owned(), f.clone()); } } } diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 4f4cf0b2cb1..adf8f25614f 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -1337,7 +1337,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co p.file_size = duplicate.file_size; p.duration = duplicate.duration; p.as_shot_wb = duplicate.as_shot_wb; - p.content_hash = duplicate.content_hash.clone(); + p.content_hash = duplicate.content_hash.as_deref().map(crate::sync::base_hash).map(str::to_owned); p.embedded_lens = duplicate.embedded_lens.clone(); p.preview_only = duplicate.preview_only.clone(); p.preview_checked = duplicate.preview_checked.clone(); diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 3503960858e..0bcf0ec93f0 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -379,7 +379,10 @@ fn a_content_duplicate_keeps_what_its_sidecar_says() { .unwrap(); std::fs::write(&source, native_catalog(&photo_tables((dir.to_str().unwrap(), "")))).unwrap(); let mut s = crate::Session::new(); - let other = library_photo(&mut s, "/elsewhere/a.ARW", |p| p.meta.caption = "Other photo's caption".into()); + let other = library_photo(&mut s, "/elsewhere/a.ARW", |p| { + p.meta.caption = "Other photo's caption".into(); + p.content_hash = Some(format!("same-bytes:dup{}", p.id.0)); + }); s.media.file_probe = Some(Arc::new(|_| { Ok(crate::media::ProbeInfo { format: "ARW".into(), @@ -396,6 +399,7 @@ fn a_content_duplicate_keeps_what_its_sidecar_says() { let new = s.catalog.photos().find(|p| p.id != other).unwrap_or_else(|| panic!("no new record: {r}")); assert_eq!((new.meta.caption.as_str(), new.meta.copyright.as_str()), ("Harbour at dawn", "© Sidecar Author"), "{r}"); assert_eq!(new.captured.as_deref(), Some("2024-05-06T07:08:09"), "the file's own capture time: {r}"); + assert_eq!(new.content_hash.as_deref(), Some("same-bytes"), "the matched photo's copy identity does not belong to this path"); std::fs::remove_dir_all(dir).unwrap(); } /// A file that becomes a content duplicate only after it was prepared (another import added a photo diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 944b6f5380b..b2c6a522e0d 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -473,7 +473,7 @@ impl Session { .catalog .photos() .filter_map(|p| { - if p.content_hash.as_deref() != Some(output_hash.as_str()) { + if p.content_hash.as_deref().map(crate::sync::base_hash) != Some(output_hash.as_str()) { return None; } let Source::File { path } = &p.source else { return None }; diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index b2dd7a4740c..ffd5f4ab252 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -4960,6 +4960,83 @@ fn content_duplicate_is_found_after_its_original_leaves_the_catalog() { let _ = std::fs::remove_dir_all(&src); } +#[test] +fn a_later_import_batch_names_the_surviving_import_anyway_copy() { + use crate::import::{ImportJob, ImportOptions, commit_prepared}; + let src = temp_dir("dup-anyway-across-batches"); + let path = |name: &str| src.join(name).to_string_lossy().into_owned(); + let original = path("original.png"); + let copy = path("copy.png"); + let later = path("later.png"); + write_png(Path::new(&original), 1); + std::fs::copy(&original, ©).unwrap(); + std::fs::copy(&original, &later).unwrap(); + let mut s = Session::new().with_fs(); + let opts = ImportOptions { import_anyway: [copy.clone()].into(), ..Default::default() }; + let mut job = ImportJob::new(&mut s, opts).unwrap(); + let cancel = std::sync::atomic::AtomicBool::new(false); + let prepared = job.prepare_files(vec![original, copy], &cancel); + let first = commit_prepared(&mut s, &job.opts, job.now(), prepared).unwrap(); + assert_eq!((first.imported.len(), first.imported_anyway), (2, 1), "{first:?}"); + let original_id = PhotoId(first.imported[0]); + s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: original_id }).unwrap(); + let prepared = job.prepare_files(vec![later], &cancel); + let second = commit_prepared(&mut s, &job.opts, job.now(), prepared).unwrap(); + assert_eq!(second.duplicates[0].existing, Some(first.imported[1]), "{second:?}"); +} + +#[test] +fn reloading_an_import_anyway_copy_keeps_its_own_content_key() { + let src = temp_dir("reload-import-anyway"); + let original = src.join("original.png"); + let copy = src.join("copy.png"); + write_png(&original, 1); + std::fs::copy(&original, ©).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [original]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [copy], "importAnyway": [copy]})).unwrap(); + assert_eq!(r["importedAnyway"], 1, "{r}"); + let id = PhotoId(r["imported"][0].as_u64().unwrap()); + let old = s.catalog.photo(id).unwrap().content_hash.clone().unwrap(); + // Reload with changed bytes must refresh the digest without losing the copy's identity. + write_png(©, 2); + s.execute("photo.reload", &json!({"ids": [id.0]})).unwrap(); + let new = s.catalog.photo(id).unwrap().content_hash.as_deref().unwrap(); + let digest = lightcraft_preview::hash_bytes(&std::fs::read(©).unwrap()).to_string(); + assert_ne!(new, old); + assert_eq!(new, format!("{digest}:dup{}", id.0)); +} + +#[test] +fn a_suffixed_browsed_copy_matches_an_import_anyway_copy() { + let src = temp_dir("browsed-and-import-anyway"); + let path = |name: &str| src.join(name).to_string_lossy().into_owned(); + let original = path("original.png"); + let library_copy = path("library.png"); + let browsed = path("browsed.png"); + write_png(Path::new(&original), 1); + std::fs::copy(&original, &library_copy).unwrap(); + std::fs::copy(&original, &browsed).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [browsed], "local": true})).unwrap(); + let browsed_id = s.catalog.photos().find(|p| p.local).unwrap().id; + let r = s.execute("photo.duplicate", &json!({"ids": [browsed_id.0]})).unwrap(); + let duplicate = PhotoId(r["ids"][0].as_u64().unwrap()); + let lightcraft_catalog::Source::File { path: browsed_copy } = &s.catalog.photo(duplicate).unwrap().source else { panic!("expected a file") }; + let browsed_copy = browsed_copy.clone(); + let r = s.execute("library.import", &json!({"paths": [original]})).unwrap(); + let original_id = PhotoId(r["imported"][0].as_u64().unwrap()); + let r = s.execute("library.import", &json!({"paths": [library_copy], "importAnyway": [library_copy]})).unwrap(); + assert_eq!(r["importedAnyway"], 1, "{r}"); + let copy_id = r["imported"][0].as_u64().unwrap(); + s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: original_id }).unwrap(); + let found = crate::import::scan(&mut s, std::slice::from_ref(&browsed_copy)); + assert_eq!((found[0].duplicate.as_deref(), found[0].existing), (Some("content"), Some(copy_id)), "{found:?}"); + let r = s.execute("library.import", &json!({"paths": [browsed_copy]})).unwrap(); + assert_eq!(ids(&r, "imported"), 0, "{r}"); + assert_eq!(r["duplicates"][0]["existing"], copy_id, "{r}"); +} + /// Fresh replaces every deleted instance of the incoming content, including intentional copies. /// Other deleted content stays available, and undo recovers each replaced photo with its edits. #[test] diff --git a/crates/engine/src/tests/merge.rs b/crates/engine/src/tests/merge.rs index d3a6a8bc42e..b4d6aa7b752 100644 --- a/crates/engine/src/tests/merge.rs +++ b/crates/engine/src/tests/merge.rs @@ -78,6 +78,34 @@ fn hdr_merge_command_creates_and_imports_a_dng() { let _ = std::fs::remove_dir_all(&dir); } +/// A repeat still reuses the result when its only catalog record is an Import Anyway copy. +#[test] +fn repeat_merge_reuses_an_import_anyway_copy() { + use crate::merge::{MergeFinish, MergeJob, MergeKind, MergeOutput}; + use lightcraft_catalog::{Op, PhotoId}; + let dir = temp_dir("hdr-import-anyway"); + let bytes = lightcraft_merge::synth::bracket_dngs(64, 48, &[0.0]).unwrap().remove(0); + let original = dir.join("result.dng").to_string_lossy().into_owned(); + let copy = dir.join("result-copy.dng").to_string_lossy().into_owned(); + std::fs::write(&original, &bytes).unwrap(); + std::fs::write(©, &bytes).unwrap(); + let mut s = Session::new().with_fs(); + let original_id = PhotoId(import(&mut s, vec![original.clone()])[0]); + let r = s.execute("library.import", &json!({"paths": [copy], "importAnyway": [copy]})).unwrap(); + assert_eq!(r["importedAnyway"], 1, "{r}"); + let copy_id = r["imported"][0].as_u64().unwrap(); + s.catalog.apply(Op::RemovePhoto { id: original_id }).unwrap(); + let job = MergeJob { + kind: MergeKind::Hdr { hdr: Default::default() }, + finish: MergeFinish::default(), + sources: vec![(original_id, original)], + preview: None, + read: std::sync::Arc::new(|_| Err("the merge bytes are already available".into())), + }; + let r = s.finish_merge(&job, MergeOutput { dng: bytes, preview: None, crop: None, info: json!({}) }).unwrap(); + assert_eq!((r["id"].as_u64(), r["reused"].as_bool()), (Some(copy_id), Some(true)), "{r}"); +} + /// An HDR merge keeps the reference frame's lens corrections. The sources carry an off-centre `WarpRectilinear` and /// `FixVignetteRadial` for their active area and have a default crop; the merged DNG must give "Enable Profile /// Corrections" the same correction as the reference photo, upright and for a vertical bracket (whose DNG keeps the From 00f0282e2f177fbc4687de850d60c8c85985c1c8 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Thu, 3 Dec 2026 12:33:01 -0500 Subject: [PATCH 11/12] Keep a browsed photo's Duplicate out of content matching A browsed record's `:dup` hash comes from photo.duplicate, not from Import Anyway, so the scan and promote_browsed treat it as a photo of its own, as on main. Matching it by base digest made the original a content duplicate of its -copy (which sorts first) and left it unticked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9MrskPCnnTeHPsF4a6j --- crates/engine/src/import/job.rs | 5 +-- crates/engine/src/import/scan.rs | 4 +-- crates/engine/src/tests/import.rs | 51 ++++++++++++++----------------- 3 files changed, 28 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 9fe8bae78f6..f44e339fead 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -390,8 +390,9 @@ impl ImportJob { fn promote_browsed(&mut self, f: String, id: PhotoId, hash: Option) -> PreparedItem { // 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(crate::sync::base_hash(h)) { + // (a browsed Duplicate's own `:dup` hash: a photo of its own, never a copy of another) + if let Some(h) = hash.as_deref().filter(|h| crate::sync::base_hash(h).len() == h.len()) { + if let Some(existing) = self.by_hash.get(h) { return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, file: None }; } index_hash(&mut self.by_hash, h, Some(id)); diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 5a03a6abc04..15daa475503 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -412,10 +412,10 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc 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 + // (a browsed Duplicate's own `:dup` hash: a photo of its own, never a copy of another) if c.local - && let Some(h) = hash + && let Some(h) = hash.as_deref().filter(|h| crate::sync::base_hash(h).len() == h.len()) { - let h = crate::sync::base_hash(h); match seen_hash.get(h) { Some((existing, earlier)) => { c.earlier = earlier.clone(); diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index ffd5f4ab252..987f3bac4bd 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5007,34 +5007,29 @@ fn reloading_an_import_anyway_copy_keeps_its_own_content_key() { assert_eq!(new, format!("{digest}:dup{}", id.0)); } -#[test] -fn a_suffixed_browsed_copy_matches_an_import_anyway_copy() { - let src = temp_dir("browsed-and-import-anyway"); - let path = |name: &str| src.join(name).to_string_lossy().into_owned(); - let original = path("original.png"); - let library_copy = path("library.png"); - let browsed = path("browsed.png"); - write_png(Path::new(&original), 1); - std::fs::copy(&original, &library_copy).unwrap(); - std::fs::copy(&original, &browsed).unwrap(); - let mut s = Session::new().with_fs(); - s.execute("library.import", &json!({"paths": [browsed], "local": true})).unwrap(); - let browsed_id = s.catalog.photos().find(|p| p.local).unwrap().id; - let r = s.execute("photo.duplicate", &json!({"ids": [browsed_id.0]})).unwrap(); - let duplicate = PhotoId(r["ids"][0].as_u64().unwrap()); - let lightcraft_catalog::Source::File { path: browsed_copy } = &s.catalog.photo(duplicate).unwrap().source else { panic!("expected a file") }; - let browsed_copy = browsed_copy.clone(); - let r = s.execute("library.import", &json!({"paths": [original]})).unwrap(); - let original_id = PhotoId(r["imported"][0].as_u64().unwrap()); - let r = s.execute("library.import", &json!({"paths": [library_copy], "importAnyway": [library_copy]})).unwrap(); - assert_eq!(r["importedAnyway"], 1, "{r}"); - let copy_id = r["imported"][0].as_u64().unwrap(); - s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: original_id }).unwrap(); - let found = crate::import::scan(&mut s, std::slice::from_ref(&browsed_copy)); - assert_eq!((found[0].duplicate.as_deref(), found[0].existing), (Some("content"), Some(copy_id)), "{found:?}"); - let r = s.execute("library.import", &json!({"paths": [browsed_copy]})).unwrap(); - assert_eq!(ids(&r, "imported"), 0, "{r}"); - assert_eq!(r["duplicates"][0]["existing"], copy_id, "{r}"); +/// A Duplicate made of a browsed photo (`photo.duplicate`, its own `:dup` hash) is a photo of its own: the +/// review offers both and importing them brings in both, whichever comes first (the copy's `-copy` name sorts +/// before the original's in a folder). +#[test] +fn a_browsed_photo_and_its_duplicate_are_both_imported() { + for copy_first in [true, false] { + let src = temp_dir(&format!("browsed-duplicate-{copy_first}")); + let original = src.join("a.png").to_string_lossy().into_owned(); + write_png(Path::new(&original), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [original], "local": true})).unwrap(); + let id = s.catalog.photos().find(|p| p.local).unwrap().id; + let r = s.execute("photo.duplicate", &json!({"ids": [id.0]})).unwrap(); + let duplicate = PhotoId(r["ids"][0].as_u64().unwrap()); + let lightcraft_catalog::Source::File { path: copy } = &s.catalog.photo(duplicate).unwrap().source else { panic!("expected a file") }; + let paths = if copy_first { vec![copy.clone(), original.clone()] } else { vec![original.clone(), copy.clone()] }; + let found = crate::import::scan(&mut s, &paths); + assert!(found.iter().all(|c| c.duplicate.is_none()), "copy first: {copy_first}: {found:?}"); + let r = s.execute("library.import", &json!({ "paths": paths })).unwrap(); + assert_eq!((ids(&r, "imported"), ids(&r, "duplicates")), (2, 0), "copy first: {copy_first}: {r}"); + assert!(s.catalog.photos().all(|p| !p.local), "copy first: {copy_first}"); + let _ = std::fs::remove_dir_all(&src); + } } /// Fresh replaces every deleted instance of the incoming content, including intentional copies. From 8300a82b2b554fa5e3ec793325437855e2d766a8 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Thu, 3 Dec 2026 12:33:01 -0500 Subject: [PATCH 12/12] Fix stray punctuation in the LR-IMP-DUPES row Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fnx9MrskPCnnTeHPsF4a6j --- docs/parity-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 49efad08e22..e477dfd0e26 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -76,7 +76,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`, `backup`), `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`), and `library.import` returns `skipped` too (issue #4319). 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`, `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.; the review names the matching library photo or earlier file, and a content duplicate may be checked by hand to import it as a second photo (`importAnyway`). | +| 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. The review names the matching library photo or earlier file, and a content duplicate may be checked by hand to import it as a second photo (`importAnyway`). | | 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 |