diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index cf0991f4e3d..503c9175ff1 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -207,17 +207,27 @@ 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 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/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..8d5d4378727 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -1,6 +1,8 @@ +use std::collections::HashSet; + 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}; @@ -212,6 +214,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().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); + } + } + 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 { @@ -254,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. @@ -261,26 +331,15 @@ 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) 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, mut trash_path): (HashMap, HashMap) = Default::default(); - 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); - } - if let Source::File { path } = &p.source { - trash_path.insert(path.clone(), p.id); - } - } - } - let mut purge: Vec = Vec::new(); - let mut purged: std::collections::HashSet = Default::default(); + let mut trash = FreshTrash::new(&s.catalog, opts.on_deleted); + let by_base = photos_by_base_hash(&s.catalog, !anyway.is_empty()); for it in prepared.items { match it { PreparedItem::Promote(id, fresh) => { @@ -295,20 +354,26 @@ 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); - } + trash.match_photo(content.as_deref(), None); report.imported.push(id.0); } PreparedItem::Duplicate { path, existing, reason, hash, file } => { let existing = existing.or_else(|| { - let h = hash?; - new_hash - .get(&h) - .copied() - .or_else(|| s.catalog.photos().find(|p| !p.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 { @@ -341,20 +406,19 @@ 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); - } - 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); - } + new_hash.entry(h.clone()).or_insert(id); } + 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()); 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) = @@ -407,8 +471,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() { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 96781be7a4a..f44e339fead 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -1,5 +1,6 @@ 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::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}; @@ -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) @@ -380,11 +390,12 @@ 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 { + // (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 }; } - 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)); @@ -443,7 +454,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 +482,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) { @@ -479,15 +499,18 @@ 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))); + 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() && 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); @@ -621,7 +644,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 +675,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..15daa475503 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) @@ -401,19 +412,21 @@ 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()) { 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); - 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()); } } } @@ -431,9 +444,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 +455,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/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/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..987f3bac4bd 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -4800,3 +4800,292 @@ 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); +} + +/// 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() { + 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() { + 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); +} + +#[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)); +} + +/// 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. +/// 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); + } +} 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 diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index 7e0b3e2bda9..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))) - && !(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 @@ -198,10 +202,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) || 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) && !self.is_copy_twin(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 +271,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 +351,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()); @@ -408,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"); @@ -533,9 +552,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 +634,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..b9d908411e7 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -199,16 +199,25 @@ 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 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 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.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 +716,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..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. | +| 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 |