From 84b296e0d6ee01f47267dd9fd2f1c092c4633e53 Mon Sep 17 00:00:00 2001 From: P2H <140529202+P2Hdontusegithub@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:40:11 +0700 Subject: [PATCH] Import: optional backup copy that mirrors the destination (#4840) (#4847) * Import: optional backup copy that mirrors the destination (#4840) Copy and Move imports can make a second, verified copy of each file in a backup folder (dialog: Backup to; library.import: backup). The backup takes the path the main copy ended up with, relative to the destination, so folder and rename templates, sequence numbers, the -1 of a taken name and Copy as DNG all carry over: the backup mirrors the destination. Each backup gets the check Copy runs (copy_verified: a new file, synced, checked against the probe hash or byte for byte); a bad one is removed and reported in backupFailed. A Move keeps the original of a photo whose backup failed. A different file already at the backup's place is left alone and reported, never renamed. A backup with mode add, or a backup folder that is, is inside or contains the destination, is refused up front. Co-Authored-By: Claude Opus 5.5 * Import backup: address review findings (#4840) - A backup place that is the file being imported (a backup folder set to the card) is not a backup: it is reported, and a Move keeps the original instead of deleting the only copy. - The backup folder check runs when library.import's params are checked, so the import dialog refuses it before creating a new album. - The "outside the destination" check also compares the folders with links resolved through their nearest existing ancestor, so a backup folder that doesn't exist yet can't slip inside the destination. - A photo browsed in Local that a Copy or Move adds in place is reported in backupFailed. - docs/user describes the latest release only: the import guide's backup step is held back until a release ships the option. Co-Authored-By: Claude Opus 5.5 * Import backup: resolve `..` and relative backup paths; refuse a backup on the main copy (#4840) - import_move::resolved makes a path absolute and follows it part by part: links of the parts that exist are resolved, and a `..` after a part that doesn't exist yet steps back from it (it used to stop there and compare the path unresolved, so /missing/../out/bk got past the "outside the destination" check). - back_up also refuses a backup place that is the main copy or one of a Move's placed sidecars, not only the original. Co-Authored-By: Claude Opus 5.5 * Import backup: compare backup and destination in one path form (#4840) On Windows, import_move::resolved gave a path whose first folder exists in the \?\C:\ form canonicalizing returns, and one whose first folder doesn't in the plain C:\ form; Path::starts_with told them apart, so a backup inside a destination that doesn't exist yet could pass the overlap check. resolved now always returns the plain form, and compare_key (used by the overlap check and the backup-is-the-file check) also ignores letter case on Windows. Co-Authored-By: Claude Opus 5.5 * Import backup: check folder overlap on resolved paths only (#4840) backup_folder_error also ran import_move::inside, which compares the raw paths first, so a folder beside the destination named through it (/../bk) was refused as inside it. The resolved comparison (compare_key: absolute, links and `..` followed) already covers equal and nested folders, so the raw checks are dropped. Co-Authored-By: Claude Opus 5.5 * add my real name in contributors * Import backup: a Move checks its backup again before removing the original (#4840) The backup path a transfer made was dropped from the Move's bookkeeping, so finish_moves checked only the main copy: a backup removed (or a backup drive unplugged) while the catalog was committed and saved still let the original be deleted. The path is now carried to finish_moves, and import_move::backup_intact checks the photo's backup and its sidecars' against the placed copies before the source is removed; when it fails the original stays, reported in kept like a backup that failed outright. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- contributors/people.toml | 1 + crates/engine/src/cmd/library/import.rs | 9 + crates/engine/src/cmd/library/specs.rs | 2 +- crates/engine/src/import.rs | 6 +- crates/engine/src/import/commit.rs | 103 ++++++++++-- crates/engine/src/import/files.rs | 1 + crates/engine/src/import/job.rs | 57 ++++++- crates/engine/src/import/types.rs | 21 +++ crates/engine/src/import_move.rs | 112 +++++++++++++ crates/engine/src/tests/import_move.rs | 195 ++++++++++++++++++++++ crates/mcp/src/tests.rs | 6 +- crates/mcp/src/tools.rs | 3 +- crates/ui-egui/src/dialogs/import.rs | 3 + crates/ui-egui/src/dialogs/import/body.rs | 50 +++++- crates/ui-egui/src/dialogs/import/task.rs | 17 ++ crates/ui-egui/src/headless/tests.rs | 87 ++++++++++ docs/feature-names.md | 4 + docs/parity-checklist.md | 3 +- 18 files changed, 653 insertions(+), 27 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 5ccb02efe7..fbebb7788b 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -91,6 +91,7 @@ display_name = "Brian Wang" display_name = "Terra854" [people.P2Hdontusegithub] +real_name = "Hoang Pham Huy" display_name = "Pizhy" [people.gmrmad1] diff --git a/crates/engine/src/cmd/library/import.rs b/crates/engine/src/cmd/library/import.rs index 99d065b2b7..5e496811ad 100644 --- a/crates/engine/src/cmd/library/import.rs +++ b/crates/engine/src/cmd/library/import.rs @@ -76,6 +76,10 @@ pub fn import_params(s: &Session, p: &Value) -> Result { Some(n) => usize::try_from(n).map_err(|_| bad("library.import", "renameStart is too large for this platform"))?, None => 1, }; + let backup = str_param(p, "backup").map(str::trim).filter(|b| !b.is_empty()).map(str::to_string); + if backup.is_some() && mode == crate::import::ImportMode::Add { + return Err(bad("library.import", "backup needs mode copy or move: adding in place copies nothing to back up")); + } let keywords = strs(p, "keywords"); for k in &keywords { s.catalog.check_keyword_name(k).map_err(|e| bad("library.import", e.to_string()))?; @@ -91,11 +95,16 @@ pub fn import_params(s: &Session, p: &Value) -> Result { rename_start, metadata_preset, convert_dng: bool_or(p, "dng", false), + backup, local: bool_or(p, "local", false), // (only the Lightroom import makes records of duplicates) read_duplicates: false, recipe: crate::cmd::recipe_param(p, "library.import")?, }; + // (here, not only when the import starts: the dialog creates a new album after this check) + if let Some(e) = crate::import::backup_refusal(s, &opts) { + return Err(bad("library.import", e)); + } let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); Ok(ImportRequest { paths, opts, album, album_name }) } diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 6eae2aef95..b366069fe2 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), 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), 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?: [..], 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?}", always, |s, p| { let req = import_params(s, p)?; diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 35068a433d..dbdc6d2574 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -57,7 +57,7 @@ pub use files::{ pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with}; #[cfg(test)] use job::PreparedItem; -pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with}; +pub use job::{ImportJob, Prepared, backup_folder_error, backup_refusal, candidate_thumb_key, import, import_with}; pub use reads::{MAX_SKIPPED, MAX_STUCK_READERS, ReadWatch, STALL_AFTER, StalledRead, StuckReaders}; pub(crate) use scan::scan_files; pub use scan::{ @@ -67,8 +67,8 @@ pub use scan::{ #[cfg(test)] use scan::{library_files, library_hashes}; pub use types::{ - Duplicate, FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, ImportUprightMode, ImportWarning, ImportWarningCode, Kept, Moved, - OnDeleted, Organize, Skipped, + BackupCopy, Duplicate, 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 863f39cfd8..86827a93ed 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -1,7 +1,7 @@ use super::defaults::apply_import_defaults; use super::files::copy_into; use super::job::{Prepared, PreparedItem, ReadyFile}; -use super::types::{Duplicate, FileFacts, ImportOptions, ImportReport, Kept, Moved, OnDeleted}; +use super::types::{BackupCopy, Duplicate, FileFacts, ImportOptions, ImportReport, Kept, Moved, OnDeleted}; use super::{HashMap, Op, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; /// A batch's items in file order while its transfers are pending ([`ImportJob::run_plan`]). @@ -30,6 +30,8 @@ pub(super) struct Transfer { pub(super) how: How, /// Copy as DNG. pub(super) dng: bool, + /// [`ImportOptions::backup`]: (the destination root `dir` is inside, the backup folder). + pub(super) backup: Option<(PathBuf, PathBuf)>, } pub(super) enum How { @@ -139,8 +141,9 @@ pub(super) fn run_transfers( /// Copy or move one planned file (and Copy as DNG); its item. fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> PreparedItem { - let Transfer { path, mut info, sidecar, dir, how, dng, .. } = t; + let Transfer { path, mut info, sidecar, dir, how, dng, backup } = t; let mut placed = None; + let mut converted = false; let mut stored = match how { How::Place { name } => match crate::import_move::place(Path::new(&path), &dir, &name) { Ok(pl) => { @@ -163,12 +166,50 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P Ok(dng) => { let _ = std::fs::remove_file(&stored); stored = dng; + converted = true; info.format = "DNG".into(); } Err(e) => log::warn!("import {path}: copy as DNG: {e}"), } } - PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed })) + let backup = + backup.map(|(root, to)| back_up(&path, &stored, placed.as_ref(), &root, &to, if converted { None } else { info.content_hash.as_deref() })); + PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed, backup })) +} + +/// The backup copy of a file an import put at `stored` inside `root` — with a Move's sidecars beside +/// it, so the backup holds what the destination does ([`crate::import_move::backup_copy`]); its path, +/// or why it has none. `probe_hash` is the content hash of `stored` as the import read it (`None`: +/// compared byte for byte). A backup place that is the file imported from (`source`), the main copy +/// (`stored`) or one of their sidecars is no backup: the identical file found there is that file +/// itself, and a Move removes the original. +fn back_up( + source: &str, + stored: &str, + placed: Option<&crate::import_move::Placed>, + root: &Path, + to: &Path, + probe_hash: Option<&str>, +) -> Result { + let expect = probe_hash.and_then(lightcraft_preview::Hash128::parse); + let same = |a: &Path, b: &Path| crate::import_move::compare_key(a) == crate::import_move::compare_key(b); + let is_source = |p: &Path| { + same(p, Path::new(source)) + || same(p, Path::new(stored)) + || placed.is_some_and(|pl| pl.sidecars.iter().any(|sc| same(p, &sc.src) || same(p, &sc.dst))) + }; + let refuse = |p: &Path| format!("the backup's place {} is the file being imported or its copy: no backup copy was made", p.display()); + let copy = crate::import_move::backup_copy(Path::new(stored), root, to, expect)?; + if is_source(©) { + return Err(refuse(©)); + } + for sc in placed.map(|p| p.sidecars.as_slice()).unwrap_or_default() { + let c = crate::import_move::backup_copy(&sc.dst, root, to, None)?; + if is_source(&c) { + return Err(refuse(&c)); + } + } + Ok(copy.to_string_lossy().to_string()) } /// A trashed photo's file is not where the library had it (never on the web, where paths are @@ -205,7 +246,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut report = ImportReport { scanned: prepared.scanned, skipped: prepared.skipped, ..Default::default() }; let mut ops = Vec::new(); // Move: placed at the destination, sources untouched until the records are committed - let mut placed: Vec = Vec::new(); + // (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 @@ -232,6 +274,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare if s.catalog.photo(id).is_some_and(|p| p.local) { ops.push(Op::SetLocal { id, local: false }); } + note_no_backup_in_place(s, opts, id, &mut report); // "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())); @@ -276,8 +319,9 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare PreparedItem::Failed(path, e) => report.failed.push((path, e)), PreparedItem::Kept(k) => report.kept.push(k), PreparedItem::Ready(r) => { - let ReadyFile { path, stored, info, sidecar, placed: pl } = *r; - placed.extend(pl); + let ReadyFile { path, stored, info, sidecar, placed: pl, backup } = *r; + let backed_up = note_backup(&mut report, &path, &stored, backup); + 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); @@ -358,7 +402,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare && let Err(e) = s.commit(&format!("{verb} {n} Photo{}", if n == 1 { "" } else { "s" }), Op::Batch { ops }) { // nothing was catalogued: take the moves back (their sources were never touched) - placed.iter().for_each(crate::import_move::rollback); + placed.iter().for_each(|(p, _)| crate::import_move::rollback(p)); return Err(e); } if !placed.is_empty() { @@ -367,23 +411,62 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare Ok(report) } +/// A file's backup outcome into the report; the outcome again, for a Move to check before it removes +/// the original (`None`: no backup was asked for). +fn note_backup(report: &mut ImportReport, path: &str, stored: &str, backup: Option>) -> Option> { + Some(match backup? { + Ok(to) => { + report.backups.push(BackupCopy { path: stored.to_string(), to: to.clone() }); + Ok(PathBuf::from(to)) + } + Err(reason) => { + report.backup_failed.push(Kept { path: path.to_string(), reason: reason.clone() }); + Err(reason) + } + }) +} + +/// A photo browsed in Local joins the library where it is, even in a Copy or Move import: with a +/// backup folder, the report says it has no backup copy. +fn note_no_backup_in_place(s: &Session, opts: &ImportOptions, id: PhotoId, report: &mut ImportReport) { + if opts.backup.as_deref().is_some_and(|b| !b.trim().is_empty()) + && matches!(opts.mode, super::ImportMode::Copy | super::ImportMode::Move) + && let Some(Source::File { path }) = s.catalog.photo(id).map(|p| &p.source) + { + let reason = "a photo browsed in Local is added where it is, so no backup copy was made".to_string(); + report.backup_failed.push(Kept { path: path.clone(), reason }); + } +} + /// Move, after the commit: save the library, then remove each source whose destination is /// still intact. Nothing is removed when the library can't be saved: saved is on disk, not just /// handed to the catalog log's thread, which looks at the folder only when it writes (issue #3240), /// so the log is flushed first. -fn finish_moves(s: &mut Session, placed: Vec, log0: usize, report: &mut ImportReport) { +fn finish_moves(s: &mut Session, placed: Vec<(crate::import_move::Placed, Option>)>, log0: usize, report: &mut ImportReport) { // (saving here clears the pending ops, so the sidecars `execute` would auto-write are written here) let auto: Vec = if s.xmp.auto_write { s.pending_log.get(log0..).map(<[Op]>::to_vec).unwrap_or_default() } else { Vec::new() }; let before = s.pending_log.len(); if let Err(e) = s.persist().and_then(|()| s.flush_log()) { - for p in placed { + for (p, _) in placed { let reason = format!("the library could not be saved ({e}): the original stays; the photo uses the copy at {}", p.dst.display()); report.kept.push(Kept { path: p.src.to_string_lossy().to_string(), reason }); } return; } - for p in placed { + for (p, backup) in placed { let from = p.src.to_string_lossy().to_string(); + // a card is never wiped while the photo has one copy only: the backup is looked at again now, + // as the destination is (a backup drive can be unplugged while the library is saved) + let no_backup = match &backup { + Some(Err(why)) => Some(why.clone()), + Some(Ok(to)) => crate::import_move::backup_intact(&p, to).err(), + None => None, + }; + if let Some(why) = no_backup { + let reason = format!("it has no backup copy ({why}): the original stays; the photo uses the copy at {}", p.dst.display()); + report.kept.push(Kept { path: from, reason }); + continue; + } match crate::import_move::finish(&p) { Ok(kept) => { let sidecars = p.sidecars.iter().map(|sc| sc.dst.to_string_lossy().to_string()).collect(); diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index 260fc6d564..a38031ae39 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -663,6 +663,7 @@ mod prepared_tests { info: ProbeInfo { format: "JPG".into(), ..ProbeInfo::default() }, sidecar: None, placed: None, + backup: None, }; let mut prepared = Prepared { scanned: 2, diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index d48f62890e..96781be7a4 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -31,6 +31,8 @@ pub struct ImportJob { mode: ImportMode, lib_dir: Option, copy_root: Option, + /// [`ImportOptions::backup`], when the import copies or moves. + backup_root: Option, /// The library as it was when the import was set up, until it is looked up /// ([`ImportJob::look_up_library`], with the first files): setting an import up is the /// session's thread, and a table of a library of millions of photos takes seconds. With it, @@ -97,6 +99,8 @@ pub(super) struct ReadyFile { pub(super) info: ProbeInfo, pub(super) sidecar: Option, pub(super) placed: Option, + /// [`ImportOptions::backup`]: its backup copy, or why it has none. `None`: no backup asked for. + pub(super) backup: Option>, } impl Prepared { @@ -140,7 +144,7 @@ impl Prepared { items.push(item); continue; }; - let ReadyFile { path, stored, info, sidecar, placed } = *ready; + 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()); if let Some(existing) = existing_path.or(existing_hash) { @@ -155,13 +159,47 @@ impl Prepared { file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), }); } else { - items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed }))); + items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed, backup }))); } } self.items = items; } } +/// Why `backup` can't be an import's backup folder ([`ImportOptions::backup`]), if it can't: the +/// import doesn't copy or move (`transfer`: as asked; `mode`: in effect, Add in a library that keeps +/// its files in its own storage), or the folder is the destination `root`, inside it, or holds it — +/// a backup there could land on the main copies themselves and be counted as made. +pub fn backup_folder_error(mode: ImportMode, transfer: bool, root: Option<&Path>, backup: &Path) -> Option { + if !transfer { + return Some("a backup copy is made only when the photos are copied or moved (mode copy or move)".into()); + } + if mode == ImportMode::Add { + return Some("this library keeps its photos in its own storage, so no backup copy can be made".into()); + } + let root = root?; + // (compared resolved: absolute, links and `..` followed, also for a folder that doesn't exist yet, + // so `/../bk` beside the destination is no overlap) + let (b, r) = (crate::import_move::compare_key(backup), crate::import_move::compare_key(root)); + (b.starts_with(&r) || r.starts_with(&b)) + .then(|| format!("the backup folder {} must be outside the destination {} and not contain it", backup.display(), root.display())) +} + +/// Why `opts.backup` can't be this import's backup folder in `s`, if it can't ([`backup_folder_error`] +/// with the mode and destination the import will use). `None` without a backup folder. +pub fn backup_refusal(s: &Session, opts: &ImportOptions) -> Option { + let backup = opts.backup.as_deref().map(str::trim).filter(|b| !b.is_empty())?; + let transfer = matches!(opts.mode, ImportMode::Copy | ImportMode::Move); + let mode = if transfer && s.library.as_ref().is_some_and(|l| !l.on_disk) { ImportMode::Add } else { opts.mode }; + let root = opts + .destination + .as_deref() + .filter(|d| !d.trim().is_empty()) + .map(PathBuf::from) + .or_else(|| s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Originals"))); + backup_folder_error(mode, transfer, root.as_deref(), Path::new(backup)) +} + fn normalize_import_path(path: &str) -> String { let path = path.replace('\\', "/"); if cfg!(windows) { path.to_lowercase() } else { path } @@ -192,6 +230,10 @@ impl ImportJob { if matches!(mode, ImportMode::Copy | ImportMode::Move) && copy_root.is_none() { return Err(crate::EngineError::Other("copying or moving needs a destination folder or an open library".into())); } + let backup_root = opts.backup.as_deref().map(str::trim).filter(|b| !b.is_empty()).map(PathBuf::from); + if let Some(e) = backup_refusal(s, &opts) { + return Err(crate::cmd::bad("library.import", e)); + } let fresh = opts.on_deleted == OnDeleted::Fresh; Ok(ImportJob { seq: Some(opts.rename_start.max(1)), @@ -199,6 +241,7 @@ impl ImportJob { mode, lib_dir, copy_root, + backup_root, library: Some((s.catalog.clone(), fresh)), by_path: HashMap::new(), local_sizes: HashMap::new(), @@ -541,6 +584,7 @@ impl ImportJob { }; let folders = opts.organize.folders(&q); let dir = folders.iter().fold(root.to_path_buf(), |d, f| d.join(f)); + let backup = self.backup_root.clone().map(|b| (root.to_path_buf(), b)); // the name this file gets depends on what a pending transfer of a like-named file // into the same folder ends up with: that one goes first let as_named = name.as_deref().unwrap_or(if own.is_empty() { "photo" } else { own.as_str() }); @@ -566,7 +610,7 @@ impl ImportJob { // (transfers of one folder and name family can take each other's names, so they never run together) plan.pending_families.insert(family); plan.pending_hashes.extend(info.content_hash.clone()); - plan.transfers.push(Transfer { path, info, sidecar, dir, how, dng }); + plan.transfers.push(Transfer { path, info, sidecar, dir, how, dng, backup }); continue; } (ImportMode::Move, _) => { @@ -580,7 +624,12 @@ impl ImportJob { self.by_hash.insert(h.clone(), None); } self.done.fetch_add(1, Relaxed); - plan.slots.push(Slot::Item(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed: None })))); + // (a file already inside the destination or the library is added where it is: nothing was copied to back up) + let backup = self + .backup_root + .as_ref() + .map(|_| Err("already inside the destination or the library: added where it is, so no backup copy was made".into())); + plan.slots.push(Slot::Item(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed: None, backup })))); } self.run_plan(&mut plan, &mut out, cancel); out diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index 0d9a3412cd..b2f017fd80 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -67,6 +67,11 @@ pub struct ImportOptions { pub metadata_preset: Option, /// Copy: raws are copied as DNG (Copy as DNG). pub convert_dng: bool, + /// Copy or Move: a backup folder. Each file the import copies or moves into the destination is + /// copied here too, with the same folders and name as in the destination (a mirror of it, not a + /// folder of its own), and verified as the main copy is. A file the import adds where it is + /// gets none, and is reported ([`ImportReport::backup_failed`]). `None` (the default): no backup. + pub backup: Option, /// A duplicate by content is read as a new file is, its XMP sidecar included: the Lightroom /// import makes a record of its own from it ([`Duplicate::file`], #2589). Any other import /// skips it without looking up its sidecar (a round trip per name on a network share, #2954). @@ -218,6 +223,13 @@ pub struct ImportReport { pub kept: Vec, /// (path, error) pub failed: Vec<(String, String)>, + /// [`ImportOptions::backup`]: the backup copies made. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub backups: Vec, + /// [`ImportOptions::backup`]: imported photos with no backup copy, and why. A Move keeps such a + /// photo's original at the source ([`ImportReport::kept`]). + #[serde(rename = "backupFailed", skip_serializing_if = "Vec::is_empty")] + pub backup_failed: Vec, /// Files found after expanding folders. pub scanned: usize, /// Photos whose metadata/develop settings were read from an XMP sidecar (or embedded XMP). @@ -278,6 +290,15 @@ pub struct Moved { pub sidecars: Vec, } +/// A backup copy an import made ([`ImportOptions::backup`]). +#[derive(Clone, Debug, Default, Serialize)] +pub struct BackupCopy { + /// The imported file: the copy in the destination, which the library uses. + pub path: String, + /// Its backup. + pub to: String, +} + /// A source a Move left where it was. #[derive(Clone, Debug, Default, Serialize)] pub struct Kept { diff --git a/crates/engine/src/import_move.rs b/crates/engine/src/import_move.rs index 06f22be40c..985caeea3d 100644 --- a/crates/engine/src/import_move.rs +++ b/crates/engine/src/import_move.rs @@ -56,6 +56,9 @@ pub(crate) enum Fault { Corrupt, /// Removing the source fails (as on a read-only card). FailRemove, + /// A backup copy ([`backup_copy`]) comes out different from the file it copies; the main copy + /// is unaffected. + CorruptBackup, /// Each copy takes a little longer and notes the thread it ran on ([`copy_threads`]), to see /// an import's copies run side by side. Slow, @@ -110,6 +113,60 @@ pub(crate) fn inside(path: &Path, dir: &Path) -> bool { } } +/// `path` made absolute, with symbolic links and `..` resolved, also when it doesn't exist yet: +/// each part is followed in turn, through the links of the parts that exist, so a folder an import +/// is about to create still lands where its existing parents' links point, and a `..` after a part +/// that doesn't exist yet steps back from it. A Windows path always comes back in its plain form +/// (`C:\…`, `\\server\share\…`), never the `\\?\` form canonicalizing gives, so a path whose first +/// folder exists and one whose first folder doesn't compare alike. +pub(crate) fn resolved(path: &Path) -> PathBuf { + let abs = + if path.is_absolute() { path.to_path_buf() } else { std::env::current_dir().map(|d| d.join(path)).unwrap_or_else(|_| path.to_path_buf()) }; + let abs = plain_prefix(abs); + let mut out = PathBuf::new(); + for part in abs.components() { + match part { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + out.pop(); + } + std::path::Component::Normal(name) => { + out.push(name); + // (only after a name: a bare drive canonicalizes to that drive's current folder) + if let Ok(real) = fs::canonicalize(&out) { + out = plain_prefix(real); + } + } + root => out.push(root), + } + } + out +} + +/// `path` as [`resolved`] gives it, in a form to compare by: letter case doesn't tell Windows paths +/// apart, so there it is lower-cased. +pub(crate) fn compare_key(path: &Path) -> PathBuf { + let r = resolved(path); + if cfg!(windows) { PathBuf::from(r.to_string_lossy().to_lowercase()) } else { r } +} + +/// A Windows `\\?\C:\…` or `\\?\UNC\server\…` path in its plain form (`C:\…`, `\\server\…`); any +/// other path as it is. +fn plain_prefix(path: PathBuf) -> PathBuf { + if !cfg!(windows) { + return path; + } + let s = path.to_string_lossy(); + if let Some(rest) = s.strip_prefix(r"\\?\UNC\") { + return PathBuf::from(format!(r"\\{rest}")); + } + match s.strip_prefix(r"\\?\") { + // (a drive letter and a colon: other `\\?\` paths have no plain form) + Some(rest) if rest.as_bytes().get(1) == Some(&b':') => PathBuf::from(rest), + _ => path, + } +} + pub(crate) fn is_symlink(path: &Path) -> bool { fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) } @@ -217,6 +274,61 @@ pub(crate) fn copy_new(src: &Path, dir: &Path, name: &str, expect: Option) -> Result { + let rel = file.strip_prefix(root).map_err(|_| format!("{} is not inside {}: no backup copy was made", file.display(), root.display()))?; + let dst = backup.join(rel); + if let Some(dir) = dst.parent() { + fs::create_dir_all(dir).map_err(|e| format!("backup copy: {}: {e}", dir.display()))?; + } + // (tests: the backup's copy comes out bad, not the main one) + #[cfg(test)] + let corrupt = injected(Fault::CorruptBackup); + #[cfg(test)] + if corrupt { + inject(Fault::Corrupt); + } + let r = copy_verified(file, &dst, expect); + #[cfg(test)] + if corrupt { + inject(Fault::CorruptBackup); + } + match r { + Ok(()) => Ok(dst), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => match same_bytes(file, &dst) { + Ok(true) => Ok(dst), + Ok(false) => Err(format!("a different file is already at {}: it was left as it is, and no backup copy was made", dst.display())), + Err(e) => Err(format!("backup copy: {}: {e}", dst.display())), + }, + Err(e) => Err(format!("backup copy to {}: {e} (no bad copy was left)", dst.display())), + } +} + +/// A Move's backup ([`backup_copy`] of a placed photo, at `backup`) is still there before the +/// original is removed: the photo with the same bytes as its placed copy, and each placed sidecar +/// beside it with the same bytes as its own (the backup mirrors the destination, so they share a +/// folder there too). `Err`: what is missing or changed. +pub(crate) fn backup_intact(p: &Placed, backup: &Path) -> Result<(), String> { + let check = |placed: &Path, copy: &Path| match same_bytes(placed, copy) { + Ok(true) => Ok(()), + Ok(false) => Err(format!("the backup copy {} changed", copy.display())), + Err(e) => Err(format!("the backup copy {} can't be read: {e}", copy.display())), + }; + check(&p.dst, backup)?; + let dir = backup.parent().unwrap_or(backup); + for sc in &p.sidecars { + if let Some(name) = sc.dst.file_name() { + check(&sc.dst, &dir.join(name))?; + } + } + Ok(()) +} + /// Undo a [`place`]: remove what it created at the destination (the sources were never touched). pub(crate) fn rollback(p: &Placed) { for sc in p.sidecars.iter().filter(|s| s.created) { diff --git a/crates/engine/src/tests/import_move.rs b/crates/engine/src/tests/import_move.rs index c4e9c52522..4f4bad3e2f 100644 --- a/crates/engine/src/tests/import_move.rs +++ b/crates/engine/src/tests/import_move.rs @@ -535,3 +535,198 @@ fn finish_keeps_the_original_when_the_copy_changed_to_the_same_length() { inject(Fault::None); let _ = std::fs::remove_dir_all(&base); } + +/// A backup copy (the `backup` param) mirrors the destination: the same folders and names the +/// import gave the main copies — the folder template, the rename template and its numbers, and the +/// `-1` a taken name got — not a folder of its own, and a Move's sidecars come along. +#[test] +fn a_backup_copy_mirrors_the_destination() { + let base = temp_dir("backup-mirror"); + let (card, dest, backup) = (base.join("card"), base.join("Photos"), base.join("Backup")); + write_png(&card.join("a.png"), 1); + write_png(&card.join("b.png"), 2); + // someone else's file holds the first name in the destination: the copy is numbered, and so is its backup + let taken = dest.join("2026/20260114/20260114_001.png"); + std::fs::create_dir_all(taken.parent().unwrap()).unwrap(); + std::fs::write(&taken, b"someone else's file").unwrap(); + let mut s = session(); + let r = s + .execute( + "library.import", + &json!({"paths": [card.to_string_lossy()], "mode": "copy", "destination": dest.to_string_lossy(), "backup": backup.to_string_lossy(), + "organize": "{date:%Y}/{date:%Y%m%d}", "rename": "{date:%Y%m%d}_{seq:3}"}), + ) + .unwrap(); + assert_eq!(len(&r, "imported"), 2, "{r}"); + assert_eq!(len(&r, "backups"), 2, "{r}"); + assert_eq!(len(&r, "backupFailed"), 0, "{r}"); + let copies: Vec = files_under(&dest).into_iter().filter(|f| *f != "2026/20260114/20260114_001.png").collect(); + assert_eq!(copies.len(), 2); + assert!(copies.iter().any(|f| f.ends_with("_001-1.png")), "the taken name was numbered: {copies:?}"); + assert_eq!(files_under(&backup), copies, "the same folders and names as the main copies"); + for f in &copies { + assert_eq!(std::fs::read(backup.join(f)).unwrap(), std::fs::read(dest.join(f)).unwrap(), "{f}"); + } + // the library uses the main copies, never the backup + assert!(photo_paths(&s).iter().all(|p| Path::new(p).starts_with(&dest)), "{:?}", photo_paths(&s)); + + // Move: the sidecar beside the moved photo is backed up beside its backup + let (card2, dest2, backup2) = (base.join("card2"), base.join("Photos2"), base.join("Backup2")); + write_png(&card2.join("c.png"), 3); + std::fs::write(card2.join("c.xmp"), xmp(4)).unwrap(); + let r = import_move(&mut s, &[&card2], &dest2, json!({"organize": "flat", "backup": backup2.to_string_lossy()})); + assert_eq!(len(&r, "moved"), 1, "{r}"); + assert_eq!(files_under(&backup2), files_under(&dest2)); + assert_eq!(files_under(&backup2), ["c.png", "c.xmp"]); + assert_eq!(files_under(&card2), Vec::::new(), "a backed-up move empties the card"); + let _ = std::fs::remove_dir_all(&base); +} + +/// A backup copy gets the check the main copy gets: one that comes out different is removed and +/// reported, the photo is still imported, and a Move keeps that photo's original, so the card never +/// loses a photo that has one copy only. A different file already at the backup's place is left +/// alone (and not given another name, which would break the mirror); the same file counts. +#[test] +fn a_bad_backup_copy_is_caught_and_a_move_keeps_its_original() { + for mode in ["copy", "move"] { + let base = temp_dir(&format!("backup-bad-{mode}")); + let (card, dest, backup) = (base.join("card"), base.join("out"), base.join("bk")); + write_png(&card.join("a.png"), 5); + let bytes = std::fs::read(card.join("a.png")).unwrap(); + let mut s = session(); + inject(Fault::CorruptBackup); + let r = s.execute( + "library.import", + &json!({"paths": [card.to_string_lossy()], "mode": mode, "destination": dest.to_string_lossy(), "backup": backup.to_string_lossy(), "organize": "flat"}), + ); + inject(Fault::None); + let r = r.unwrap(); + assert_eq!(len(&r, "imported"), 1, "{mode}: {r}"); + assert_eq!(len(&r, "backups"), 0, "{mode}: {r}"); + assert_eq!(len(&r, "backupFailed"), 1, "{mode}: {r}"); + assert!(r["backupFailed"][0]["reason"].as_str().unwrap().contains("differs"), "{r}"); + assert_eq!(files_under(&backup), Vec::::new(), "{mode}: no bad backup left"); + assert_eq!(std::fs::read(dest.join("a.png")).unwrap(), bytes, "{mode}: the main copy is good"); + assert_eq!(std::fs::read(card.join("a.png")).unwrap(), bytes, "{mode}: the original stays"); + if mode == "move" { + assert_eq!(len(&r, "moved"), 0, "{r}"); + assert!(r["kept"][0]["reason"].as_str().unwrap().contains("no backup copy"), "{r}"); + } + let _ = std::fs::remove_dir_all(&base); + } + + // a backup folder that is the card itself: the original sits at the backup's place with the same + // bytes, but it is the file being moved, not a backup of it, so it is kept + let base = temp_dir("backup-is-source"); + let (card, dest) = (base.join("card"), base.join("out")); + write_png(&card.join("a.png"), 9); + let mut s = session(); + let r = import_move(&mut s, &[&card], &dest, json!({"organize": "flat", "backup": card.to_string_lossy()})); + assert_eq!(len(&r, "imported"), 1, "{r}"); + assert_eq!(len(&r, "backups"), 0, "{r}"); + assert!(r["backupFailed"][0]["reason"].as_str().unwrap().contains("the file being imported"), "{r}"); + assert_eq!(len(&r, "moved"), 0, "{r}"); + assert!(card.join("a.png").is_file(), "the original stays: {r}"); + let _ = std::fs::remove_dir_all(&base); + + let base = temp_dir("backup-taken"); + let (card, dest, backup) = (base.join("card"), base.join("out"), base.join("bk")); + write_png(&card.join("a.png"), 6); + write_png(&card.join("b.png"), 7); + std::fs::create_dir_all(&backup).unwrap(); + std::fs::write(backup.join("a.png"), b"another file").unwrap(); + std::fs::copy(card.join("b.png"), backup.join("b.png")).unwrap(); + let mut s = session(); + let r = s + .execute( + "library.import", + &json!({"paths": [card.to_string_lossy()], "mode": "copy", "destination": dest.to_string_lossy(), "backup": backup.to_string_lossy(), "organize": "flat"}), + ) + .unwrap(); + assert_eq!(len(&r, "imported"), 2, "{r}"); + assert_eq!(len(&r, "backups"), 1, "the identical file counts: {r}"); + assert_eq!(len(&r, "backupFailed"), 1, "{r}"); + assert!(r["backupFailed"][0]["reason"].as_str().unwrap().contains("different file"), "{r}"); + assert_eq!(std::fs::read(backup.join("a.png")).unwrap(), b"another file", "left as it was"); + assert_eq!(files_under(&backup), ["a.png", "b.png"], "no renamed backup"); + let _ = std::fs::remove_dir_all(&base); +} + +/// A backup folder is refused where it could not be honest: adding in place copies nothing, and a +/// folder that is the destination, or inside it, or holds it, could put the backup on the main +/// copies themselves and count it as made. +#[test] +fn a_backup_folder_that_cannot_be_a_backup_is_refused() { + let base = temp_dir("backup-refused"); + let (card, dest) = (base.join("card"), base.join("out")); + write_png(&card.join("a.png"), 8); + let mut s = session(); + let run = |s: &mut Session, mode: &str, backup: &Path| { + s.execute( + "library.import", + &json!({"paths": [card.to_string_lossy()], "mode": mode, "destination": dest.to_string_lossy(), "backup": backup.to_string_lossy()}), + ) + }; + assert!(run(&mut s, "add", &base.join("bk")).is_err()); + // (the last one goes through a folder that doesn't exist yet and back out of it, into the destination) + for b in [dest.clone(), dest.join("bk"), base.clone(), base.join("not-yet").join("..").join("out").join("bk")] { + let e = run(&mut s, "copy", &b).unwrap_err().to_string(); + assert!(e.contains("outside the destination"), "{}: {e}", b.display()); + } + assert_eq!(s.catalog.len(), 0); + assert_eq!(files_under(&card), ["a.png"]); + let _ = std::fs::remove_dir_all(&base); +} + +/// A backup folder inside the destination is refused however the two are spelled: here the +/// destination's first folder doesn't exist, and the backup reaches it through folders that do and +/// back out with `..`. On Windows the two then resolved to different forms of the drive (`C:\` and +/// `\?\C:\`) and passed as separate; letter case doesn't tell Windows folders apart either. +#[test] +fn a_backup_inside_a_destination_that_does_not_exist_yet_is_refused() { + use crate::import::{ImportMode, backup_folder_error}; + let tmp = std::env::temp_dir(); + let top = tmp.ancestors().last().unwrap().to_path_buf(); + let absent = format!("lc-not-there-{}", std::process::id()); + let dest = top.join(&absent).join("out"); + assert!(!top.join(&absent).exists()); + let up = tmp.components().count(); + let backup = (0..up).fold(tmp.clone(), |p, _| p.join("..")).join(&absent).join("out").join("bk"); + assert!(backup_folder_error(ImportMode::Copy, true, Some(&dest), &backup).is_some(), "{}", backup.display()); + // the same folder in other letter case: the same folder on Windows, another one elsewhere + let shouted = top.join(absent.to_uppercase()).join("OUT").join("bk"); + assert_eq!(backup_folder_error(ImportMode::Copy, true, Some(&dest), &shouted).is_some(), cfg!(windows), "{}", shouted.display()); + // a folder beside the destination is still a backup folder, also when it is named through it + assert!(backup_folder_error(ImportMode::Copy, true, Some(&dest), &top.join(&absent).join("bk")).is_none()); + let beside = dest.join("..").join("bk"); + assert!(backup_folder_error(ImportMode::Copy, true, Some(&dest), &beside).is_none(), "{}", beside.display()); +} + +/// A Move looks at the backup again before it removes the original: a backup made with the copy +/// and gone by the time the library is saved (a backup drive unplugged meanwhile) keeps the +/// original, as a backup that failed does. +#[test] +fn a_move_keeps_the_original_when_its_backup_is_gone_before_the_end() { + use crate::import::{ImportJob, ImportMode, ImportOptions, Organize, commit_prepared}; + let base = temp_dir("backup-gone"); + let (card, dest, backup) = (base.join("card"), base.join("out"), base.join("bk")); + write_png(&card.join("a.png"), 11); + let mut s = session(); + let opts = ImportOptions { + mode: ImportMode::Move, + destination: Some(dest.to_string_lossy().to_string()), + backup: Some(backup.to_string_lossy().to_string()), + organize: Organize::Flat, + ..Default::default() + }; + let mut job = ImportJob::new(&mut s, opts).unwrap(); + let prepared = job.prepare(&[card.to_string_lossy().to_string()], &std::sync::atomic::AtomicBool::new(false)); + assert!(backup.join("a.png").is_file(), "the backup was made with the copy"); + std::fs::remove_file(backup.join("a.png")).unwrap(); + let r = serde_json::to_value(commit_prepared(&mut s, &job.opts, job.now(), prepared).unwrap()).unwrap(); + assert_eq!(len(&r, "imported"), 1, "{r}"); + assert_eq!(len(&r, "moved"), 0, "{r}"); + assert!(r["kept"][0]["reason"].as_str().unwrap().contains("no backup copy"), "{r}"); + assert!(card.join("a.png").is_file(), "the original stays: {r}"); + let _ = std::fs::remove_dir_all(&base); +} diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index fa17d01a31..c8bab04803 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -92,11 +92,13 @@ fn import_tool_copies_with_a_folder_template() { file_dated_2026_01_14(&src.join("a.png")); let mut b = Headless::demo(); b.session.clock = Box::new(|| "2026-01-14T05:58:48".to_string()); - let args = - json!({"paths": [src.to_string_lossy()], "mode": "copy", "destination": dest.to_string_lossy(), "organize": "{date:%Y}/{date:%Y%m%d}"}); + let backup = base.join("backup"); + let args = json!({"paths": [src.to_string_lossy()], "mode": "copy", "destination": dest.to_string_lossy(), "organize": "{date:%Y}/{date:%Y%m%d}", + "backup": backup.to_string_lossy()}); let r = call_tool(&mut b, "import", &args); assert!(!r.is_error, "{r:?}"); assert!(dest.join("2026").join("20260114").join("a.png").is_file()); + assert!(backup.join("2026").join("20260114").join("a.png").is_file(), "the backup mirrors the destination"); let _ = std::fs::remove_dir_all(&base); } diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index a70359ba03..d3002a13dc 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -147,6 +147,7 @@ pub fn helper_tools(has_ui: bool) -> Vec { "album": {"type": "integer", "description": "Also add to this album id"}, "mode": {"type": "string", "enum": ["add", "copy", "move"], "description": "add (default) = reference the files in place; copy = copy them into `destination` (default: the library's Originals/); move = as copy, then each original and its XMP sidecars are removed from the source once the copy is verified and catalogued (duplicates and failures keep their sources; `kept` lists sources left in place and why; undo leaves the moved files at the destination)"}, "destination": {"type": "string", "description": "Copy or move: destination folder"}, + "backup": {"type": "string", "description": "Copy or move: also copy each file into this folder, under the same folders and name as in the destination, verified like the main copy (off when absent). `backups` lists the copies made; `backupFailed` lists photos imported without one and why (a move keeps their originals). Must be outside the destination"}, "organize": {"type": "string", "description": "Copy or move: folders inside the destination — date (YYYY/YYYY-MM-DD, default), month (YYYY/YYYY-MM), flat, or a folder template such as {date:%Y}/{date:%Y%m%d} (→ 2026/20260114; the template's / make the levels, tokens as for rename; relative, no ..). Dated by capture time, else the import time"}, "onDeleted": {"type": "string", "enum": ["restore", "skip", "fresh"], "description": "A file that is in Recently Deleted: restore (default) = bring the photo back with its edits (`restored` lists it; relinked to the file when its own is gone); skip = leave it there (the duplicate is reported with existingDeleted); fresh = delete the trashed record and import the file as a new photo"}, "rename": {"type": "string", "description": "Copy or move: file-name template, e.g. {date:%Y%m%d_%H%M%S}_{seq:3} (run_command photo.renameTokens lists the tags); the extension is kept"} @@ -686,7 +687,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult { return ToolResult::error(format!("no photos found in {paths:?}")); } let mut p = json!({"paths": files}); - for k in ["album", "mode", "destination", "organize", "rename", "onDeleted"] { + for k in ["album", "mode", "destination", "backup", "organize", "rename", "onDeleted"] { if let Some(v) = args.get(k).filter(|v| !v.is_null()) { p[k] = v.clone(); } diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index e871dc7d27..4420e045ee 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -87,6 +87,9 @@ pub struct ImportDialog { pub metadata_preset: String, /// Copy: raws are copied as DNG. pub dng: bool, + /// Copy or Move: a backup folder ("" = none) that gets a verified copy of each file, under the + /// same folders and name as in the destination (the `backup` param of `library.import`). + pub backup: String, /// Per candidate: the library already has it in Recently Deleted ([`ImportDialog::set_trashed`]). pub trashed: Vec, /// What to do with those: `restore` (the default: the photo comes back with its edits), `fresh` diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 2dc4adc3c9..58f3d8e7f7 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -253,6 +253,28 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { d.destination.clear(); } }); + // an optional second, verified copy of each file, mirroring the destination's folders and names + field(ui, "Backup to", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let t = Tokens::get(ui.ctx()); + let none = d.backup.trim().is_empty(); + let shown = if none { crate::i18n::tr("No backup copy").to_string() } else { d.backup.clone() }; + let r = ui.label(egui::RichText::new(shown).color(if none { t.text_dim } else { t.text_label })); + register(ui, "label:importBackup", r.rect); + if app.services.pick_folder.is_some() + && crate::widgets::text_button(ui, "importBackup", crate::i18n::tr("Choose…"), false) + .on_hover_text(crate::i18n::tr( + "Also copy each file to this folder (a backup drive or a network share), with the same folders and names as above", + )) + .clicked() + && let Some(f) = app.services.pick_folder.as_mut().and_then(|f| f()) + { + d.backup = f; + } + if !none && crate::widgets::text_button(ui, "importBackupClear", crate::i18n::tr("None"), false).clicked() { + d.backup.clear(); + } + }); field(ui, "Folders", |ui| { let opts = [ ("date", "By day (YYYY/YYYY-MM-DD)"), @@ -331,6 +353,10 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let t = Tokens::get(ui.ctx()); let r = ui.label(egui::RichText::new(crate::i18n::tr_format!("Example: {example}", example = example)).color(t.text_dim)); register(ui, "label:importExample", r.rect); + if let Some(b) = example_backup(app, d) { + let r = ui.label(egui::RichText::new(crate::i18n::tr_format!("Backup: {example}", example = b)).color(t.text_dim)); + register(ui, "label:importBackupExample", r.rect); + } ui.label( egui::RichText::new(crate::i18n::tr("Folders and {date} use the capture time; a photo without one uses today's date.")) .color(t.text_dim) @@ -643,6 +669,25 @@ pub const DEFAULT_FOLDER_TEMPLATE: &str = "{date:%Y}/{date:%Y%m%d}"; /// Where the first selected photo would be copied to (destination, folders, name), for the /// dialog's example line; `None` without a photo or with an unusable folder template. pub fn example_destination(app: &LightcraftApp, d: &ImportDialog) -> Option { + let root = if d.destination.trim().is_empty() { + app.session.library.as_ref().map_or_else(|| "Originals".to_string(), |l| l.dir.join("Originals").to_string_lossy().to_string()) + } else { + d.destination.trim().trim_end_matches(['/', '\\']).to_string() + }; + example_under(app, d, root) +} + +/// Where the backup of that photo would go: the same folders and name, in the backup folder. +pub fn example_backup(app: &LightcraftApp, d: &ImportDialog) -> Option { + let root = d.backup.trim().trim_end_matches(['/', '\\']); + if root.is_empty() { + return None; + } + example_under(app, d, root.to_string()) +} + +/// The first selected photo's folders and name as the import gives them, under `root`. +fn example_under(app: &LightcraftApp, d: &ImportDialog, root: String) -> Option { let c = d.candidates.iter().zip(&d.checked).enumerate().find(|(i, (_, on))| **on && d.importable(*i)).map(|(_, (c, _))| c)?; let organize = match d.organize_param().ok()? { Some(o) => lightcraft_engine::import::Organize::parse(&o)?, @@ -664,11 +709,6 @@ pub fn example_destination(app: &LightcraftApp, d: &ImportDialog) -> Option, undo0: usize, @@ -255,6 +258,9 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result if d.dng && !d.move_files { params["dng"] = json!(true); } + if !d.backup.trim().is_empty() { + params["backup"] = json!(d.backup.trim()); + } } // the params are checked before a new album is created, so a refused import leaves no album let mut check = params.clone(); @@ -383,6 +389,11 @@ fn commit_batch(app: &mut LightcraftApp, task: &mut ImportTask, prepared: lightc task.failed += len("failed"); task.moved += len("moved"); task.kept += len("kept"); + task.backed_up += len("backups"); + task.no_backup += len("backupFailed"); + for k in v["backupFailed"].as_array().into_iter().flatten() { + log::warn!("import: no backup copy of {}: {}", k["path"].as_str().unwrap_or(""), k["reason"].as_str().unwrap_or("")); + } task.warnings.extend(v["warnings"].as_array().into_iter().flatten().filter_map(|warning| serde_json::from_value(warning.clone()).ok())); for k in v["kept"].as_array().into_iter().flatten() { log::warn!("import: kept {}: {}", k["path"].as_str().unwrap_or(""), k["reason"].as_str().unwrap_or("")); @@ -531,6 +542,12 @@ fn import_summary(app: &LightcraftApp, task: &ImportTask) -> String { msg.push_str(&crate::i18n::tr_format!(" · {} original{} left at the source", task.kept, crate::i18n::plural_s(task.kept))); } } + if task.params["backup"].is_string() { + msg.push_str(&crate::i18n::tr_format!(" · {} backed up", task.backed_up)); + if task.no_backup > 0 { + msg.push_str(&crate::i18n::tr_format!(" · {} without a backup copy", task.no_backup)); + } + } if task.duplicates > 0 { msg.push_str(&crate::i18n::tr_format!(" · {} duplicate{} skipped", task.duplicates, crate::i18n::plural_s(task.duplicates))); let deleted = deleted_of(app, &task.existing).len(); diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index 45c2425992..6c54f6e014 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -4211,6 +4211,93 @@ fn import_copy_renames_into_destination() { let _ = std::fs::remove_dir_all(&base); } +/// Import dialog, Copy with **Backup to**: Choose… sets the backup folder, the import copies each +/// file there under the same name as in the destination, and the summary says how many were backed up. +#[test] +fn import_copy_with_a_backup_folder() { + let base = std::env::temp_dir().join(format!("lc-ui-import-backup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (src, dest, backup) = (base.join("card"), base.join("out"), base.join("backup")); + std::fs::create_dir_all(&src).unwrap(); + for i in 0..3u8 { + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[i * 50, 7, 9, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(src.join(format!("IMG_{i:02}.png")), png).unwrap(); + } + let backup_s = backup.to_string_lossy().to_string(); + let services = crate::Services { png: None, pick_folder: Some(Box::new(move || Some(backup_s.clone()))), ..Default::default() }; + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), services); + app.ui.view = crate::state::ViewMode::PhotoGrid; + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let t = Duration::from_secs(10); + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [src.to_string_lossy()]}}), t); + assert_eq!(r["result"]["scanning"], true, "{r}"); + h.settle(SETTLE); + h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. }))); + for id in ["button:importCopy", "button:importBackup"] { + let r = h.request("ui.clickWidget", json!({"id": id}), t); + assert_eq!(r["ok"], true, "{id}: {r}"); + } + if let Some(crate::state::Dialog::Import { opts }) = &mut h.app.ui.dialog { + assert_eq!(opts.backup, backup.to_string_lossy(), "Choose… sets the backup folder"); + opts.destination = dest.to_string_lossy().to_string(); + opts.organize = "flat".into(); + opts.rename = "Trip-{seq:2}".into(); + } else { + panic!("no import dialog"); + } + let r = h.request("ui.dialog.confirm", json!({}), t); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.import.is_none(), "finished"); + let names = |d: &std::path::Path| { + let mut v: Vec = std::fs::read_dir(d).unwrap().flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect(); + v.sort(); + v + }; + assert_eq!(names(&dest).len(), 3); + assert_eq!(names(&backup), names(&dest), "the backup has the destination's names"); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("3 backed up"), "{toast}"); + let _ = std::fs::remove_dir_all(&base); +} + +/// A backup folder inside the destination is refused when the import is confirmed, before the +/// dialog creates the new album it names: a refused import leaves no empty album behind. +#[test] +fn a_refused_backup_folder_creates_no_album() { + let base = std::env::temp_dir().join(format!("lc-ui-import-backup-refused-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (src, dest) = (base.join("card"), base.join("out")); + std::fs::create_dir_all(&src).unwrap(); + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[90, 7, 9, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(src.join("IMG_01.png"), png).unwrap(); + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), crate::Services::default()); + app.ui.view = crate::state::ViewMode::PhotoGrid; + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let t = Duration::from_secs(10); + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [src.to_string_lossy()]}}), t); + assert_eq!(r["result"]["scanning"], true, "{r}"); + h.settle(SETTLE); + h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. }))); + if let Some(crate::state::Dialog::Import { opts }) = &mut h.app.ui.dialog { + opts.set_transfer(true, false); + opts.destination = dest.to_string_lossy().to_string(); + opts.backup = dest.join("bk").to_string_lossy().to_string(); + opts.new_album = "Backup refused".into(); + } else { + panic!("no import dialog"); + } + let albums = h.app.session.catalog.albums().count(); + let r = h.request("ui.dialog.confirm", json!({}), t); + assert_eq!(r["ok"], false, "refused: {r}"); + assert!(r.to_string().contains("outside the destination"), "{r}"); + assert_eq!(h.app.session.catalog.albums().count(), albums, "no album was created"); + assert!(h.app.import.is_none(), "nothing started"); + let _ = std::fs::remove_dir_all(&base); +} + /// The instant this machine reads as the tests' clock time: an undated file takes the file's /// date in the host's zone, so a fixed epoch would file it on the day before west of UTC. fn filed_at() -> u64 { diff --git a/docs/feature-names.md b/docs/feature-names.md index 532d0f7bcf..f01a248b1f 100644 --- a/docs/feature-names.md +++ b/docs/feature-names.md @@ -13,3 +13,7 @@ All 17 shipped non-English catalogs contain the new labels. The normal CI, persp ## Regression coverage The standard-library-only `display_names` integration tests scan production Rust string literals for the retired display names and preserve explicit compatibility exceptions. They also test identifier, comment and raw-string handling. These focused checks do not replace application or visual testing. + +## Import backup copy + +The import dialog's option to copy each imported file to a second folder is labelled **Backup to**, and its parameter is `backup`. Both are ordinary descriptive words for what the option does: it keeps a backup copy. The label does not use another photo library's name for its version of this option. Checked 2026-11-27 against the naming standard's names list; no trademark search was run, since the label is plain descriptive wording. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 2057855476..f3d7cfb5c8 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -74,7 +74,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with a remembered 80–320 pt thumbnail-size slider (default 116, independent of the library grid), density-aware previews capped at 1024 px and retention limited to nearby cells; tiny sources are tried once per requested size bucket; renderable raws use a sharper render when the camera JPEG is undersized, retaining the JPEG for preview-only raws or an unavailable/failed render; the pre-import loupe and keyboard culling remain open under #2056; thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step; when a Copy rename sequence runs out, remaining files are reported as failed and earlier completed transfers stay accounted for. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`). An import (and a scan of a folder scanned before) checks that each file a scan already probed is as it was by asking the disk about up to 16 files at a time (an import batch's files, at most), not one after another (`stat_all`, `crates/engine/src/import/files.rs`), and looks up the sidecars of a batch's photos the same way (`sidecars_of`); on a network share each file was a round trip When the scan left something out, one line under the count says so: the folder walk stopped at its depth or entry limit (“Stopped at the scan limit: there may be more photos”), folders it could not read, and files in the folders that are not a supported photo type (XMP sidecars, which the import reads with their photos, and hidden files are never counted; a file named on its own is always tried); nothing is shown when nothing was left out. `library.importPreview` returns the same as `scanLimited` and `skipped` (`unreadable`, `unsupported`), 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-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-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`) | @@ -808,6 +808,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-27 | minor | LR-IMP-ADD-DIALOG / LR-IMP-MOVE: an optional backup folder (Backup to, `library.import` `backup`) gets a verified copy of each copied or moved file under the same folders and names as the destination; a move keeps the original of a photo whose backup failed; counts unchanged | | 2026-11-19 | minor | LR-EDIT-OPTICS-DEFRINGE: AI Defringe (beyond Lightroom), a user-installed defringe network with a cached per-photo correction; no model ships; status unchanged | | 2026-10-31 | patch | LR-FILT-RATING: = or ≤ no stars in the filter bar shows the unrated photos instead of every photo (#3417); status unchanged | | 2026-10-29 | minor | MENU-EDIT-SELECTBY: Edit → Select by lists each rating on its own (★ only … ★★★★★ only, `library.selectBy` with `ratingOp: eq`) after the "and higher" rows, beside Unrated (#3311); status unchanged (✅) |