From 5563a7461c3547610ae9191a5d1be4fdf3332825 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 20 Oct 2026 16:18:41 -0400 Subject: [PATCH 01/10] PERF-SIDECARS: an import skips sidecar probes in folders its listing shows have no .xmp The import and the Add Photos review keep each listed folder's .xmp names; the review hands its listing only to the import it starts, and a folder's names are trusted only while its time (read before listing, at least 2 s old) is unchanged. Files the review listed are not asked about with is_dir. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/import.rs | 7 + crates/engine/src/import/files.rs | 89 +---- crates/engine/src/import/job.rs | 56 +-- crates/engine/src/import/listed_folders.rs | 151 +++++++++ crates/engine/src/import/scan.rs | 36 +- .../engine/src/import/tests_listed_folders.rs | 318 ++++++++++++++++++ crates/engine/src/rename.rs | 4 + crates/engine/src/sync.rs | 6 +- crates/engine/src/sync/tests_listing.rs | 6 +- crates/engine/src/walk.rs | 40 ++- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs/import/scan.rs | 5 + crates/ui-egui/src/dialogs/import/task.rs | 16 +- crates/ui-egui/src/headless/tests.rs | 51 +++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/tests/drop_import.rs | 1 + crates/ui-egui/src/tests/scan_probes.rs | 1 + 17 files changed, 675 insertions(+), 115 deletions(-) create mode 100644 crates/engine/src/import/listed_folders.rs create mode 100644 crates/engine/src/import/tests_listed_folders.rs diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 96ce93d0c1..3879ee65f7 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -66,6 +66,13 @@ pub use types::{ OnDeleted, Organize, }; +mod listed_folders; +pub use listed_folders::ListedFolders; + +#[cfg(test)] +#[path = "import/tests_listed_folders.rs"] +mod tests_listed_folders; + #[cfg(test)] #[path = "import/tests_known.rs"] mod tests_known; diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index d6a9c6eea9..b7627ed6c2 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -114,14 +114,29 @@ pub fn expand_report(paths: &[String], skip: Option<&Path>, limits: crate::walk: /// ([`expand_report`], handing the listing of every folder that is walked to `note`, as /// [`expand_noting`] does.) -fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, mut note: Option) -> Expansion { +fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, note: Option) -> Expansion { + expand_report_knowing(paths, skip, limits, note, false, &|_| false) +} + +/// [`expand_report_noting`], taking the paths `known_file` says are files as files without asking the +/// disk (a review hands over thousands of them, and telling a file from a folder is a round trip +/// each on a network share). With `timed`, each folder's modification time goes to `note` too +/// ([`crate::walk::files_in_noting_timed`]). +pub(super) fn expand_report_knowing( + paths: &[String], + skip: Option<&Path>, + limits: crate::walk::Limits, + mut note: Option, + timed: bool, + known_file: &dyn Fn(&Path) -> bool, +) -> Expansion { let mut out = Expansion::default(); for p in paths { let p = Path::new(p); if skip.is_some_and(|s| p == s) { continue; } - if p.is_dir() { + if !known_file(p) && p.is_dir() { // XMP sidecars are read with their photos, not skipped: they are left out of the count let mut sidecars = 0usize; let keep = |f: &Path| { @@ -132,6 +147,7 @@ fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::wa keep }; let w = match note.as_mut() { + Some(note) if timed => crate::walk::files_in_noting_timed(p, skip, limits, keep, &mut **note), Some(note) => crate::walk::files_in_noting(p, skip, limits, keep, &mut **note), None => crate::walk::files_in(p, skip, limits, keep), }; @@ -432,17 +448,6 @@ pub(crate) fn stat_all(paths: &[&str], cancel: &std::sync::atomic::AtomicBool, s at_once(paths, cancel, |p| stat(p)).into_iter().map(|s| s.unwrap_or(Seen::Unchecked)).collect() } -/// The sidecar of each of `files` (`find` says which: a few names looked up on the disk for each, -/// a round trip apiece on a network share), several files at once ([`at_once`]); `None` for a -/// file with no sidecar or not reached once `cancel` is set. -pub(super) fn sidecars_of( - files: &[&str], - cancel: &std::sync::atomic::AtomicBool, - find: impl Fn(&str) -> Option + Sync, -) -> Vec> { - at_once(files, cancel, |f| find(f)).into_iter().map(Option::flatten).collect() -} - /// The probes in `cache` of `files` that are still true: the file is looked at ([`stat_all`]) and /// `ok` says it is as it was probed. `None` for a file with no probe in `cache`, one that changed, /// and one not looked at because `cancel` was set. @@ -734,62 +739,4 @@ mod prepared_tests { assert_eq!(prepared.items.len(), 4); let _ = std::fs::remove_dir_all(&dir); } - - /// Given photos on a network share, when an import looks for their sidecars, then it asks about - /// several photos at once: one photo after another, nine names each, they were 77 % of the - /// import's preparation (95 % where a folder listing could not vouch for the names). - #[test] - fn sidecars_are_looked_up_for_several_photos_at_once() { - use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; - let (active, together) = (AtomicUsize::new(0), AtomicUsize::new(0)); - let names: Vec = (0..6).map(|i| format!("photo-{i}.jpg")).collect(); - let files: Vec<&str> = names.iter().map(String::as_str).collect(); - let found = sidecars_of(&files, &std::sync::atomic::AtomicBool::new(false), |f| { - active.fetch_add(1, Relaxed); - let end = std::time::Instant::now() + std::time::Duration::from_secs(1); - while active.load(Relaxed) < 2 && std::time::Instant::now() < end { - std::thread::yield_now(); - } - together.fetch_max(active.load(Relaxed), Relaxed); - active.fetch_sub(1, Relaxed); - f.ends_with("-3.jpg").then(|| PathBuf::from(f).with_extension("xmp")) - }); - assert!(together.load(Relaxed) >= 2, "the photos were looked up one at a time"); - let expect: Vec> = (0..6).map(|i| (i == 3).then(|| PathBuf::from("photo-3.xmp"))).collect(); - assert_eq!(found, expect, "each sidecar stays with its photo"); - } - - /// The sidecars found for a batch go to the photos they belong to, whichever have one, and a - /// photo that failed to probe takes none of the others'. - #[test] - fn a_batchs_sidecars_go_to_their_own_photos() { - let dir = std::env::temp_dir().join(format!("lightcraft-sidecars-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let xmp = r#""#; - let files: Vec = ["a.jpg", "broken.jpg", "c.jpg", "d.jpg"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect(); - for f in &files { - std::fs::write(f, b"x").unwrap(); - } - std::fs::write(dir.join("c.xmp"), xmp).unwrap(); - let mut s = Session::new(); - let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap(); - job.probe = Some(std::sync::Arc::new(|p: &str| { - if p.ends_with("broken.jpg") { - Err("unreadable".into()) - } else { - Ok(ProbeInfo { format: "JPEG".into(), file_size: 1, ..ProbeInfo::default() }) - } - })); - let prepared = job.prepare_files(files, &std::sync::atomic::AtomicBool::new(false)); - let rating = |name: &str| { - prepared.items.iter().find_map(|i| match i { - PreparedItem::Ready(r) if r.path.ends_with(name) => Some(r.sidecar.as_ref().and_then(|sc| sc.rating)), - _ => None, - }) - }; - assert_eq!((rating("a.jpg"), rating("c.jpg"), rating("d.jpg")), (Some(None), Some(Some(4)), Some(None))); - assert!(prepared.items.iter().any(|i| matches!(i, PreparedItem::Failed(p, _) if p.ends_with("broken.jpg")))); - let _ = std::fs::remove_dir_all(&dir); - } } diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index ca906c6192..fb2147ee7e 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -1,7 +1,7 @@ use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock}; -use super::files::{Seen, expand, probe_all, reusable_probes, sidecars_of}; +use super::files::{Seen, expand, probe_all, reusable_probes}; use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted}; -use super::{HashMap, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; +use super::{HashMap, ListedFolders, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; /// Import files/folders. See the module docs. pub fn import(s: &mut Session, paths: &[String], mode: ImportMode) -> crate::Result { @@ -46,6 +46,8 @@ pub struct ImportJob { /// Probes from a preceding scan (not read again). pub(super) cache: HashMap, naming: crate::sidecar::SidecarNaming, + /// The `.xmp` names in the folders [`ImportJob::expand`] listed. + listed: ListedFolders, now: String, /// Next rename number; `None` once the final representable value has been reserved. seq: Option, @@ -198,6 +200,7 @@ impl ImportJob { file_bytes: s.media.file_bytes.clone(), cache: std::mem::take(&mut s.import_probes), naming: s.xmp.naming, + listed: ListedFolders::default(), now: (s.clock)(), total: Default::default(), done: Default::default(), @@ -215,10 +218,33 @@ impl ImportJob { self.prepare_files(files, cancel) } + /// Hand the job the folders the review that started it listed ([`ScanOutput::listed`]). + #[must_use] + pub fn with_listed(mut self, listed: ListedFolders) -> Self { + self.listed = listed; + self + } + /// Expand `paths` (folders recursively, the library's own folder skipped) into the files an /// import would handle; counted in [`ImportJob::total`]. - pub fn expand(&self, paths: &[String]) -> Vec { - let files = expand(paths, self.lib_dir.as_deref()); + pub fn expand(&mut self, paths: &[String]) -> Vec { + // (a file the review listed is a file: no round trip to a share to ask) + let mut listed = std::mem::take(&mut self.listed); + let mut walked = ListedFolders::default(); + let (files, _) = expand_knowing( + paths, + self.lib_dir.as_deref(), + crate::walk::Limits::default(), + Some(&mut |dir, names, complete, modified| { + walked.note(dir, names, complete, modified); + true + }), + true, + &|p| listed.is_known_file(p), + ); + listed.absorb(walked); + listed.forget_files(); + self.listed = listed; self.total.fetch_add(files.len(), std::sync::atomic::Ordering::Relaxed); files } @@ -254,6 +280,7 @@ impl ImportJob { use std::sync::atomic::Ordering::Relaxed; // the library as it was, kept for the ownership of the shared stem sidecars below let library = self.look_up_library(); + self.listed.new_batch(); let opts = self.opts.clone(); let mode = self.mode; let mut out = Prepared { scanned: files.len(), items: Vec::new() }; @@ -295,20 +322,6 @@ impl ImportJob { library.as_ref(), todo.iter().zip(&probed).filter_map(|(path, info)| info.as_ref().ok().map(|i| (path.as_str(), i.kind))), ); - // The sidecar of every file that was probed, looked up for the batch at once: each is a few - // names asked of the disk, which on a network share made a folder of thousands of photos wait - // a round trip per name, one name after another. - let asked: Vec<&str> = todo.iter().zip(&probed).filter(|(_, p)| p.is_ok()).map(|(f, _)| f.as_str()).collect(); - // (a file whose content the library has is skipped below as a duplicate: it asks the disk nothing) - let known: std::collections::HashSet<&str> = todo - .iter() - .zip(&probed) - .filter(|(_, p)| !opts.local && 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 = - sidecars_of(&asked, cancel, |f| if known.contains(f) { None } else { crate::sidecar::find_sidecar_for_import(&stems, self.naming, f) }) - .into_iter(); // Files are planned one by one, in order (duplicates, sidecars, names, folders); their // copies or moves — the slow part, reading and writing every byte and verifying it — are // collected and run on several threads (issue #367), then their outcomes take their places. @@ -326,8 +339,6 @@ impl ImportJob { continue; } }; - // (this file's place in the lookups above: files that failed to probe have none) - let found_sidecar = found.next().flatten(); // a copy of a file whose transfer is still pending: a duplicate only if that one succeeds if !opts.local && let Some(h) = &info.content_hash @@ -347,7 +358,10 @@ impl ImportJob { let packet = if duplicate_of.is_some() && info.captured.is_some() { None } else { - found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).or_else(|| info.xmp.clone().filter(|_| raw)) + self.listed + .find_for_import(&stems, self.naming, &path) + .and_then(|f| std::fs::read_to_string(f).ok()) + .or_else(|| info.xmp.clone().filter(|_| raw)) }; let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { diff --git a/crates/engine/src/import/listed_folders.rs b/crates/engine/src/import/listed_folders.rs new file mode 100644 index 0000000000..d1b30e206e --- /dev/null +++ b/crates/engine/src/import/listed_folders.rs @@ -0,0 +1,151 @@ +//! What an import (or the review before it) learned of the folders it listed: the files in them +//! and the `.xmp` names. +//! +//! Looking for a photo's sidecar asks the disk about up to nine names ([`sidecar_candidates`]). +//! On a network share a name that is not there costs a round trip as much as one that is, so a +//! folder with no `.xmp` at all cost nine for each of its photos. Telling a file from a folder +//! (`is_dir`) is a round trip too, for each of the thousands of files a review hands over. The +//! listing that found those files already has both answers. +use std::collections::{HashMap, HashSet}; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::SystemTime; + +use crate::sidecar::{SidecarNaming, find_sidecar, sidecar_candidates}; +use crate::walk::EntryKind; + +/// One listed folder. +#[derive(Debug, Default)] +struct Folder { + /// The names listed as files (links are not: the disk says where they lead). + files: HashSet, + /// The `.xmp` names, lower-cased. Only for a folder that was listed completely, with plain + /// ASCII names (the names a file system treats alike in other cases are the ones we can fold + /// ourselves): for any other the disk decides, as before. + xmp: Option>, + /// The folder's modification time when it was listed: a file added or removed since changes + /// it, and the `.xmp` names are then not trusted (a listing taken by a review can be hours old). + modified: Option, +} + +/// The folders listed so far (see the module docs). The review's scan hands its listing to the +/// import that review starts ([`crate::import::ImportJob::with_listed`]), and nowhere else. +/// The `.xmp` names of a folder are trusted only while its modification time is what it was +/// when it was listed (looked at once per folder per batch: [`ListedFolders::new_batch`]); a +/// volume whose folders keep no usable time (it can't be read) is probed as before. +#[derive(Debug, Default)] +pub struct ListedFolders { + folders: HashMap, + /// folder → whether its time is still the listed one, for the batch being handled. + checked: Mutex>, + /// How often the disk was asked after all about a sidecar (for the tests). + pub(crate) asked: AtomicUsize, + /// How many folders' times were looked at (for the tests). + pub(crate) looked: AtomicUsize, +} + +impl ListedFolders { + /// Take the listing of `folder` from the walk ([`crate::walk::files_in_noting`]), with the + /// folder's time as the walk read it before listing (`None`: too recent to vouch for, or unreadable). + pub(crate) fn note(&mut self, folder: &Path, entries: Vec<(OsString, EntryKind)>, complete: bool, modified: Option) { + let mut listed = Folder { modified, ..Default::default() }; + let mut xmp = (complete && listed.modified.is_some()).then(HashSet::new); + for (name, kind) in entries { + // (a name that is no text is not one a path can be compared with) + let Some(name) = name.to_str() else { + xmp = None; + continue; + }; + if let Some(set) = &mut xmp { + if name.is_ascii() { + let lower = name.to_ascii_lowercase(); + if lower.ends_with(".xmp") { + set.insert(lower); + } + } else { + // (not ours to say what another name's other case is) + xmp = None; + } + } + if kind == EntryKind::File && crate::import::is_supported(Path::new(name)) { + listed.files.insert(name.to_string()); + } + } + listed.xmp = xmp; + self.folders.insert(folder.to_path_buf(), listed); + } + + /// A new batch of files is handled: look at the folders' times again. + pub(crate) fn new_batch(&self) { + self.checked.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } + + /// The names of files are needed to take a path for a file (once the files are expanded, no more). + pub(crate) fn forget_files(&mut self) { + for f in self.folders.values_mut() { + f.files = HashSet::new(); + } + } + + /// Whether `dir` is as it was listed. + fn unchanged(&self, dir: &Path, listed: Option) -> bool { + let mut checked = self.checked.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(known) = checked.get(dir) { + return *known; + } + self.looked.fetch_add(1, Ordering::Relaxed); + let now = std::fs::metadata(dir).and_then(|m| m.modified()).ok(); + let same = now.is_some() && now == listed; + checked.insert(dir.to_path_buf(), same); + same + } + + /// Take over `walked`'s folders, which are newer than the ones held for them. + pub(crate) fn absorb(&mut self, walked: ListedFolders) { + self.folders.extend(walked.folders); + } + + /// Whether a listing says `path` is a file, as it was found: the disk need not be asked. + pub(crate) fn is_known_file(&self, path: &Path) -> bool { + let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else { return false }; + // (the path ends in that name: no `/.` or separator after it, which the disk would resolve) + path.to_str().is_some_and(|p| p.ends_with(name)) && self.folders.get(dir).is_some_and(|f| f.files.contains(name)) + } + + /// Whether the listing of `original`'s folder shows that none of its sidecar names is there. + /// `false` where it can't say: the folder was not listed (or not completely), or a name is + /// one the disk may resolve another way. + fn rules_out(&self, original: &str, naming: SidecarNaming) -> bool { + let path = Path::new(original); + let Some(dir) = path.parent() else { return false }; + let Some((xmp, modified)) = self.folders.get(dir).and_then(|f| Some((f.xmp.as_ref()?, f.modified))) else { return false }; + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false }; + if !original.ends_with(name) || crate::sync::asks_the_disk(name) || !crate::sync::plain_name(name) || !self.unchanged(dir, modified) { + return false; + } + sidecar_candidates(original, naming) + .all(|c| c.file_name().and_then(|n| n.to_str()).is_some_and(|n| crate::sync::plain_name(n) && !xmp.contains(&n.to_ascii_lowercase()))) + } + + /// [`crate::sidecar::find_sidecar_for_import`], without asking the disk where the listing shows + /// there is none: a file that owns its stem sidecar ([`crate::sidecar::ImportStems`]) is looked + /// up as [`ListedFolders::find`] does; one that doesn't reads only its own `.xmp`. + pub(crate) fn find_for_import(&self, stems: &crate::sidecar::ImportStems, naming: SidecarNaming, original: &str) -> Option { + if stems.owns(original) { + return self.find(original, naming); + } + self.asked.fetch_add(1, Ordering::Relaxed); + crate::sidecar::find_sidecar_for_import(stems, naming, original) + } + + /// [`find_sidecar`], without asking the disk where the listing shows there is none. + pub(crate) fn find(&self, original: &str, naming: SidecarNaming) -> Option { + if self.rules_out(original, naming) { + return None; + } + self.asked.fetch_add(1, Ordering::Relaxed); + find_sidecar(original, naming) + } +} diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index aaae16c7a4..9e0e5a4154 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -1,6 +1,6 @@ -use super::files::{Seen, expand, expand_report, is_supported, probe_all, reusable_probes}; +use super::files::{Seen, expand, expand_report_knowing, is_supported, probe_all, reusable_probes}; use super::types::ImportCandidate; -use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; +use super::{HashMap, ListedFolders, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; /// What a [`scan`] needs from the session, so it can run on another thread (a folder on a network /// share can take minutes to read). @@ -12,6 +12,8 @@ pub struct ScanInput { /// ([`library_hashes`]), on the scan's thread. library: std::sync::Arc, cache: HashMap, + /// The folders the scan listed, for the import that follows. + listed: ListedFolders, } /// The library's photos of `files`: path → (photo, its summary as a candidate that is there @@ -83,6 +85,8 @@ pub struct ScanOutput { pub unreadable: usize, /// Files inside the folders that are not a supported photo type (XMP sidecars not counted). pub unsupported: usize, + /// The folders the scan listed (kept with the probes, for the import that follows). + pub listed: ListedFolders, } impl ScanInput { @@ -91,7 +95,13 @@ impl ScanInput { // (no table of the library here: this is the session's thread, and the library may hold // millions of photos. The scan looks up what it finds) let library = std::sync::Arc::new(s.catalog.clone()); - let input = ScanInput { probe: s.media.file_probe.clone(), skip, library, cache: std::mem::take(&mut s.import_probes) }; + let input = ScanInput { + probe: s.media.file_probe.clone(), + skip, + library, + cache: std::mem::take(&mut s.import_probes), + listed: ListedFolders::default(), + }; (input, paths.to_vec()) } @@ -303,8 +313,20 @@ pub fn scan_report(s: &mut Session, paths: &[String]) -> ScanOutput { /// [`scan`] without the session, so it can run on a worker thread. Stops early (returning what it /// has) when `progress.cancel` is set. -pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput { - let expansion = expand_report(paths, input.skip.as_deref(), crate::walk::Limits::default()); +pub fn scan_with(mut input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput { + let listed = &mut input.listed; + let expansion = expand_report_knowing( + paths, + input.skip.as_deref(), + crate::walk::Limits::default(), + // (the walk goes on: only a scan that is cancelled ends it early) + Some(&mut |dir, names, complete, modified| { + listed.note(dir, names, complete, modified); + true + }), + true, + &|_| false, + ); let mut out = scan_files(input, expansion.files, progress); out.truncated = expansion.truncated; out.unreadable = expansion.unreadable; @@ -314,7 +336,7 @@ pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> /// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]). The walks' /// diagnostics ([`ScanOutput::truncated`] and friends) are left empty: who expanded the paths has -/// them ([`expand_report`]). +/// them ([`expand_report`](super::files::expand_report)). pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &ScanProgress) -> ScanOutput { use std::sync::atomic::Ordering::Relaxed; let by_path = library_files(&input.library, &files); @@ -376,5 +398,5 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc out.push(c); } // (the walks' diagnostics are [`scan_with`]'s: these files were found already) - ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0 } + ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0, listed: input.listed } } diff --git a/crates/engine/src/import/tests_listed_folders.rs b/crates/engine/src/import/tests_listed_folders.rs new file mode 100644 index 0000000000..18e1179963 --- /dev/null +++ b/crates/engine/src/import/tests_listed_folders.rs @@ -0,0 +1,318 @@ +//! An import asks the disk for a photo's sidecar only where the folder's listing leaves room for +//! one: on a network share every name asked about is a round trip, found or not. +use super::*; +use crate::sidecar::SidecarNaming; +use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; + +fn scratch(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-listed-sidecars-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Make `dir` and the folders in it an hour old, so the walk vouches for their times +/// (`walk::TIME_GRAIN`, two seconds) without the test waiting. +fn settle(dir: &Path) { + let hour_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(3600); + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + if e.file_type().is_ok_and(|t| t.is_dir()) { + settle(&e.path()); + } + } + set_folder_time(dir, hour_ago); +} + +/// Set a folder's modification time (Unix: a plain handle; Windows: one opened for attributes, +/// with backup semantics, which is how a folder is opened there). +fn set_folder_time(dir: &Path, at: std::time::SystemTime) { + #[cfg(windows)] + let handle = { + use std::os::windows::fs::OpenOptionsExt; + // FILE_WRITE_ATTRIBUTES, FILE_FLAG_BACKUP_SEMANTICS + std::fs::OpenOptions::new().write(true).access_mode(0x100).custom_flags(0x0200_0000).open(dir) + }; + #[cfg(not(windows))] + let handle = std::fs::File::open(dir); + handle.unwrap().set_modified(at).unwrap(); +} + +fn modified(dir: &Path) -> Option { + std::fs::metadata(dir).and_then(|m| m.modified()).ok() +} + +fn xmp(rating: u8) -> String { + format!( + r#" +"# + ) +} + +/// An import of files that are not read (the probe says "a JPEG") with the naming `naming`. +fn job(naming: SidecarNaming) -> ImportJob { + let mut s = Session::new(); + let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap(); + job.naming = naming; + job.probe = Some(std::sync::Arc::new(|_: &str| Ok(ProbeInfo { format: "JPEG".into(), ..ProbeInfo::default() }))); + job +} + +/// (file name → the rating its sidecar gave, `None`: no sidecar) in the order imported. +fn ratings(p: Prepared) -> Vec<(String, Option)> { + p.items + .into_iter() + .map(|i| match i { + PreparedItem::Ready(r) => (Path::new(&r.path).file_name().unwrap().to_string_lossy().to_string(), r.sidecar.and_then(|sc| sc.rating)), + other => panic!("not ready: {other:?}"), + }) + .collect() +} + +/// Given folders listed completely that hold no `.xmp`, when their files are imported, then no +/// sidecar name is asked of the disk (it was nine names for every file); and files named one by +/// one, whose folders nobody listed, are asked about as before. +#[test] +fn a_listed_folder_without_sidecars_is_not_asked_about_them() { + let root = scratch("none"); + let mut named = Vec::new(); + for folder in 0..50 { + let dir = root.join(format!("f{folder:02}")); + std::fs::create_dir_all(&dir).unwrap(); + for n in 0..20 { + let f = dir.join(format!("IMG_{n:04}.jpg")); + std::fs::write(&f, b"x").unwrap(); + named.push(f.to_string_lossy().to_string()); + } + } + settle(&root); + let cancel = AtomicBool::new(false); + + let mut listed = job(SidecarNaming::Stem); + let p = listed.prepare(&[root.to_string_lossy().to_string()], &cancel); + assert_eq!(p.items.len(), 1000); + assert_eq!(listed.listed.asked.load(Relaxed), 0, "1,000 files in 50 listed folders: no disk probe"); + + let mut by_name = job(SidecarNaming::Stem); + let p = by_name.prepare(&named, &cancel); + assert_eq!(p.items.len(), 1000); + assert_eq!(by_name.listed.asked.load(Relaxed), 1000, "files named directly keep their disk probes"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given sidecars in every case and naming, when the folder is imported, then each is read, and +/// only the photo without one is not asked about. +#[test] +fn sidecars_in_the_listing_are_read_in_any_case() { + for naming in [SidecarNaming::Stem, SidecarNaming::Full] { + let root = scratch("cases"); + let write = |name: &str, rating: u8| std::fs::write(root.join(name), xmp(rating)).unwrap(); + for p in ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg"] { + std::fs::write(root.join(p), b"x").unwrap(); + } + write("a.xmp", 1); + write("b.XMP", 2); + write("c.Xmp", 3); + write("d.jpg.xmp", 4); + write("e.JPG.XMP", 5); + settle(&root); + let mut job = job(naming); + let found = ratings(job.prepare(&[root.to_string_lossy().to_string()], &AtomicBool::new(false))); + let expect: Vec<(String, Option)> = + [("a.jpg", Some(1)), ("b.jpg", Some(2)), ("c.jpg", Some(3)), ("d.jpg", Some(4)), ("e.jpg", Some(5)), ("f.jpg", None)] + .into_iter() + .map(|(n, r)| (n.to_string(), r)) + .collect(); + let mut found = found; + found.sort(); + assert_eq!(found, expect, "{naming:?}"); + assert_eq!(job.listed.asked.load(Relaxed), 5, "{naming:?}: the five with a sidecar are asked about, f.jpg is not"); + let _ = std::fs::remove_dir_all(&root); + } +} + +/// A folder the walk did not list completely, or whose names the listing can't compare as the +/// disk does (not ASCII), is not trusted: its photos are asked about as before. +#[test] +fn a_listing_that_cannot_say_leaves_the_disk_to_decide() { + let root = scratch("cannot-say"); + let (whole, partial, accents) = (root.join("whole"), root.join("partial"), root.join("accents")); + for d in [&whole, &partial, &accents] { + std::fs::create_dir_all(d).unwrap(); + } + let in_ = |d: &Path, n: &str| d.join(n).to_string_lossy().to_string(); + let mut l = listed_folders::ListedFolders::default(); + let file = |n: &str| (std::ffi::OsString::from(n), crate::walk::EntryKind::File); + l.note(&partial, vec![file("a.jpg")], false, modified(&partial)); + l.note(&accents, vec![file("é.jpg"), file("a.jpg")], true, modified(&accents)); + l.note(&whole, vec![file("a.jpg"), file("b.xmp")], true, modified(&whole)); + let naming = SidecarNaming::Stem; + // (a folder that is not on disk any more has no time to compare: asked about, too) + l.note(Path::new("/p/gone"), vec![file("a.jpg")], true, Some(std::time::SystemTime::UNIX_EPOCH)); + // (a folder too recent to vouch for, as the walk reports it: no time) + let recent = root.join("recent"); + std::fs::create_dir_all(&recent).unwrap(); + l.note(&recent, vec![file("a.jpg")], true, None); + let cases = [ + in_(&partial, "a.jpg"), + in_(&accents, "a.jpg"), + in_(&root.join("unlisted"), "a.jpg"), + in_(&whole, "b.jpg"), + in_(&whole, "a~1.jpg"), + in_(&whole, "nul.jpg"), + "/p/gone/a.jpg".to_string(), + in_(&recent, "a.jpg"), + ]; + for original in &cases { + let before = l.asked.load(Relaxed); + assert!(l.find(original, naming).is_none()); + assert_eq!(l.asked.load(Relaxed), before + 1, "{original}: the disk is asked"); + } + let before = l.asked.load(Relaxed); + assert!(l.find(&in_(&whole, "a.jpg"), naming).is_none()); + assert_eq!(l.asked.load(Relaxed), before, "a listed folder with no a.xmp: the disk is not asked"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given a review (the scan before the Add Photos dialog) of folders without sidecars, and an +/// import of the files it listed, when the files are handled, then neither a sidecar name nor +/// "is it a folder" is asked of the disk for them; and the sidecar the review's listing shows is +/// read. +#[test] +fn an_import_after_a_review_trusts_the_folders_the_review_listed() { + let root = scratch("review"); + for folder in 0..20 { + let dir = root.join(format!("f{folder:02}")); + std::fs::create_dir_all(&dir).unwrap(); + for n in 0..10 { + std::fs::write(dir.join(format!("IMG_{n:04}.jpg")), b"x").unwrap(); + } + } + std::fs::write(root.join("f07").join("IMG_0003.xmp"), xmp(4)).unwrap(); + settle(&root); + let mut s = Session::new(); + s.media.file_probe = Some(std::sync::Arc::new(|_: &str| Ok(ProbeInfo { format: "JPEG".into(), file_size: 1, ..ProbeInfo::default() }))); + let (input, paths) = ScanInput::new(&mut s, &[root.to_string_lossy().to_string()]); + let out = scan_with(input, &paths, &ScanProgress::default()); + let selected: Vec = out.candidates.iter().map(|c| c.path.clone()).collect(); + assert_eq!(selected.len(), 200); + // (what the app does with the scan's output) + s.import_probes = out.probes; + let listed = out.listed; + + let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap().with_listed(listed); + let p = job.prepare(&selected, &AtomicBool::new(false)); + assert_eq!(job.listed.asked.load(Relaxed), 1, "only the photo with a sidecar in the listing is asked about"); + let found = ratings(p); + assert_eq!(found.len(), 200); + assert_eq!(found.iter().filter(|(_, r)| r.is_some()).collect::>(), [&("IMG_0003.jpg".to_string(), Some(4))]); + let _ = std::fs::remove_dir_all(&root); +} + +/// A path the listing calls a file is not asked about (here the disk holds a folder by that +/// name, which only a look at the disk would find); one it does not list still is. +#[test] +fn a_file_the_listing_does_not_know_is_still_checked() { + let root = scratch("known"); + for name in ["known.jpg", "unknown.jpg"] { + std::fs::create_dir_all(root.join(name)).unwrap(); + std::fs::write(root.join(name).join("inner.jpg"), b"x").unwrap(); + } + let mut job = job(SidecarNaming::Stem); + job.listed.note(&root, vec![("known.jpg".into(), crate::walk::EntryKind::File)], true, None); + let (known, unknown) = (root.join("known.jpg"), root.join("unknown.jpg")); + let files = job.expand(&[known.to_string_lossy().to_string(), unknown.to_string_lossy().to_string()]); + assert_eq!(files, [known.to_string_lossy().to_string(), unknown.join("inner.jpg").to_string_lossy().to_string()]); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given a review whose listing was kept, when a sidecar appears in a folder afterwards (the +/// review was left open, or cancelled, and something else added it), then the import that gets +/// the listing still reads it: a folder that changed since it was listed is probed. +#[test] +fn a_folder_that_changed_since_it_was_listed_is_probed() { + let root = scratch("stale"); + for n in 0..3 { + std::fs::write(root.join(format!("a{n}.jpg")), b"x").unwrap(); + } + settle(&root); + let mut walked = ListedFolders::default(); + let (files, _) = expand_knowing( + &[root.to_string_lossy().to_string()], + None, + crate::walk::Limits::default(), + Some(&mut |dir, names, complete, modified| { + walked.note(dir, names, complete, modified); + true + }), + true, + &|_| false, + ); + assert_eq!(files.len(), 3); + // a sidecar arrives, more than a clock tick after the listing + std::fs::write(root.join("a1.xmp"), xmp(5)).unwrap(); + let mut job = job(SidecarNaming::Stem).with_listed(walked); + let found = ratings(job.prepare_files(files, &AtomicBool::new(false))); + assert_eq!(found.iter().filter(|(_, r)| *r == Some(5)).count(), 1, "{found:?}"); + assert_eq!(job.listed.asked.load(Relaxed), 3, "the folder is asked about, photo by photo"); + let _ = std::fs::remove_dir_all(&root); +} + +/// A batch looks at the time of each folder its files are in, once: not once per file, and not +/// once per folder that was listed. +#[test] +fn a_batch_looks_at_each_of_its_folders_once() { + let root = scratch("looks"); + for folder in 0..50 { + let dir = root.join(format!("f{folder:02}")); + std::fs::create_dir_all(&dir).unwrap(); + for n in 0..20 { + std::fs::write(dir.join(format!("IMG_{n:04}.jpg")), b"x").unwrap(); + } + } + settle(&root); + let mut job = job(SidecarNaming::Stem); + let files = job.expand(&[root.to_string_lossy().to_string()]); + assert_eq!(files.len(), 1000); + let in_folders = |names: &[&str]| -> Vec { + files.iter().filter(|f| Path::new(f).parent().and_then(Path::file_name).is_some_and(|d| names.iter().any(|n| d == *n))).cloned().collect() + }; + let cancel = AtomicBool::new(false); + let first = job.prepare_files(in_folders(&["f00", "f01"]), &cancel); + assert_eq!(first.items.len(), 40); + assert_eq!(job.listed.looked.load(Relaxed), 2, "40 files in 2 of the 50 listed folders"); + job.prepare_files(in_folders(&["f01", "f02", "f03"]), &cancel); + assert_eq!(job.listed.looked.load(Relaxed), 2 + 3, "the next batch looks again, at its own 3"); + assert_eq!(job.listed.asked.load(Relaxed), 0); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given a folder listed in the same clock tick as its files were made, when a sidecar is +/// written into it right after the listing and the folder's time reads as it did before (a +/// volume that keeps folder times to the second or two), then the import still reads it: a +/// time too recent to vouch for is not trusted. (The test puts the folder's time back.) +#[test] +fn a_sidecar_written_in_the_tick_of_the_listing_is_read() { + let root = scratch("racy"); + for n in 0..3 { + std::fs::write(root.join(format!("a{n}.jpg")), b"x").unwrap(); + } + let at_listing = modified(&root).unwrap(); + let mut walked = ListedFolders::default(); + let (files, _) = expand_knowing( + &[root.to_string_lossy().to_string()], + None, + crate::walk::Limits::default(), + Some(&mut |dir, names, complete, modified| { + walked.note(dir, names, complete, modified); + true + }), + true, + &|_| false, + ); + std::fs::write(root.join("a1.xmp"), xmp(5)).unwrap(); + set_folder_time(&root, at_listing); + let mut job = job(SidecarNaming::Stem).with_listed(walked); + let found = ratings(job.prepare_files(files, &AtomicBool::new(false))); + assert_eq!(found.iter().filter(|(_, r)| *r == Some(5)).count(), 1, "{found:?}"); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index 8b165245b1..f1d06b3cd5 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -71,5 +71,9 @@ pub struct RenamePlan { pub to_path: Option, } +#[cfg(test)] +#[path = "rename/tests_listed_sources.rs"] +mod tests_listed_sources; + #[cfg(test)] pub(crate) mod tests; diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 6b09ed09f5..7ad8715a44 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -231,7 +231,7 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges { std::slice::from_ref(&folder), scan.skip(), crate::walk::Limits::default(), - Some(&mut |dir, names, complete| { + Some(&mut |dir, names, complete, _| { use std::sync::atomic::Ordering::Relaxed; progress.folders_listed.fetch_add(1, Relaxed); let files = names.iter().filter(|(_, kind)| *kind == crate::walk::EntryKind::File).count(); @@ -426,7 +426,7 @@ struct Listed { /// Whether the disk is asked about `name` whatever the listing holds: a name Windows takes for /// a device (`NUL`, `aux.jpg`: there in every folder, or not openable where it is listed). -fn asks_the_disk(name: &str) -> bool { +pub(crate) fn asks_the_disk(name: &str) -> bool { let stem = name.split('.').next().unwrap_or_default().trim_end_matches(' ').to_ascii_lowercase(); // (`COM` and `LPT` with any one digit, the superscript ones Windows also takes among them) let numbered = ["com", "lpt"].iter().any(|port| { @@ -439,7 +439,7 @@ fn asks_the_disk(name: &str) -> bool { /// Whether `name` can only be found under itself in some case: ASCII, and nothing in it that a /// file system resolves another way (a short name with `~`, a stream after `:`, dots or spaces /// at its end, which Windows drops). -fn plain_name(name: &str) -> bool { +pub(crate) fn plain_name(name: &str) -> bool { name.is_ascii() && !name.contains(['~', ':']) && !name.ends_with(['.', ' ']) && !name.is_empty() } diff --git a/crates/engine/src/sync/tests_listing.rs b/crates/engine/src/sync/tests_listing.rs index 099b5dd0f9..ff15069c7a 100644 --- a/crates/engine/src/sync/tests_listing.rs +++ b/crates/engine/src/sync/tests_listing.rs @@ -151,7 +151,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() { .collect(); // (`dir.jpg` is gone, though a sidecar of its name is there) let mut l = Listing::default(); - let walked = crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete| { + let walked = crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete, _| { l.note(d, names, complete); true }); @@ -174,7 +174,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() { l.asked.load(std::sync::atomic::Ordering::Relaxed) }; let mut with = Listing::default(); - crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete| { + crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete, _| { with.note(d, names, complete); true }); @@ -191,7 +191,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() { // a folder of plain names only: the disk is asked nothing at all let sub = dir.join("sub"); let mut only_plain = Listing::default(); - crate::walk::files_in_noting(&sub, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete| { + crate::walk::files_in_noting(&sub, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete, _| { only_plain.note(d, names, complete); true }); diff --git a/crates/engine/src/walk.rs b/crates/engine/src/walk.rs index f0c4033dd6..c3173968a5 100644 --- a/crates/engine/src/walk.rs +++ b/crates/engine/src/walk.rs @@ -94,9 +94,24 @@ pub enum EntryKind { /// What [`files_in_noting`] hands over for each folder it lists: the folder, the name and kind /// of every entry in it (hidden ones too), and whether that is all of them (not when the walk -/// stopped inside the folder, or an entry could not be read). It answers whether to go on: `false` -/// ends the walk there (a scan cancelled; [`Walked::truncated`] is left alone: who stopped it knows). -pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, EntryKind)>, bool) -> bool; +/// stopped inside the folder, or an entry could not be read), and the folder's modification time when the walk read +/// it and it was old enough to show a later change ([`files_in_noting_timed`]; else `None`). It answers whether to go +/// on: `false` ends the walk there (a scan cancelled; [`Walked::truncated`] is left alone: who stopped it knows). +pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, EntryKind)>, bool, Option) -> bool; + +/// How old a folder's modification time must be, when the folder is read, for a change after the +/// listing to show in it. File systems keep folder times in whole seconds (HFS+, ext3) or two +/// (FAT, and SMB1's DOS times): a file added in the same tick as the listing would leave the +/// time as it was. Two seconds is the coarsest of them (git's "racily clean" rule, for the same reason). +const TIME_GRAIN: std::time::Duration = std::time::Duration::from_secs(2); + +/// `dir`'s modification time, when it is old enough ([`TIME_GRAIN`]) that a change after now +/// would move it: read before the folder is listed, so nothing added during the listing hides. +fn settled_time(dir: &Path) -> Option { + let modified = std::fs::metadata(dir).and_then(|m| m.modified()).ok()?; + let now = std::time::SystemTime::now(); + modified.checked_add(TIME_GRAIN).filter(|t| *t <= now).map(|_| modified) +} /// The files below folder `root` that `keep` accepts. Hidden entries (names starting with `.`) /// are left out, the folder `skip` (e.g. the library's own) is never entered, and the walk stops @@ -123,7 +138,13 @@ pub fn files_in_entering( /// find its files has, with that, the answer to "is this name there" for everything in it, and /// need not ask the disk again (a round trip for each name on a network share). pub fn files_in_noting(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool, note: NoteFolder) -> Walked { - walk(root, skip, limits, keep, |_| true, Some(note)) + walk(root, skip, limits, keep, |_| true, Some((note, false))) +} + +/// [`files_in_noting`], also reading each folder's modification time (before it is listed; a round +/// trip on a network share) and handing it over when it is old enough to show a later change. +pub fn files_in_noting_timed(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool, note: NoteFolder) -> Walked { + walk(root, skip, limits, keep, |_| true, Some((note, true))) } fn walk( @@ -132,7 +153,7 @@ fn walk( limits: Limits, mut keep: impl FnMut(&Path) -> bool, mut enter: impl FnMut(&Path) -> bool, - mut note: Option, + mut note: Option<(NoteFolder, bool)>, ) -> Walked { let mut out = Walked::default(); // canonical folders reached through a link, so a link loop is walked at most once @@ -160,6 +181,7 @@ fn walk( out.truncated = true; continue; } + let modified = if note.as_ref().is_some_and(|n| n.1) { settled_time(&path) } else { None }; let Ok(rd) = std::fs::read_dir(&path) else { out.unreadable = out.unreadable.saturating_add(1); continue; @@ -227,8 +249,8 @@ fn walk( }; children.push((p, dir)); } - if let (Some(note), Some(listed)) = (note.as_mut(), listed) - && !note(&path, listed, complete) + if let (Some((note, _)), Some(listed)) = (note.as_mut(), listed) + && !note(&path, listed, complete, modified) { break; } @@ -292,7 +314,7 @@ mod tests { #[cfg(unix)] std::os::unix::fs::symlink(root.join("a.jpg"), root.join("link.jpg")).unwrap(); let mut noted: Vec<(PathBuf, Vec<(String, EntryKind)>, bool)> = Vec::new(); - let walked = files_in_noting(&root, None, Limits::default(), |_| true, &mut |dir, entries, complete| { + let walked = files_in_noting(&root, None, Limits::default(), |_| true, &mut |dir, entries, complete, _| { let mut entries: Vec<(String, EntryKind)> = entries.into_iter().map(|(n, k)| (n.to_string_lossy().to_string(), k)).collect(); entries.sort_by(|a, b| a.0.cmp(&b.0)); noted.push((dir.to_path_buf(), entries, complete)); @@ -308,7 +330,7 @@ mod tests { // stopped inside the first folder: its listing is not all of it let mut cut = Vec::new(); - let walked = files_in_noting(&root, None, Limits { max_depth: 8, max_entries: 2 }, |_| true, &mut |dir, entries, complete| { + let walked = files_in_noting(&root, None, Limits { max_depth: 8, max_entries: 2 }, |_| true, &mut |dir, entries, complete, _| { cut.push((dir.to_path_buf(), entries.len(), complete)); true }); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 74425972d8..caf344deb3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -113,6 +113,7 @@ impl LightcraftApp { scan: None, scans_stopping: Default::default(), waiting_import: Default::default(), + review_listed: None, sync: None, sync_owns_changes: false, sync_run: None, diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index f4d22079a4..e402fcbeed 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -239,12 +239,15 @@ pub fn browse(app: &mut LightcraftApp, path: &str, subfolders: Option) -> let candidates = queue.iter().cloned().map(|path| lightcraft_engine::import::ImportCandidate { path, ..Default::default() }).chain(known).collect(); // the probes of earlier scans go back to the session with the result, for the import that follows + // (a browse imports nothing from a review, so no folder listing goes with it) + let listed = lightcraft_engine::import::ListedFolders::default(); let _ = tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates, probes: input.take_probes(), truncated: false, unreadable: 0, unsupported: 0, + listed, })); }; #[cfg(not(target_arch = "wasm32"))] @@ -341,6 +344,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { if cancelled { return; } + app.review_listed = None; if task.browse { // the folder and the ones its photos are in count as browsed now, as `library.browse` records them, so // their untouched Local photos aren't forgotten while the folder is in use @@ -393,6 +397,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { d.album = task.album.filter(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_some_and(|a| !a.folder && !a.is_smart())); d.sources = task.sources; d.library = Some(app.session.library_generation()); + app.review_listed = Some(out.listed); app.review_pending = Some(crate::state::Dialog::Import { opts: Box::new(d) }); show_pending_review(app, ctx); } diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index 71ac358f9a..fdeac9c5b9 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -17,6 +17,8 @@ pub struct ImportTask { pub total: usize, pub done: usize, pub(super) params: Value, + /// What the review that started this import listed, for its job. + listed: Option, pub imported: usize, /// Brought back from Recently Deleted (`onDeleted: restore`). pub restored: usize, @@ -256,7 +258,9 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result } } let total = queue.len(); - app.import = Some(ImportTask::new(queue, params, undo0, false)); + let mut task = ImportTask::new(queue, params, undo0, false); + task.listed = app.review_listed.take(); + app.import = Some(task); app.renderer.forget_imports(); Ok(json!({"importing": total})) } @@ -282,6 +286,16 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { p["paths"] = json!(task.queue); let started = lightcraft_engine::cmd::library::import_params(&app.session, &p) .and_then(|req| Ok((lightcraft_engine::import::ImportJob::new(&mut app.session, req.opts)?, req.album, req.album_name))) + .map(|(job, album, name)| { + ( + match task.listed.take() { + Some(l) => job.with_listed(l), + None => job, + }, + album, + name, + ) + }) .map_err(|e| e.to_string()) .and_then(|(job, album, name)| ImportRun::start(job, std::mem::take(&mut task.queue), album, name, ctx)); if task.auto { diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index eb05be0c4c..b330477d6f 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -3695,6 +3695,57 @@ fn import_review_dialog() { let _ = std::fs::remove_dir_all(&dir); } +/// Set a folder's modification time (Windows opens a folder for attributes, with backup semantics). +fn set_folder_time(dir: &std::path::Path, at: std::time::SystemTime) { + #[cfg(windows)] + let handle = { + use std::os::windows::fs::OpenOptionsExt; + std::fs::OpenOptions::new().write(true).access_mode(0x100).custom_flags(0x0200_0000).open(dir) + }; + #[cfg(not(windows))] + let handle = std::fs::File::open(dir); + handle.unwrap().set_modified(at).unwrap(); +} + +/// A review's listing belongs to the import that review starts. Given a review that was +/// cancelled, when a sidecar appears in its folder (the folder's time put back as it was, as a +/// volume with coarse folder times would show it) and its file is imported another way (a folder +/// given by name is walked afresh, so only a named file could meet the old listing), +/// then the sidecar is read. +#[test] +fn a_cancelled_reviews_listing_is_not_used_by_another_import() { + let dir = std::env::temp_dir().join(format!("lc-ui-import-cancelled-review-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[9, 9, 9, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join("a.png"), png).unwrap(); + // (old enough for the scan to vouch for the folder's time) + set_folder_time(&dir, std::time::SystemTime::now() - Duration::from_secs(3600)); + let services = crate::Services { png: None, ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), services), [1300.0, 900.0], 1.0); + let t = Duration::from_secs(10); + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [dir.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 { .. }))); + assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. })), "the review is open"); + h.app.ui.dialog = None; // cancelled + let was = std::fs::metadata(&dir).unwrap().modified().unwrap(); + std::fs::write( + dir.join("a.xmp"), + r#""#, + ) + .unwrap(); + set_folder_time(&dir, was); + let r = h.request("engine.execute", json!({"command": "library.import", "params": {"paths": [dir.join("a.png").to_string_lossy()]}}), t); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let p = h.app.session.catalog.photos().find(|p| p.file_name == "a.png").expect("imported"); + assert_eq!(p.rating, 4, "the sidecar that appeared after the review is read"); + let _ = std::fs::remove_dir_all(&dir); +} + /// The import review offers what to do with files that are in Recently Deleted (issues #298, /// #706): they are checked, to be restored, by default; Leave them unchecks them; confirming /// restores the photo (with its edits) or, with Import as new, imports the file afresh. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e1b3410556..f29a96d458 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -331,6 +331,8 @@ pub struct LightcraftApp { pub(crate) scans_stopping: import::StoppingScans, /// Files that waited for a library and wait for the running import or Synchronize Folder too. pub waiting_import: panels::library_problem::WaitingImport, + /// The folders the last review's scan listed, for the import that review starts (and no other). + pub review_listed: Option, /// A Synchronize Folder scan in progress (feeds its dialog). pub sync: Option, /// `session.folder_changes` came from the Synchronize Folder dialog (and goes with it). diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index ae043cb5f1..7dffeb491c 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -1230,6 +1230,7 @@ fn auto_import_waits_for_a_browse_that_starts_during_its_listing() { truncated: false, unreadable: 0, unsupported: 0, + listed: Default::default(), })) .unwrap(); drop(tx); diff --git a/crates/ui-egui/src/tests/scan_probes.rs b/crates/ui-egui/src/tests/scan_probes.rs index a8a5bf116f..7496ad85fb 100644 --- a/crates/ui-egui/src/tests/scan_probes.rs +++ b/crates/ui-egui/src/tests/scan_probes.rs @@ -74,6 +74,7 @@ fn a_scan_closed_with_its_cross_hands_back_its_probes_when_the_worker_ends() { truncated: false, unreadable: 0, unsupported: 0, + listed: Default::default(), })) .unwrap(); assert!(h.step_until(T, kept), "the probes came back"); From 08c74f9a8f0743b6322bc97dd24aa86061b09ff1 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 20 Oct 2026 16:18:41 -0400 Subject: [PATCH 02/10] PERF-SIDECARS: renames and moves answer sidecar lookups from the folder listing Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/rename/fs.rs | 121 ++++++++++++++- crates/engine/src/rename/moves.rs | 2 + .../engine/src/rename/tests_listed_sources.rs | 138 ++++++++++++++++++ docs/whats-new.md | 12 ++ 4 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/rename/tests_listed_sources.rs diff --git a/crates/engine/src/rename/fs.rs b/crates/engine/src/rename/fs.rs index 30b6a3e30c..5787469f55 100644 --- a/crates/engine/src/rename/fs.rs +++ b/crates/engine/src/rename/fs.rs @@ -1,5 +1,5 @@ use super::sidecar::PacketVersion; -use super::{Path, PathBuf, SidecarNaming}; +use super::{HashMap, HashSet, Path, PathBuf, SidecarNaming}; /// Every sidecar that may belong to `path` (both naming conventions, `.xmp` and `.XMP`). pub(super) fn sidecars(path: &str) -> Vec<(PathBuf, SidecarNaming, bool)> { @@ -41,6 +41,10 @@ pub(crate) trait MoveFs { Err(_) => true, } } + /// The names in folder `dir`, or `None` when it can't be listed. + fn list_dir(&self, dir: &Path) -> Option> { + std::fs::read_dir(dir).ok()?.map(|e| e.map(|e| e.file_name())).collect::>().ok() + } /// Content observed in a packet, independent of its pathname or inode. Model volumes /// override this; disk implementations stream a bounded buffer without retaining the XML. fn packet_version(&self, path: &Path) -> std::io::Result { @@ -199,6 +203,121 @@ fn open_regular(a: &Path, checked: &std::fs::Metadata) -> std::io::Result { + inner: &'a dyn MoveFs, + /// folder → the `.xmp` names in it, lower-cased. + folders: std::cell::RefCell>>, +} + +impl<'a> ListedSources<'a> { + fn new(inner: &'a dyn MoveFs, moves: &[(String, String)]) -> Self { + let mut leaving: HashMap<&Path, usize> = HashMap::new(); + for (from, _) in moves { + if let Some(dir) = Path::new(from).parent().filter(|d| !d.as_os_str().is_empty()) { + *leaving.entry(dir).or_default() += 1; + } + } + let mut folders = HashMap::new(); + for (dir, n) in leaving { + if n < LIST_FOLDER_AT { + continue; + } + let Some(names) = inner.list_dir(dir) else { continue }; + // (any name that is no ASCII text: the listing can't say what another name's other case is) + let xmp: Option> = names + .iter() + .map(|n| n.to_str().filter(|n| n.is_ascii()).map(str::to_ascii_lowercase)) + .collect::>>() + .map(|v| v.into_iter().filter(|n| n.ends_with(".xmp")).collect()); + if let Some(xmp) = xmp { + folders.insert(dir.to_path_buf(), xmp); + } + } + ListedSources { inner, folders: std::cell::RefCell::new(folders) } + } + + /// Whether the listing shows `p`, a sidecar name, is not there. + fn surely_absent(&self, p: &Path) -> bool { + let folders = self.folders.borrow(); + let (Some(xmp), Some(name)) = (p.parent().and_then(|d| folders.get(d)), p.file_name().and_then(|n| n.to_str())) else { return false }; + p.to_str().is_some_and(|s| s.ends_with(name)) + && name.len() > ".xmp".len() + && name.to_ascii_lowercase().ends_with(".xmp") + && crate::sync::plain_name(name) + && !crate::sync::asks_the_disk(name) + && !xmp.contains(&name.to_ascii_lowercase()) + } + + /// A file arrived at `p`: a `.xmp` joins its folder's names (one that leaves changes nothing: + /// a name listed that is gone is asked about, and found missing, as before). + fn arrived(&self, p: &Path) { + let Some(dir) = p.parent() else { return }; + let mut folders = self.folders.borrow_mut(); + let Some(xmp) = folders.get_mut(dir) else { return }; + match p.file_name().and_then(|n| n.to_str()).filter(|n| n.is_ascii()) { + Some(name) if name.to_ascii_lowercase().ends_with(".xmp") => { + xmp.insert(name.to_ascii_lowercase()); + } + Some(_) => {} + None => { + folders.remove(dir); + } + } + } +} + +impl MoveFs for ListedSources<'_> { + fn exists(&self, p: &Path) -> bool { + self.inner.exists(p) + } + fn is_file(&self, p: &Path) -> bool { + !self.surely_absent(p) && self.inner.is_file(p) + } + fn same_file(&self, a: &Path, b: &Path) -> bool { + self.inner.same_file(a, b) + } + fn rename_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + let moved = self.inner.rename_no_replace(a, b); + if moved.is_ok() { + self.arrived(b); + } + moved + } + fn copy_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + let copied = self.inner.copy_no_replace(a, b); + if copied.is_ok() { + self.arrived(b); + } + copied + } + fn remove_file(&self, p: &Path) -> std::io::Result<()> { + self.inner.remove_file(p) + } + fn stem_sibling(&self, sidecar: &Path) -> Option { + self.inner.stem_sibling(sidecar) + } + fn listed(&self, p: &Path) -> bool { + self.inner.listed(p) + } + fn list_dir(&self, dir: &Path) -> Option> { + self.inner.list_dir(dir) + } + fn packet_version(&self, path: &Path) -> std::io::Result { + self.inner.packet_version(path) + } +} + /// Move `a` to `b` on another volume: copy (never replacing), compare the copy with the original /// byte for byte, and only then remove the original. A copy that doesn't match is removed. fn move_across_volumes(fs: &RealFs, a: &Path, b: &Path) -> std::io::Result<()> { diff --git a/crates/engine/src/rename/moves.rs b/crates/engine/src/rename/moves.rs index 07d7fdfc3d..19fe7965e1 100644 --- a/crates/engine/src/rename/moves.rs +++ b/crates/engine/src/rename/moves.rs @@ -123,6 +123,8 @@ pub(crate) struct BatchMoveError { /// Move the files `moves` names, all or nothing: after a failure the earlier moves are undone. /// Moves that can't be undone (e.g. the network share went away) are reported, not ignored. pub(crate) fn move_all(fs: &dyn MoveFs, moves: &[(String, String)]) -> std::result::Result<(), BatchMoveError> { + let listed = ListedSources::new(fs, moves); + let fs: &dyn MoveFs = &listed; let mut done: Vec<&(String, String)> = Vec::new(); for m in moves { let Err(e) = move_file_with(fs, &m.0, &m.1) else { diff --git a/crates/engine/src/rename/tests_listed_sources.rs b/crates/engine/src/rename/tests_listed_sources.rs new file mode 100644 index 0000000000..3ef5f9e7ba --- /dev/null +++ b/crates/engine/src/rename/tests_listed_sources.rs @@ -0,0 +1,138 @@ +//! Moving photos out of a folder asks the disk for their sidecars only where a listing of the +//! folder leaves room for one: on a network share each name asked about is a round trip. +use super::*; +use std::cell::Cell; + +/// The disk, counting the questions about `.xmp` names and the listings. +struct Counting { + can_list: bool, + xmp_asked: Cell, + listings: Cell, +} + +impl Counting { + fn new(can_list: bool) -> Self { + Counting { can_list, xmp_asked: Cell::new(0), listings: Cell::new(0) } + } +} + +impl MoveFs for Counting { + fn exists(&self, p: &Path) -> bool { + RealFs.exists(p) + } + fn is_file(&self, p: &Path) -> bool { + if p.extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp")) { + self.xmp_asked.set(self.xmp_asked.get() + 1); + } + RealFs.is_file(p) + } + fn same_file(&self, a: &Path, b: &Path) -> bool { + RealFs.same_file(a, b) + } + fn rename_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + RealFs.rename_no_replace(a, b) + } + fn copy_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + RealFs.copy_no_replace(a, b) + } + fn remove_file(&self, p: &Path) -> std::io::Result<()> { + RealFs.remove_file(p) + } + fn stem_sibling(&self, sidecar: &Path) -> Option { + RealFs.stem_sibling(sidecar) + } + fn list_dir(&self, dir: &Path) -> Option> { + self.listings.set(self.listings.get() + 1); + if self.can_list { RealFs.list_dir(dir) } else { None } + } +} + +fn scratch(tag: &str) -> (PathBuf, PathBuf) { + let root = std::env::temp_dir().join(format!("lc-listed-sources-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (from, to) = (root.join("from"), root.join("to")); + std::fs::create_dir_all(&from).unwrap(); + std::fs::create_dir_all(&to).unwrap(); + (from, to) +} + +/// `n` photos `p00.jpg`… in `from`, moved to `to` under the same names. +fn moves(from: &Path, to: &Path, n: usize) -> Vec<(String, String)> { + (0..n) + .map(|i| { + let name = format!("p{i:02}.jpg"); + (from.join(&name).to_string_lossy().to_string(), to.join(name).to_string_lossy().to_string()) + }) + .collect() +} + +fn names_lower(dir: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_lowercase()).collect(); + v.sort(); + v +} + +/// Given 50 photos in a folder without sidecars, when they are moved, then no sidecar name is +/// asked of the disk (it was eight questions for each photo), and the folder is listed once. +#[test] +fn photos_leaving_a_listed_folder_without_sidecars_ask_the_disk_nothing() { + let (from, to) = scratch("none"); + for (src, _) in moves(&from, &to, 50) { + std::fs::write(src, b"x").unwrap(); + } + let fs = Counting::new(true); + move_all(&fs, &moves(&from, &to, 50)).unwrap(); + assert_eq!((fs.xmp_asked.get(), fs.listings.get()), (0, 1)); + assert_eq!(names_lower(&to).len(), 50); + assert!(names_lower(&from).is_empty()); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); +} + +/// Given sidecars in every case and naming among the photos, when they are moved and moved back +/// (undo), then each goes with its photo each way, and only the photos that have one are asked +/// about. +#[test] +fn sidecars_in_the_listing_move_with_their_photos_and_back() { + let (from, to) = scratch("cases"); + let all = moves(&from, &to, 12); + for (src, _) in &all { + std::fs::write(src, b"x").unwrap(); + } + // stem and full names, in lower and upper case (the spellings a move looks for) + for sc in ["p00.xmp", "p01.XMP", "p02.jpg.xmp", "p03.jpg.XMP"] { + std::fs::write(from.join(sc), b"").unwrap(); + } + let before = names_lower(&from); + let fs = Counting::new(true); + move_all(&fs, &all).unwrap(); + assert!(names_lower(&from).is_empty(), "everything left, sidecars with their photos: {:?}", names_lower(&from)); + assert_eq!(names_lower(&to), before); + // (the four photos with a sidecar are asked about; the eight others are not) + assert!(fs.xmp_asked.get() > 0 && fs.xmp_asked.get() < 12 * 8, "{}", fs.xmp_asked.get()); + + let back: Vec<(String, String)> = all.iter().map(|(a, b)| (b.clone(), a.clone())).collect(); + move_all(&fs, &back).unwrap(); + assert_eq!(names_lower(&from), before); + assert!(names_lower(&to).is_empty()); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); +} + +/// A folder that can't be listed, and one with too few photos to list, keep the probes: a +/// sidecar there is still moved with its photo. +#[test] +fn a_folder_that_cannot_be_listed_or_is_too_small_is_probed_photo_by_photo() { + for (can_list, photos) in [(false, 12), (true, LIST_FOLDER_AT - 1)] { + let (from, to) = scratch("probed"); + let all = moves(&from, &to, photos); + for (src, _) in &all { + std::fs::write(src, b"x").unwrap(); + } + std::fs::write(from.join("p00.XMP"), b"").unwrap(); + let fs = Counting::new(can_list); + move_all(&fs, &all).unwrap(); + assert!(names_lower(&to).contains(&"p00.xmp".to_string()), "{can_list} {photos}"); + assert!(fs.xmp_asked.get() >= photos * 4, "each photo is probed: {}", fs.xmp_asked.get()); + assert_eq!(fs.listings.get(), usize::from(can_list && photos >= LIST_FOLDER_AT) + usize::from(!can_list), "{can_list} {photos}"); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); + } +} diff --git a/docs/whats-new.md b/docs/whats-new.md index ab0f90c033..36b2b5d991 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -364,6 +364,18 @@ Denoise ▸ Run on chooses; Automatic times both). Photos denoised before are denoised again the next time they are needed. See [AI Denoise](denoise.md). +### Imports and moves on a network share ask it less +- Import no longer asks a network share about each photo's `.xmp` sidecar (up to nine names, each a round trip) when + the folder's listing, which the import or the Add Photos review has already read, shows there is none. A sidecar in + any letter case (`.xmp`, `.XMP`, `.Xmp`, or `.xmp`) is still found and read. A folder that changed since + it was listed, or was too recently changed to tell, is asked about photo by photo. Importing the photos picked in + the review also stops asking the share whether each one is a file or a folder before the first one is handled. +- Renaming photos, moving them to another folder, and undoing either look for their sidecars in one listing of each + folder that eight or more photos leave, instead of asking for four names per photo. Sidecars the listing shows + still move with their photos (`.xmp` or `.XMP`, as before). +- Folders that could not be listed completely or whose time can't be read, and files you add one by one, are checked + as before. + ### A right-click on a text field while you carry photos opens no menu - While you drag photos from the grid, a right-click on a text field, such as the search box, opens no Cut, Copy and Paste menu. Before, the menu opened over the field the photos were on. Right-clicking a field without a drag works From 81fc5fa175310f7305d436f3e4f2a136be2b39dc Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 20 Oct 2026 16:55:56 -0400 Subject: [PATCH 03/10] PERF-SIDECARS: closing the import review without importing drops its listing Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control.rs | 1 + crates/ui-egui/src/dialogs.rs | 2 ++ crates/ui-egui/src/headless/tests.rs | 4 +++- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 63403650b2..6d67ceb1e7 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -466,6 +466,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest "ui.dialog.cancel" => { if matches!(app.ui.dialog, Some(crate::state::Dialog::Import { .. })) { app.renderer.forget_imports(); + app.review_listed = None; } app.ui.dialog = None; ok(Value::Null) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 91d9dd2611..05ec2bc856 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -389,8 +389,10 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { let frame = ctx.cumulative_frame_nr(); ctx.data_mut(|d| d.insert_temp(egui::Id::unique(BACKDROP_SHOWN), frame)); } + // a review closed without importing (Cancel, Esc) leaves no listing behind (OK took it already) if close && matches!(dlg, Dialog::Import { .. }) { app.renderer.forget_imports(); + app.review_listed = None; } app.ui.dialog = if close { None } else { Some(dlg) }; } diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index b330477d6f..841281222e 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -3730,7 +3730,9 @@ fn a_cancelled_reviews_listing_is_not_used_by_another_import() { h.settle(SETTLE); h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. }))); assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. })), "the review is open"); - h.app.ui.dialog = None; // cancelled + assert!(h.app.review_listed.is_some(), "the review holds its listing"); + h.request("ui.dialog.cancel", json!({}), t); + assert!(h.app.review_listed.is_none(), "cancelling the review drops the listing"); let was = std::fs::metadata(&dir).unwrap().modified().unwrap(); std::fs::write( dir.join("a.xmp"), From 950ee928b347768e8757c21b2bcd59c58e0505c7 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 15:37:10 -0400 Subject: [PATCH 04/10] PERF-SIDECARS: the scan's folder-listing callback says it never stops the walk (comment only) --- crates/engine/src/import/scan.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 9e0e5a4154..5941d83194 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -319,7 +319,8 @@ pub fn scan_with(mut input: ScanInput, paths: &[String], progress: &ScanProgress paths, input.skip.as_deref(), crate::walk::Limits::default(), - // (the walk goes on: only a scan that is cancelled ends it early) + // (always `true`: nothing here stops the walk. `progress.cancel` is read only once it is over, in + // `scan_files`, which stops the probing and returns what it has) Some(&mut |dir, names, complete, modified| { listed.note(dir, names, complete, modified); true From e4761368332595112236c990bbd0a82d9901b731 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 16:07:49 -0400 Subject: [PATCH 05/10] PERF-SIDECARS: a listed file name is trusted only while its folder is as it was listed --- crates/engine/src/import/job.rs | 2 + crates/engine/src/import/listed_folders.rs | 5 ++- .../engine/src/import/tests_listed_folders.rs | 41 ++++++++++++++++++- 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index fb2147ee7e..777b375eb0 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -231,6 +231,8 @@ impl ImportJob { // (a file the review listed is a file: no round trip to a share to ask) let mut listed = std::mem::take(&mut self.listed); let mut walked = ListedFolders::default(); + // (the folders' times are looked at now, not as an earlier batch found them) + listed.new_batch(); let (files, _) = expand_knowing( paths, self.lib_dir.as_deref(), diff --git a/crates/engine/src/import/listed_folders.rs b/crates/engine/src/import/listed_folders.rs index d1b30e206e..b895de7306 100644 --- a/crates/engine/src/import/listed_folders.rs +++ b/crates/engine/src/import/listed_folders.rs @@ -108,10 +108,13 @@ impl ListedFolders { } /// Whether a listing says `path` is a file, as it was found: the disk need not be asked. + /// Only while its folder is as it was listed (a file may have been replaced by a folder since; + /// a folder with no usable time is never trusted). pub(crate) fn is_known_file(&self, path: &Path) -> bool { let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else { return false }; // (the path ends in that name: no `/.` or separator after it, which the disk would resolve) - path.to_str().is_some_and(|p| p.ends_with(name)) && self.folders.get(dir).is_some_and(|f| f.files.contains(name)) + path.to_str().is_some_and(|p| p.ends_with(name)) + && self.folders.get(dir).is_some_and(|f| f.files.contains(name) && self.unchanged(dir, f.modified)) } /// Whether the listing of `original`'s folder shows that none of its sidecar names is there. diff --git a/crates/engine/src/import/tests_listed_folders.rs b/crates/engine/src/import/tests_listed_folders.rs index 18e1179963..a34644ca86 100644 --- a/crates/engine/src/import/tests_listed_folders.rs +++ b/crates/engine/src/import/tests_listed_folders.rs @@ -209,7 +209,8 @@ fn an_import_after_a_review_trusts_the_folders_the_review_listed() { } /// A path the listing calls a file is not asked about (here the disk holds a folder by that -/// name, which only a look at the disk would find); one it does not list still is. +/// name, which only a look at the disk would find) while its folder is as it was listed; one it +/// does not list still is. #[test] fn a_file_the_listing_does_not_know_is_still_checked() { let root = scratch("known"); @@ -217,8 +218,10 @@ fn a_file_the_listing_does_not_know_is_still_checked() { std::fs::create_dir_all(root.join(name)).unwrap(); std::fs::write(root.join(name).join("inner.jpg"), b"x").unwrap(); } + settle(&root); let mut job = job(SidecarNaming::Stem); - job.listed.note(&root, vec![("known.jpg".into(), crate::walk::EntryKind::File)], true, None); + // (the folder is as listed: its time is the one the listing holds) + job.listed.note(&root, vec![("known.jpg".into(), crate::walk::EntryKind::File)], true, modified(&root)); let (known, unknown) = (root.join("known.jpg"), root.join("unknown.jpg")); let files = job.expand(&[known.to_string_lossy().to_string(), unknown.to_string_lossy().to_string()]); assert_eq!(files, [known.to_string_lossy().to_string(), unknown.join("inner.jpg").to_string_lossy().to_string()]); @@ -316,3 +319,37 @@ fn a_sidecar_written_in_the_tick_of_the_listing_is_read() { assert_eq!(found.iter().filter(|(_, r)| *r == Some(5)).count(), 1, "{found:?}"); let _ = std::fs::remove_dir_all(&root); } + +/// Given a review whose listing was kept, when a listed file is replaced by a folder holding a +/// photo afterwards, then the import's expansion walks that folder: a name in a folder that +/// changed since it was listed is not trusted to still be a file. +#[test] +fn a_listed_file_replaced_by_a_folder_is_expanded() { + let root = scratch("replaced"); + for n in 0..3 { + std::fs::write(root.join(format!("a{n}.jpg")), b"x").unwrap(); + } + settle(&root); + let mut walked = ListedFolders::default(); + let (files, _) = expand_knowing( + &[root.to_string_lossy().to_string()], + None, + crate::walk::Limits::default(), + Some(&mut |dir, names, complete, modified| { + walked.note(dir, names, complete, modified); + true + }), + true, + &|_| false, + ); + assert_eq!(files.len(), 3); + std::fs::remove_file(root.join("a1.jpg")).unwrap(); + std::fs::create_dir(root.join("a1.jpg")).unwrap(); + std::fs::write(root.join("a1.jpg").join("inside.jpg"), b"x").unwrap(); + let mut job = job(SidecarNaming::Stem).with_listed(walked); + // (the paths handed to the import are the files the review listed) + let found = job.expand(&files); + assert!(found.iter().any(|f| f.ends_with("inside.jpg")), "{found:?}"); + assert_eq!(found.len(), 3, "{found:?}"); + let _ = std::fs::remove_dir_all(&root); +} From fa49d0a5fd0be11541b2ec52b4cdf9ac60083806 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 16:21:22 -0400 Subject: [PATCH 06/10] PERF-SIDECARS: a folder listed with no time is not trusted without a look; docs say names depend on the folder's time --- crates/engine/src/import/listed_folders.rs | 13 ++++++++----- crates/engine/src/import/tests_listed_folders.rs | 13 +++++++++++++ docs/whats-new.md | 5 +++-- 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/import/listed_folders.rs b/crates/engine/src/import/listed_folders.rs index b895de7306..8d79732aa7 100644 --- a/crates/engine/src/import/listed_folders.rs +++ b/crates/engine/src/import/listed_folders.rs @@ -25,15 +25,16 @@ struct Folder { /// ASCII names (the names a file system treats alike in other cases are the ones we can fold /// ourselves): for any other the disk decides, as before. xmp: Option>, - /// The folder's modification time when it was listed: a file added or removed since changes - /// it, and the `.xmp` names are then not trusted (a listing taken by a review can be hours old). + /// The folder's modification time when it was listed: a file added, removed or replaced since + /// changes it, and the `.xmp` and file names are then not trusted (a listing taken by a review + /// can be hours old). modified: Option, } /// The folders listed so far (see the module docs). The review's scan hands its listing to the /// import that review starts ([`crate::import::ImportJob::with_listed`]), and nowhere else. -/// The `.xmp` names of a folder are trusted only while its modification time is what it was -/// when it was listed (looked at once per folder per batch: [`ListedFolders::new_batch`]); a +/// The `.xmp` names and the file names of a folder are trusted only while its modification time +/// is what it was when it was listed (looked at once per folder per batch: [`ListedFolders::new_batch`]); a /// volume whose folders keep no usable time (it can't be read) is probed as before. #[derive(Debug, Default)] pub struct ListedFolders { @@ -91,13 +92,15 @@ impl ListedFolders { /// Whether `dir` is as it was listed. fn unchanged(&self, dir: &Path, listed: Option) -> bool { + // (no time to compare with: not trusted, and the disk is not asked) + let Some(listed) = listed else { return false }; let mut checked = self.checked.lock().unwrap_or_else(|e| e.into_inner()); if let Some(known) = checked.get(dir) { return *known; } self.looked.fetch_add(1, Ordering::Relaxed); let now = std::fs::metadata(dir).and_then(|m| m.modified()).ok(); - let same = now.is_some() && now == listed; + let same = now == Some(listed); checked.insert(dir.to_path_buf(), same); same } diff --git a/crates/engine/src/import/tests_listed_folders.rs b/crates/engine/src/import/tests_listed_folders.rs index a34644ca86..169922add9 100644 --- a/crates/engine/src/import/tests_listed_folders.rs +++ b/crates/engine/src/import/tests_listed_folders.rs @@ -353,3 +353,16 @@ fn a_listed_file_replaced_by_a_folder_is_expanded() { assert_eq!(found.len(), 3, "{found:?}"); let _ = std::fs::remove_dir_all(&root); } + +/// A folder noted with no time (too recent to vouch for, or the volume keeps none) is not +/// trusted, and finding that out costs no look at the disk. +#[test] +fn a_folder_without_a_listed_time_costs_no_look() { + let root = scratch("no-time"); + std::fs::write(root.join("a.jpg"), b"x").unwrap(); + let mut l = ListedFolders::default(); + l.note(&root, vec![("a.jpg".into(), crate::walk::EntryKind::File)], true, None); + assert!(!l.is_known_file(&root.join("a.jpg"))); + assert_eq!(l.looked.load(Relaxed), 0); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/docs/whats-new.md b/docs/whats-new.md index 36b2b5d991..892f96d915 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -368,8 +368,9 @@ - Import no longer asks a network share about each photo's `.xmp` sidecar (up to nine names, each a round trip) when the folder's listing, which the import or the Add Photos review has already read, shows there is none. A sidecar in any letter case (`.xmp`, `.XMP`, `.Xmp`, or `.xmp`) is still found and read. A folder that changed since - it was listed, or was too recently changed to tell, is asked about photo by photo. Importing the photos picked in - the review also stops asking the share whether each one is a file or a folder before the first one is handled. + it was listed, or was too recently changed to tell, is asked about photo by photo. For the folders that have not + changed since the review listed them, importing the photos picked in the review also stops asking the share + whether each one is a file or a folder before the first one is handled. - Renaming photos, moving them to another folder, and undoing either look for their sidecars in one listing of each folder that eight or more photos leave, instead of asking for four names per photo. Sidecars the listing shows still move with their photos (`.xmp` or `.XMP`, as before). From 7eb7f00b79a5733761987e5a646a9ec85da80166 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 13:43:24 -0400 Subject: [PATCH 07/10] PERF-SIDECARS: a review waiting behind the open one keeps its own listing A scan that finishes while an import review is open queues its review behind it. Its listing used to replace the open review's at once, so cancelling the open one dropped the queued one's, and confirming it used the wrong one. The listing now waits with its review and takes over when it opens. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs/import/scan.rs | 5 +-- crates/ui-egui/src/headless/tests.rs | 39 +++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 4 ++- 4 files changed, 46 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index caf344deb3..d15e894b2f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -121,6 +121,7 @@ impl LightcraftApp { lightroom_last: None, lightroom_result: None, review_pending: None, + review_pending_listed: None, shown_library: None, export: None, tasks: Default::default(), diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index e402fcbeed..9902262856 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -344,7 +344,6 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { if cancelled { return; } - app.review_listed = None; if task.browse { // the folder and the ones its photos are in count as browsed now, as `library.browse` records them, so // their untouched Local photos aren't forgotten while the folder is in use @@ -397,7 +396,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { d.album = task.album.filter(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_some_and(|a| !a.folder && !a.is_smart())); d.sources = task.sources; d.library = Some(app.session.library_generation()); - app.review_listed = Some(out.listed); + app.review_pending_listed = Some(out.listed); app.review_pending = Some(crate::state::Dialog::Import { opts: Box::new(d) }); show_pending_review(app, ctx); } @@ -413,10 +412,12 @@ fn show_pending_review(app: &mut LightcraftApp, ctx: &egui::Context) { && !opts.in_library(app) { app.review_pending = None; + app.review_pending_listed = None; return; } if app.ui.dialog.is_none() { app.ui.dialog = app.review_pending.take(); + app.review_listed = app.review_pending_listed.take(); } else { ctx.request_repaint_after(std::time::Duration::from_millis(100)); } diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index 841281222e..af62205907 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -3748,6 +3748,45 @@ fn a_cancelled_reviews_listing_is_not_used_by_another_import() { let _ = std::fs::remove_dir_all(&dir); } +/// A review waiting behind the open one keeps its own listing. Given a review that is open, when +/// another scan finishes (it waits for the dialog to close), then the open review still holds the +/// folders its own scan listed, and the waiting one's are kept for when it opens. +#[test] +fn a_waiting_reviews_listing_does_not_replace_the_open_ones() { + let make = |tag: &str| { + let dir = std::env::temp_dir().join(format!("lc-ui-import-waiting-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[9, 9, 9, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join("a.png"), png).unwrap(); + set_folder_time(&dir, std::time::SystemTime::now() - Duration::from_secs(3600)); + dir + }; + let (first, second) = (make("first"), make("second")); + let services = crate::Services { png: None, ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), services), [1300.0, 900.0], 1.0); + let t = Duration::from_secs(10); + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [first.to_string_lossy()]}}), t); + assert_eq!(r["result"]["scanning"], true, "{r}"); + h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. }))); + let listed = |h: &Headless| format!("{:?}", h.app.review_listed); + assert!(listed(&h).contains("-first-"), "the open review holds its own listing: {}", listed(&h)); + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [second.to_string_lossy()]}}), t); + assert_eq!(r["result"]["scanning"], true, "{r}"); + h.step_until(SETTLE, |h| h.app.scan.is_none()); + h.settle(SETTLE); + assert!(h.app.review_pending.is_some(), "the second review waits behind the open one"); + assert!(listed(&h).contains("-first-") && !listed(&h).contains("-second-"), "the open review keeps its listing: {}", listed(&h)); + // cancelled, the first review makes room for the waiting one, which brings its own listing + h.request("ui.dialog.cancel", json!({}), t); + h.step_until(SETTLE, |h| h.app.review_pending.is_none()); + assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. })), "the waiting review opens"); + assert!(listed(&h).contains("-second-") && !listed(&h).contains("-first-"), "it holds its own listing: {}", listed(&h)); + let _ = std::fs::remove_dir_all(&first); + let _ = std::fs::remove_dir_all(&second); +} + /// The import review offers what to do with files that are in Recently Deleted (issues #298, /// #706): they are checked, to be restored, by default; Leave them unchecks them; confirming /// restores the photo (with its edits) or, with Import as new, imports the file afresh. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f29a96d458..8a222ad08d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -331,7 +331,7 @@ pub struct LightcraftApp { pub(crate) scans_stopping: import::StoppingScans, /// Files that waited for a library and wait for the running import or Synchronize Folder too. pub waiting_import: panels::library_problem::WaitingImport, - /// The folders the last review's scan listed, for the import that review starts (and no other). + /// The folders the scan of the review on screen listed, for the import that review starts (and no other). pub review_listed: Option, /// A Synchronize Folder scan in progress (feeds its dialog). pub sync: Option, @@ -347,6 +347,8 @@ pub struct LightcraftApp { pub(crate) lightroom_result: Option, /// The import review of a finished scan, waiting for another dialog to close. pub(crate) review_pending: Option, + /// The folders that review's scan listed; they become [`Self::review_listed`] when the review opens. + pub(crate) review_pending_listed: Option, /// The library generation the window title and the recent list were last updated for. pub shown_library: Option, /// A background export in progress. From 77fa7d1d7376fb66a7b134d5f62195811cec248e Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 22:18:36 -0400 Subject: [PATCH 08/10] PERF-SIDECARS: a move lists no folder of more entries than a bound --- crates/engine/src/import.rs | 2 + crates/engine/src/import/files.rs | 15 ++++++- crates/engine/src/import/job.rs | 6 +-- crates/engine/src/rename.rs | 4 +- crates/engine/src/rename/fs.rs | 39 ++++++++++++++----- crates/engine/src/rename/moves.rs | 2 +- .../engine/src/rename/tests_listed_sources.rs | 36 ++++++++++++++++- 7 files changed, 85 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 3879ee65f7..013a96f360 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -46,6 +46,8 @@ mod types; pub(crate) use commit::workers; pub use commit::{batch_size, civil, commit_prepared, system_clock}; pub use defaults::{CameraDefault, ImportDefaults, apply_import_defaults, has_import_look, import_defaults}; +#[cfg(test)] +use files::expand_knowing; pub use files::{ EXTENSIONS, Expansion, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_report, expand_within, is_supported, launch_deadline, launch_path, launch_path_until, diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index b7627ed6c2..5ab0923a3e 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -118,10 +118,23 @@ fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::wa expand_report_knowing(paths, skip, limits, note, false, &|_| false) } -/// [`expand_report_noting`], taking the paths `known_file` says are files as files without asking the +/// [`expand_noting`], taking the paths `known_file` says are files as files without asking the /// disk (a review hands over thousands of them, and telling a file from a folder is a round trip /// each on a network share). With `timed`, each folder's modification time goes to `note` too /// ([`crate::walk::files_in_noting_timed`]). +pub(super) fn expand_knowing( + paths: &[String], + skip: Option<&Path>, + limits: crate::walk::Limits, + note: Option, + timed: bool, + known_file: &dyn Fn(&Path) -> bool, +) -> (Vec, bool) { + let e = expand_report_knowing(paths, skip, limits, note, timed, known_file); + (e.files, e.truncated) +} + +/// [`expand_knowing`] keeping the walks' diagnostics ([`Expansion`]). pub(super) fn expand_report_knowing( paths: &[String], skip: Option<&Path>, diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 777b375eb0..def0f1ccbd 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -1,5 +1,5 @@ use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock}; -use super::files::{Seen, expand, probe_all, reusable_probes}; +use super::files::{Seen, expand_knowing, probe_all, reusable_probes}; use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted}; use super::{HashMap, ListedFolders, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; @@ -45,9 +45,9 @@ pub struct ImportJob { file_bytes: Option, /// Probes from a preceding scan (not read again). pub(super) cache: HashMap, - naming: crate::sidecar::SidecarNaming, + pub(super) naming: crate::sidecar::SidecarNaming, /// The `.xmp` names in the folders [`ImportJob::expand`] listed. - listed: ListedFolders, + pub(super) listed: ListedFolders, now: String, /// Next rename number; `None` once the final representable value has been reserved. seq: Option, diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index f1d06b3cd5..d1677498ea 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -38,9 +38,9 @@ mod plan; mod sidecar; mod tokens; -pub(crate) use fs::{MoveFs, RealFs}; #[cfg(test)] -use fs::{folded_path, same_contents}; +use fs::{LIST_FOLDER_AT, ListedSources, folded_path, same_contents}; +pub(crate) use fs::{MoveFs, RealFs}; pub(crate) use moves::move_all; #[cfg(test)] pub(crate) use moves::move_file_with; diff --git a/crates/engine/src/rename/fs.rs b/crates/engine/src/rename/fs.rs index 5787469f55..31e69a6c8c 100644 --- a/crates/engine/src/rename/fs.rs +++ b/crates/engine/src/rename/fs.rs @@ -41,9 +41,17 @@ pub(crate) trait MoveFs { Err(_) => true, } } - /// The names in folder `dir`, or `None` when it can't be listed. - fn list_dir(&self, dir: &Path) -> Option> { - std::fs::read_dir(dir).ok()?.map(|e| e.map(|e| e.file_name())).collect::>().ok() + /// The names in folder `dir`, or `None` when it can't be listed or holds more than `budget` + /// entries (it stops reading at that many, so a huge folder is never collected). + fn list_dir(&self, dir: &Path, budget: usize) -> Option> { + let mut names = Vec::new(); + for entry in std::fs::read_dir(dir).ok()? { + if names.len() == budget { + return None; + } + names.push(entry.ok()?.file_name()); + } + Some(names) } /// Content observed in a packet, independent of its pathname or inode. Model volumes /// override this; disk implementations stream a bounded buffer without retaining the XML. @@ -206,7 +214,12 @@ fn open_regular(a: &Path, checked: &std::fs::Metadata) -> std::io::Result { +pub(super) struct ListedSources<'a> { inner: &'a dyn MoveFs, /// folder → the `.xmp` names in it, lower-cased. - folders: std::cell::RefCell>>, + pub(super) folders: std::cell::RefCell>>, } impl<'a> ListedSources<'a> { - fn new(inner: &'a dyn MoveFs, moves: &[(String, String)]) -> Self { + pub(super) fn new(inner: &'a dyn MoveFs, moves: &[(String, String)]) -> Self { + Self::with_budget(inner, moves, LIST_ENTRIES_AT_MOST) + } + + /// As [`Self::new`], with at most `budget` directory entries listed over all folders. + pub(super) fn with_budget(inner: &'a dyn MoveFs, moves: &[(String, String)], mut budget: usize) -> Self { let mut leaving: HashMap<&Path, usize> = HashMap::new(); for (from, _) in moves { if let Some(dir) = Path::new(from).parent().filter(|d| !d.as_os_str().is_empty()) { @@ -233,7 +251,8 @@ impl<'a> ListedSources<'a> { if n < LIST_FOLDER_AT { continue; } - let Some(names) = inner.list_dir(dir) else { continue }; + let Some(names) = inner.list_dir(dir, budget) else { continue }; + budget -= names.len(); // (any name that is no ASCII text: the listing can't say what another name's other case is) let xmp: Option> = names .iter() @@ -310,8 +329,8 @@ impl MoveFs for ListedSources<'_> { fn listed(&self, p: &Path) -> bool { self.inner.listed(p) } - fn list_dir(&self, dir: &Path) -> Option> { - self.inner.list_dir(dir) + fn list_dir(&self, dir: &Path, budget: usize) -> Option> { + self.inner.list_dir(dir, budget) } fn packet_version(&self, path: &Path) -> std::io::Result { self.inner.packet_version(path) diff --git a/crates/engine/src/rename/moves.rs b/crates/engine/src/rename/moves.rs index 19fe7965e1..88ffc75fb1 100644 --- a/crates/engine/src/rename/moves.rs +++ b/crates/engine/src/rename/moves.rs @@ -1,4 +1,4 @@ -use super::fs::{MoveFs, RealFs, folded_path, is_respelling, move_one, sidecars}; +use super::fs::{ListedSources, MoveFs, RealFs, folded_path, is_respelling, move_one, sidecars}; use super::sidecar::{RetainedPacket, SidecarMove, advance_packets, note_companions, packet_aliases}; use super::{HashMap, HashSet, Op, Path, PathBuf, SidecarNaming, Source}; diff --git a/crates/engine/src/rename/tests_listed_sources.rs b/crates/engine/src/rename/tests_listed_sources.rs index 3ef5f9e7ba..3454309a4d 100644 --- a/crates/engine/src/rename/tests_listed_sources.rs +++ b/crates/engine/src/rename/tests_listed_sources.rs @@ -41,9 +41,9 @@ impl MoveFs for Counting { fn stem_sibling(&self, sidecar: &Path) -> Option { RealFs.stem_sibling(sidecar) } - fn list_dir(&self, dir: &Path) -> Option> { + fn list_dir(&self, dir: &Path, budget: usize) -> Option> { self.listings.set(self.listings.get() + 1); - if self.can_list { RealFs.list_dir(dir) } else { None } + if self.can_list { RealFs.list_dir(dir, budget) } else { None } } } @@ -136,3 +136,35 @@ fn a_folder_that_cannot_be_listed_or_is_too_small_is_probed_photo_by_photo() { let _ = std::fs::remove_dir_all(from.parent().unwrap()); } } + +/// Given a folder that holds more entries than the listing budget, when its photos are moved, +/// then the folder is not collected (the read stops at the budget) and each photo's sidecar is +/// still probed and moved with it. +#[test] +fn a_folder_past_the_listing_budget_is_not_listed_and_is_probed_photo_by_photo() { + let (from, to) = scratch("budget"); + let all = moves(&from, &to, 12); + for (src, _) in &all { + std::fs::write(src, b"x").unwrap(); + } + std::fs::write(from.join("p00.XMP"), b"").unwrap(); + // 13 entries: 12 photos and a sidecar + assert!(RealFs.list_dir(&from, 12).is_none(), "one entry past the budget"); + assert_eq!(RealFs.list_dir(&from, 13).map(|n| n.len()), Some(13), "a budget of exactly its size lists it"); + + let fs = Counting::new(true); + let listed = ListedSources::with_budget(&fs, &all, 12); + assert!(listed.folders.borrow().is_empty(), "the folder is past the budget"); + let listed = ListedSources::with_budget(&fs, &all, 13); + assert_eq!(listed.folders.borrow().len(), 1, "and within it, listed"); + + // the move itself goes photo by photo: every photo asks the disk, the sidecar still follows + let probing = Counting::new(true); + let listed = ListedSources::with_budget(&probing, &all, 12); + for (a, b) in &all { + move_file_with(&listed, a, b).unwrap(); + } + assert!(probing.xmp_asked.get() >= 12 * 4, "each photo is probed: {}", probing.xmp_asked.get()); + assert!(names_lower(&to).contains(&"p00.xmp".to_string())); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); +} From e35d9fd4947ee92609608b162ed1f5eaaadb7a80 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 27 Oct 2026 13:24:00 -0400 Subject: [PATCH 09/10] Skip a folder listing larger than its budget instead of underflowing it MoveFs::list_dir can be overridden, and only the default implementation keeps its contract of returning None past the budget. ListedSources::with_budget subtracted the names it got from the shared budget, which panics in debug builds and wraps in release ones when an override returns more. Such a folder is now not trusted and its photos are probed one by one, as for any folder that isn't listed. --- crates/engine/src/rename/fs.rs | 4 ++- .../engine/src/rename/tests_listed_sources.rs | 33 ++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/rename/fs.rs b/crates/engine/src/rename/fs.rs index 31e69a6c8c..52a86e7545 100644 --- a/crates/engine/src/rename/fs.rs +++ b/crates/engine/src/rename/fs.rs @@ -252,7 +252,9 @@ impl<'a> ListedSources<'a> { continue; } let Some(names) = inner.list_dir(dir, budget) else { continue }; - budget -= names.len(); + // (an override that lists more than the budget it was given breaks the contract: not trusted) + let Some(left) = budget.checked_sub(names.len()) else { continue }; + budget = left; // (any name that is no ASCII text: the listing can't say what another name's other case is) let xmp: Option> = names .iter() diff --git a/crates/engine/src/rename/tests_listed_sources.rs b/crates/engine/src/rename/tests_listed_sources.rs index 3454309a4d..394f87419f 100644 --- a/crates/engine/src/rename/tests_listed_sources.rs +++ b/crates/engine/src/rename/tests_listed_sources.rs @@ -6,13 +6,19 @@ use std::cell::Cell; /// The disk, counting the questions about `.xmp` names and the listings. struct Counting { can_list: bool, + /// `list_dir` returns every name whatever the budget (an override that breaks the contract). + ignores_budget: bool, xmp_asked: Cell, listings: Cell, } impl Counting { fn new(can_list: bool) -> Self { - Counting { can_list, xmp_asked: Cell::new(0), listings: Cell::new(0) } + Counting { can_list, ignores_budget: false, xmp_asked: Cell::new(0), listings: Cell::new(0) } + } + + fn ignoring_the_budget() -> Self { + Counting { ignores_budget: true, ..Counting::new(true) } } } @@ -43,6 +49,7 @@ impl MoveFs for Counting { } fn list_dir(&self, dir: &Path, budget: usize) -> Option> { self.listings.set(self.listings.get() + 1); + let budget = if self.ignores_budget { usize::MAX } else { budget }; if self.can_list { RealFs.list_dir(dir, budget) } else { None } } } @@ -168,3 +175,27 @@ fn a_folder_past_the_listing_budget_is_not_listed_and_is_probed_photo_by_photo() assert!(names_lower(&to).contains(&"p00.xmp".to_string())); let _ = std::fs::remove_dir_all(from.parent().unwrap()); } + +/// Given a `list_dir` override that returns more names than the budget it was given (the trait +/// documents `None` then), when the listing is collected, then the folder is skipped: the budget +/// neither underflows nor wraps, and the photos' sidecars are probed one by one as before. +#[test] +fn a_listing_larger_than_its_budget_is_skipped_not_counted_below_zero() { + let (from, to) = scratch("overlist"); + let all = moves(&from, &to, 12); + for (src, _) in &all { + std::fs::write(src, b"x").unwrap(); + } + std::fs::write(from.join("p00.XMP"), b"").unwrap(); + + let fs = Counting::ignoring_the_budget(); + let listed = ListedSources::with_budget(&fs, &all, 5); + assert_eq!(fs.listings.get(), 1, "the folder was asked for"); + assert!(listed.folders.borrow().is_empty(), "13 names against a budget of 5: not trusted"); + + for (a, b) in &all { + move_file_with(&listed, a, b).unwrap(); + } + assert!(names_lower(&to).contains(&"p00.xmp".to_string()), "the sidecar still follows its photo"); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); +} From fd0e47270060959a58f50e07e3a95eff28852b02 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 3 Nov 2026 19:43:36 -0500 Subject: [PATCH 10/10] PERF-SIDECARS: a batch's sidecars are looked up 16 at a time again, through the listing Main's `sidecars_of` (#2954) looks up the sidecars of a batch's probed files together, 16 at a time, before the loop that plans them. The rebase onto main kept the listing's lookup but left it inside that loop, so on a network share the lookups ran one photo after another again. `prepare_files` now asks `sidecars_of` for the whole batch with `ListedFolders::find_for_import` as the lookup. A file whose content the library has still asks the disk nothing, as on main. Main's two tests for this are back, with one that fails when the lookups are made by the thread that plans the batch. `new_batch` now says a folder's time is looked at once per batch. --- crates/engine/src/import/files.rs | 69 +++++++++++++++++++ crates/engine/src/import/job.rs | 22 ++++-- crates/engine/src/import/listed_folders.rs | 11 ++- .../engine/src/import/tests_listed_folders.rs | 26 +++++++ 4 files changed, 122 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index 5ab0923a3e..cfa7e9a6e6 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -461,6 +461,17 @@ pub(crate) fn stat_all(paths: &[&str], cancel: &std::sync::atomic::AtomicBool, s at_once(paths, cancel, |p| stat(p)).into_iter().map(|s| s.unwrap_or(Seen::Unchecked)).collect() } +/// The sidecar of each of `files` (`find` says which: a few names looked up on the disk for each, +/// a round trip apiece on a network share), several files at once ([`at_once`]); `None` for a +/// file with no sidecar or not reached once `cancel` is set. +pub(super) fn sidecars_of( + files: &[&str], + cancel: &std::sync::atomic::AtomicBool, + find: impl Fn(&str) -> Option + Sync, +) -> Vec> { + at_once(files, cancel, |f| find(f)).into_iter().map(Option::flatten).collect() +} + /// The probes in `cache` of `files` that are still true: the file is looked at ([`stat_all`]) and /// `ok` says it is as it was probed. `None` for a file with no probe in `cache`, one that changed, /// and one not looked at because `cancel` was set. @@ -752,4 +763,62 @@ mod prepared_tests { assert_eq!(prepared.items.len(), 4); let _ = std::fs::remove_dir_all(&dir); } + + /// Given photos on a network share, when an import looks for their sidecars, then it asks about + /// several photos at once: one photo after another, nine names each, they were 77 % of the + /// import's preparation (95 % where a folder listing could not vouch for the names). + #[test] + fn sidecars_are_looked_up_for_several_photos_at_once() { + use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + let (active, together) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let names: Vec = (0..6).map(|i| format!("photo-{i}.jpg")).collect(); + let files: Vec<&str> = names.iter().map(String::as_str).collect(); + let found = sidecars_of(&files, &std::sync::atomic::AtomicBool::new(false), |f| { + active.fetch_add(1, Relaxed); + let end = std::time::Instant::now() + std::time::Duration::from_secs(1); + while active.load(Relaxed) < 2 && std::time::Instant::now() < end { + std::thread::yield_now(); + } + together.fetch_max(active.load(Relaxed), Relaxed); + active.fetch_sub(1, Relaxed); + f.ends_with("-3.jpg").then(|| PathBuf::from(f).with_extension("xmp")) + }); + assert!(together.load(Relaxed) >= 2, "the photos were looked up one at a time"); + let expect: Vec> = (0..6).map(|i| (i == 3).then(|| PathBuf::from("photo-3.xmp"))).collect(); + assert_eq!(found, expect, "each sidecar stays with its photo"); + } + + /// The sidecars found for a batch go to the photos they belong to, whichever have one, and a + /// photo that failed to probe takes none of the others'. + #[test] + fn a_batchs_sidecars_go_to_their_own_photos() { + let dir = std::env::temp_dir().join(format!("lightcraft-sidecars-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let xmp = r#""#; + let files: Vec = ["a.jpg", "broken.jpg", "c.jpg", "d.jpg"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect(); + for f in &files { + std::fs::write(f, b"x").unwrap(); + } + std::fs::write(dir.join("c.xmp"), xmp).unwrap(); + let mut s = Session::new(); + let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap(); + job.probe = Some(std::sync::Arc::new(|p: &str| { + if p.ends_with("broken.jpg") { + Err("unreadable".into()) + } else { + Ok(ProbeInfo { format: "JPEG".into(), file_size: 1, ..ProbeInfo::default() }) + } + })); + let prepared = job.prepare_files(files, &std::sync::atomic::AtomicBool::new(false)); + let rating = |name: &str| { + prepared.items.iter().find_map(|i| match i { + PreparedItem::Ready(r) if r.path.ends_with(name) => Some(r.sidecar.as_ref().and_then(|sc| sc.rating)), + _ => None, + }) + }; + assert_eq!((rating("a.jpg"), rating("c.jpg"), rating("d.jpg")), (Some(None), Some(Some(4)), Some(None))); + assert!(prepared.items.iter().any(|i| matches!(i, PreparedItem::Failed(p, _) if p.ends_with("broken.jpg")))); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index def0f1ccbd..6ea505990a 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -1,5 +1,5 @@ use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock}; -use super::files::{Seen, expand_knowing, probe_all, reusable_probes}; +use super::files::{Seen, expand_knowing, probe_all, reusable_probes, sidecars_of}; use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted}; use super::{HashMap, ListedFolders, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; @@ -324,6 +324,19 @@ impl ImportJob { library.as_ref(), todo.iter().zip(&probed).filter_map(|(path, info)| info.as_ref().ok().map(|i| (path.as_str(), i.kind))), ); + // The sidecar of every file that was probed, looked up for the batch at once: each is a few + // names asked of the disk, which on a network share made a folder of thousands of photos wait + // a round trip per name, one name after another. + let asked: Vec<&str> = todo.iter().zip(&probed).filter(|(_, p)| p.is_ok()).map(|(f, _)| f.as_str()).collect(); + // (a file whose content the library has is skipped below as a duplicate: it asks the disk nothing) + let known: std::collections::HashSet<&str> = todo + .iter() + .zip(&probed) + .filter(|(_, p)| !opts.local && 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 = + sidecars_of(&asked, cancel, |f| if known.contains(f) { None } else { self.listed.find_for_import(&stems, self.naming, f) }).into_iter(); // Files are planned one by one, in order (duplicates, sidecars, names, folders); their // copies or moves — the slow part, reading and writing every byte and verifying it — are // collected and run on several threads (issue #367), then their outcomes take their places. @@ -341,6 +354,8 @@ impl ImportJob { continue; } }; + // (this file's place in the lookups above: files that failed to probe have none) + let found_sidecar = found.next().flatten(); // a copy of a file whose transfer is still pending: a duplicate only if that one succeeds if !opts.local && let Some(h) = &info.content_hash @@ -360,10 +375,7 @@ impl ImportJob { let packet = if duplicate_of.is_some() && info.captured.is_some() { None } else { - self.listed - .find_for_import(&stems, self.naming, &path) - .and_then(|f| std::fs::read_to_string(f).ok()) - .or_else(|| info.xmp.clone().filter(|_| raw)) + found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).or_else(|| info.xmp.clone().filter(|_| raw)) }; let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { diff --git a/crates/engine/src/import/listed_folders.rs b/crates/engine/src/import/listed_folders.rs index 8d79732aa7..d8eac72c40 100644 --- a/crates/engine/src/import/listed_folders.rs +++ b/crates/engine/src/import/listed_folders.rs @@ -45,6 +45,10 @@ pub struct ListedFolders { pub(crate) asked: AtomicUsize, /// How many folders' times were looked at (for the tests). pub(crate) looked: AtomicUsize, + /// The threads that looked a sidecar up for an import (for the tests: the lookups of a batch are + /// not made one after another by the thread that plans it). + #[cfg(test)] + pub(crate) lookers: Mutex>, } impl ListedFolders { @@ -78,7 +82,10 @@ impl ListedFolders { self.folders.insert(folder.to_path_buf(), listed); } - /// A new batch of files is handled: look at the folders' times again. + /// A new batch of files is handled: look at the folders' times again. A folder's time is looked at + /// once per batch, by the first lookup in it (a look for each photo would cost the round trip each + /// that the listing saves), so a sidecar added there while the batch is handled is not seen until + /// the next batch. pub(crate) fn new_batch(&self) { self.checked.lock().unwrap_or_else(|e| e.into_inner()).clear(); } @@ -139,6 +146,8 @@ impl ListedFolders { /// there is none: a file that owns its stem sidecar ([`crate::sidecar::ImportStems`]) is looked /// up as [`ListedFolders::find`] does; one that doesn't reads only its own `.xmp`. pub(crate) fn find_for_import(&self, stems: &crate::sidecar::ImportStems, naming: SidecarNaming, original: &str) -> Option { + #[cfg(test)] + self.lookers.lock().unwrap_or_else(|e| e.into_inner()).insert(std::thread::current().id()); if stems.owns(original) { return self.find(original, naming); } diff --git a/crates/engine/src/import/tests_listed_folders.rs b/crates/engine/src/import/tests_listed_folders.rs index 169922add9..5c7e7f4130 100644 --- a/crates/engine/src/import/tests_listed_folders.rs +++ b/crates/engine/src/import/tests_listed_folders.rs @@ -289,6 +289,32 @@ fn a_batch_looks_at_each_of_its_folders_once() { let _ = std::fs::remove_dir_all(&root); } +/// Given photos named one by one (no listing to rule a sidecar out), when a batch of them is +/// handled, then their sidecars are not looked up one after another by the thread that plans the +/// batch: each is a few names asked of the disk, a round trip apiece on a network share, so the +/// lookups of a batch run together (`sidecars_of`). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_batchs_sidecars_are_looked_up_off_the_thread_that_plans_it() { + let root = scratch("lookers"); + let files: Vec = (0..6) + .map(|n| { + let f = root.join(format!("IMG_{n:04}.jpg")); + std::fs::write(&f, b"x").unwrap(); + f.to_string_lossy().to_string() + }) + .collect(); + let mut job = job(SidecarNaming::Stem); + let prepared = job.prepare_files(files, &AtomicBool::new(false)); + assert_eq!(prepared.items.len(), 6); + assert_eq!(job.listed.asked.load(Relaxed), 6, "each photo's sidecar is asked of the disk"); + let lookers = job.listed.lookers.lock().unwrap(); + assert!(!lookers.is_empty(), "no lookups were made"); + assert!(!lookers.contains(&std::thread::current().id()), "a lookup was made by the thread that plans the batch, one after another"); + drop(lookers); + let _ = std::fs::remove_dir_all(&root); +} + /// Given a folder listed in the same clock tick as its files were made, when a sidecar is /// written into it right after the listing and the folder's time reads as it did before (a /// volume that keeps folder times to the second or two), then the import still reads it: a