diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 4274e689c9..7732b855ba 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1325,16 +1325,22 @@ pub fn specs() -> Vec { "Review Import", [], None, - "{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned} — nothing is added", + "{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned, scanLimited: bool (the folder walk stopped at its scan limit: there may be more photos), skipped: {unreadable (folders that could not be listed), unsupported (files in the folders that are not a supported photo type, XMP sidecars not counted; a file named in paths is always tried)}} — nothing is added", always, |s, p| { let paths = strs(p, "paths"); if paths.is_empty() { return Err(bad("library.importPreview", "no paths")); } - let c = crate::import::scan(s, &paths); - let dups = c.iter().filter(|c| c.duplicate.is_some()).count(); - Ok(json!({"scanned": c.len(), "duplicates": dups, "candidates": c})) + let out = crate::import::scan_report(s, &paths); + let dups = out.candidates.iter().filter(|c| c.duplicate.is_some()).count(); + Ok(json!({ + "scanned": out.candidates.len(), + "duplicates": dups, + "candidates": out.candidates, + "scanLimited": out.truncated, + "skipped": {"unreadable": out.unreadable, "unsupported": out.unsupported}, + })) } ), cmd!( diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index b4ee766048..cd3123e522 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -46,7 +46,8 @@ 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}; pub use files::{ - EXTENSIONS, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_within, is_supported, launch_deadline, launch_path, launch_path_until, + EXTENSIONS, Expansion, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_report, expand_within, is_supported, launch_deadline, + launch_path, launch_path_until, }; pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with}; #[cfg(test)] @@ -54,7 +55,8 @@ use job::PreparedItem; pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with}; pub(crate) use scan::scan_files; pub use scan::{ - ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan, scan_with, + ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan, + scan_report, scan_with, }; #[cfg(test)] use scan::{library_files, library_hashes}; diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index 39c55f56ff..d6a9c6eea9 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -24,6 +24,11 @@ pub fn is_supported(path: &Path) -> bool { path.extension().is_some_and(|e| EXTENSIONS.contains(&e.to_string_lossy().to_lowercase().as_str())) } +/// An XMP sidecar (`.xmp`, any letter case): read with its photo on import, never a photo itself. +fn is_xmp_sidecar(path: &Path) -> bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp")) +} + /// The web file picker's accept list, derived from [`EXTENSIONS`]. Each extension /// is listed in both cases: browsers' `accept` matching is case-insensitive per /// spec, but some implementations (e.g. Windows/Edge) match case-sensitively and @@ -78,19 +83,57 @@ pub(crate) fn expand_noting( paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, - mut note: Option, + note: Option, ) -> (Vec, bool) { - let mut out = Vec::new(); - let mut truncated = false; + let e = expand_report_noting(paths, skip, limits, note); + (e.files, e.truncated) +} + +/// What expanding import sources found, and what the walks left out ([`expand_report`]), so a +/// review can say that it did not see everything. +#[derive(Clone, Debug, Default)] +pub struct Expansion { + /// Supported files, folders walked recursively and deduplicated by path, in walk order. + pub files: Vec, + /// A walk stopped at a depth or entry bound: there may be more files. + pub truncated: bool, + /// Folders whose contents couldn't be listed (permissions, a folder that vanished or went offline). + pub unreadable: usize, + /// Files found inside the folders walked that are not a supported type (see [`is_supported`]), + /// not counting XMP sidecars, which the import reads with their photos. A file named directly + /// is attempted whatever its extension and is never counted here. Both counts add up over the + /// sources, so a folder named twice (or inside another source) counts twice. + pub unsupported: usize, +} + +/// [`expand_within`] keeping the walks' diagnostics. A walk that stops at a bound is logged here +/// (once per folder), as it always was. +pub fn expand_report(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits) -> Expansion { + expand_report_noting(paths, skip, limits, None) +} + +/// ([`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 { + 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() { + // XMP sidecars are read with their photos, not skipped: they are left out of the count + let mut sidecars = 0usize; + let keep = |f: &Path| { + let keep = is_supported(f); + if !keep && is_xmp_sidecar(f) { + sidecars = sidecars.saturating_add(1); + } + keep + }; let w = match note.as_mut() { - Some(note) => crate::walk::files_in_noting(p, skip, limits, is_supported, &mut **note), - None => crate::walk::files_in(p, skip, limits, is_supported), + Some(note) => crate::walk::files_in_noting(p, skip, limits, keep, &mut **note), + None => crate::walk::files_in(p, skip, limits, keep), }; if w.truncated { log::warn!( @@ -101,16 +144,18 @@ pub(crate) fn expand_noting( limits.max_depth ); } - truncated |= w.truncated; - out.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string())); + out.truncated |= w.truncated; + out.unreadable = out.unreadable.saturating_add(w.unreadable); + out.unsupported = out.unsupported.saturating_add(w.skipped.saturating_sub(sidecars)); + out.files.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string())); } else { // explicitly named files are attempted even with an unknown extension (sniffed) - out.push(p.to_string_lossy().to_string()); + out.files.push(p.to_string_lossy().to_string()); } } let mut seen = std::collections::HashSet::new(); - out.retain(|p| seen.insert(p.clone())); - (out, truncated) + out.files.retain(|p| seen.insert(p.clone())); + out } /// What a path given on the command line at launch becomes ([`launch_path`]). diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index ad247c22c6..aaae16c7a4 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -1,4 +1,4 @@ -use super::files::{Seen, expand, is_supported, probe_all, reusable_probes}; +use super::files::{Seen, expand, expand_report, is_supported, probe_all, reusable_probes}; use super::types::ImportCandidate; use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; @@ -77,6 +77,12 @@ pub struct ScanProgress { pub struct ScanOutput { pub candidates: Vec, pub probes: HashMap, + /// A folder walk stopped at a depth or entry bound: there may be more photos ([`Expansion`]). + pub truncated: bool, + /// Folders whose contents couldn't be listed. + pub unreadable: usize, + /// Files inside the folders that are not a supported photo type (XMP sidecars not counted). + pub unsupported: usize, } impl ScanInput { @@ -283,20 +289,32 @@ fn browse_order_until(files: &mut [String], sort: &lightcraft_catalog::Sort, can /// against the library and earlier candidates). Nothing is added; the probes are kept for the /// import that follows. pub fn scan(s: &mut Session, paths: &[String]) -> Vec { + scan_report(s, paths).candidates +} + +/// [`scan`] keeping what the walks left out. The probes are already kept in the session for the +/// import that follows, so `probes` of the output is empty. +pub fn scan_report(s: &mut Session, paths: &[String]) -> ScanOutput { let (input, paths) = ScanInput::new(s, paths); - let out = scan_with(input, &paths, &ScanProgress::default()); - s.import_probes = out.probes; - out.candidates + let mut out = scan_with(input, &paths, &ScanProgress::default()); + s.import_probes = std::mem::take(&mut out.probes); + out } /// [`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 files = expand(paths, input.skip.as_deref()); - scan_files(input, files, progress) + let expansion = expand_report(paths, input.skip.as_deref(), crate::walk::Limits::default()); + let mut out = scan_files(input, expansion.files, progress); + out.truncated = expansion.truncated; + out.unreadable = expansion.unreadable; + out.unsupported = expansion.unsupported; + out } -/// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]). +/// [`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`]). 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); @@ -357,5 +375,6 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc } out.push(c); } - ScanOutput { candidates: out, probes: kept } + // (the walks' diagnostics are [`scan_with`]'s: these files were found already) + ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0 } } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 54f3382014..49176077fb 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -2172,6 +2172,216 @@ fn expand_stops_at_the_walk_limits() { let _ = std::fs::remove_dir_all(&d); } +/// `levels` folders named `d` nested below `root` (created); the innermost one's path. +fn nested(root: &Path, levels: usize) -> std::path::PathBuf { + let mut dir = root.to_path_buf(); + for _ in 0..levels { + dir = dir.join("d"); + } + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Expanding folders reports what the walks left out — files of an unsupported type, a walk that +/// stopped at a bound — and returns the same files as `expand_within`; a file named on its own is +/// attempted whatever its extension and is not counted as unsupported. +#[test] +fn expand_report_counts_what_the_walks_left_out() { + use crate::import::{expand_report, expand_within}; + let d = temp_dir("expand-report"); + write_png(&d.join("a.png"), 1); + write_png(&d.join("sub/b.png"), 2); + std::fs::write(d.join("notes.txt"), "x").unwrap(); + std::fs::write(d.join("sub/readme.md"), "x").unwrap(); + std::fs::write(d.join("sub/.hidden.txt"), "x").unwrap(); + let named = temp_dir("expand-report-named"); + std::fs::write(named.join("odd.dat"), "x").unwrap(); + let paths = [d.to_string_lossy().to_string(), named.join("odd.dat").to_string_lossy().to_string()]; + let limits = crate::walk::Limits::default(); + + let e = expand_report(&paths, None, limits); + assert_eq!(e.files.len(), 3, "both photos and the named file: {:?}", e.files); + assert_eq!((e.unsupported, e.unreadable, e.truncated), (2, 0, false), "notes.txt and readme.md; the hidden file is not counted: {e:?}"); + assert_eq!(expand_within(&paths, None, limits), (e.files.clone(), false), "expand_within is the same walk"); + + // stopping one level down: the second folder is never listed, so its files are not counted + let e = expand_report(&paths[..1], None, crate::walk::Limits { max_depth: 1, max_entries: 1000 }); + assert_eq!((e.files.len(), e.unsupported, e.truncated), (1, 1, true), "{e:?}"); + let _ = std::fs::remove_dir_all(&d); + let _ = std::fs::remove_dir_all(&named); +} + +/// A scan says that its folder walk stopped at the depth limit (there may be more photos), and +/// does not when the tree ends within it. +#[test] +fn scan_with_reports_a_walk_that_stopped_at_a_bound() { + use crate::import::{ScanInput, ScanProgress, scan_with}; + let scan = |dir: &Path| { + let mut s = Session::new().with_fs(); + let (input, paths) = ScanInput::new(&mut s, &[dir.to_string_lossy().to_string()]); + scan_with(input, &paths, &ScanProgress::default()) + }; + // the deepest folder a walk lists is one level above the limit; one more folder is never entered + let cut = temp_dir("scan-cut"); + write_png(&cut.join("top.png"), 1); + write_png(&nested(&cut, crate::walk::MAX_DEPTH - 1).join("last.png"), 2); + nested(&cut, crate::walk::MAX_DEPTH); + let out = scan(&cut); + assert_eq!(out.candidates.len(), 2, "what was reached is still returned"); + assert_eq!((out.truncated, out.unreadable, out.unsupported), (true, 0, 0)); + + let whole = temp_dir("scan-whole"); + write_png(&whole.join("top.png"), 1); + write_png(&nested(&whole, crate::walk::MAX_DEPTH - 1).join("last.png"), 2); + let out = scan(&whole); + assert_eq!(out.candidates.len(), 2); + assert_eq!((out.truncated, out.unreadable, out.unsupported), (false, 0, 0)); + let _ = std::fs::remove_dir_all(&cut); + let _ = std::fs::remove_dir_all(&whole); +} + +/// A folder this process is not allowed to list, until it is dropped (Unix: no permissions; +/// Windows: a deny entry for Everyone on listing it). +struct Unlistable(std::path::PathBuf); + +impl Unlistable { + /// `None` when the folder can still be listed (the super-user ignores permissions) or the + /// means to deny it is missing: the test then has nothing to check. + fn new(dir: &Path) -> Option { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o000)).ok()?; + } + #[cfg(windows)] + { + let denied = std::process::Command::new("icacls").arg(dir).args(["/deny", "*S-1-1-0:(RD)"]).output(); + if !denied.is_ok_and(|o| o.status.success()) { + return None; + } + } + // from here the folder is restored on drop, whatever the test does + let guard = Unlistable(dir.to_path_buf()); + std::fs::read_dir(dir).is_err().then_some(guard) + } +} + +impl Drop for Unlistable { + fn drop(&mut self) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755)); + } + #[cfg(windows)] + { + let _ = std::process::Command::new("icacls").arg(&self.0).args(["/remove:d", "*S-1-1-0"]).output(); + } + } +} + +/// A folder the scan can't list is counted — by the scan and by `library.importPreview` — and the +/// photos around it are still found. +#[test] +fn an_unlistable_folder_is_reported_by_the_scan() { + use crate::import::{ScanInput, ScanProgress, scan_with}; + let src = temp_dir("unlistable"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("locked").join("b.png"), 2); + let Some(locked) = Unlistable::new(&src.join("locked")) else { + eprintln!("skipped: this process can still list a folder it was denied"); + let _ = std::fs::remove_dir_all(&src); + return; + }; + let mut s = Session::new().with_fs(); + let (input, paths) = ScanInput::new(&mut s, &[src.to_string_lossy().to_string()]); + let out = scan_with(input, &paths, &ScanProgress::default()); + assert_eq!(out.candidates.len(), 1, "only the photo outside the folder"); + assert_eq!((out.unreadable, out.unsupported, out.truncated), (1, 0, false)); + let r = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["skipped"].clone()), (json!(1), json!({"unreadable": 1, "unsupported": 0})), "{r}"); + drop(locked); + let _ = std::fs::remove_dir_all(&src); +} + +/// `library.importPreview` reports the walk's diagnostics next to the keys it always returned, and +/// still leaves its probes for the import that follows. +#[test] +fn import_preview_reports_what_the_scan_skipped() { + let src = temp_dir("preview-diag"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("sub/b.png"), 2); + std::fs::write(src.join("notes.txt"), b"not a photo").unwrap(); + std::fs::write(src.join("sub/readme.md"), b"x").unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["duplicates"].clone()), (json!(2), json!(0)), "{r}"); + assert_eq!(ids(&r, "candidates"), 2, "{r}"); + assert_eq!(r["scanLimited"], false, "{r}"); + assert_eq!(r["skipped"], json!({"unreadable": 0, "unsupported": 2}), "notes.txt and readme.md are reported: {r}"); + for f in [src.join("a.png"), src.join("sub").join("b.png")] { + let key = f.to_string_lossy().to_string(); + assert!(s.import_probes.contains_key(&key), "the probe of {key} is kept for the import: {:?}", s.import_probes.keys()); + } + // a second preview reuses them: a file that has not changed is not read again + let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (counted, probe) = (reads.clone(), s.media.file_probe.clone().unwrap()); + s.media.file_probe = Some(std::sync::Arc::new(move |path: &str| { + counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + probe(path) + })); + let again = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(again["scanned"], 2, "{again}"); + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 0, "the first preview's probes are reused"); + + // a file named on its own is tried, not reported as skipped + let r = s.execute("library.importPreview", &json!({"paths": [src.join("notes.txt").to_string_lossy()]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["skipped"]["unsupported"].clone()), (json!(1), json!(0)), "{r}"); + + // a walk that stopped at the depth limit says so + let deep = temp_dir("preview-deep"); + write_png(&deep.join("top.png"), 3); + nested(&deep, crate::walk::MAX_DEPTH); + let r = s.execute("library.importPreview", &json!({"paths": [deep.to_string_lossy()]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["scanLimited"].clone()), (json!(1), json!(true)), "{r}"); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&deep); +} + +/// XMP sidecars are read with their photos, so they are not "skipped": the expansion, the scan and +/// `library.importPreview` count them (in any letter case, in subfolders too) as nothing, and still +/// count every other file that is not a photo. +#[test] +fn xmp_sidecars_are_not_counted_as_unsupported() { + use crate::import::{ScanInput, ScanProgress, expand_report, scan_with}; + let mut s = Session::new().with_fs(); + // sidecars beside a photo, a sidecar without one, in any case, one deeper; plus a text file + let mixed = temp_dir("sidecars-mixed"); + write_png(&mixed.join("a.png"), 1); + std::fs::write(mixed.join("a.xmp"), b"x").unwrap(); + std::fs::write(mixed.join("b.XMP"), b"x").unwrap(); + std::fs::create_dir_all(mixed.join("sub")).unwrap(); + std::fs::write(mixed.join("sub").join("c.Xmp"), b"x").unwrap(); + std::fs::write(mixed.join("c.txt"), b"x").unwrap(); + // only photos and sidecars + let tidy = temp_dir("sidecars-only"); + write_png(&tidy.join("a.png"), 2); + std::fs::write(tidy.join("a.xmp"), b"x").unwrap(); + std::fs::write(tidy.join("b.XMP"), b"x").unwrap(); + for (dir, unsupported) in [(&mixed, 1usize), (&tidy, 0)] { + let path = dir.to_string_lossy().to_string(); + let e = expand_report(std::slice::from_ref(&path), None, crate::walk::Limits::default()); + assert_eq!((e.files.len(), e.unsupported), (1, unsupported), "expand_report {e:?}"); + let (input, paths) = ScanInput::new(&mut s, std::slice::from_ref(&path)); + let out = scan_with(input, &paths, &ScanProgress::default()); + assert_eq!((out.candidates.len(), out.unsupported), (1, unsupported), "scan_with"); + let r = s.execute("library.importPreview", &json!({"paths": [path]})).unwrap(); + assert_eq!((r["scanned"].clone(), r["skipped"]["unsupported"].clone()), (json!(1), json!(unsupported)), "{r}"); + } + let _ = std::fs::remove_dir_all(&mixed); + let _ = std::fs::remove_dir_all(&tidy); +} + /// Raw containers LightCraft cannot decode but shows by their embedded JPEG are picked up from a folder /// (the extensions are in `import::EXTENSIONS`; the files differ so none is a duplicate) and import as preview only. #[test] diff --git a/crates/engine/src/walk.rs b/crates/engine/src/walk.rs index db024f7098..f0c4033dd6 100644 --- a/crates/engine/src/walk.rs +++ b/crates/engine/src/walk.rs @@ -41,6 +41,13 @@ pub struct Walked { pub truncated: bool, /// Directory entries looked at. pub entries: usize, + /// Folders whose contents couldn't be listed (permissions, a folder that vanished or went + /// offline): the walk skipped them and carried on. Only a refused listing counts, not an + /// entry inside a listed folder that couldn't be examined. + pub unreadable: usize, + /// Files the walk reached that `keep` refused. Hidden entries and the skipped folder are left + /// out silently and not counted. + pub skipped: usize, } /// Whether the entry has a dot-prefixed name or a Windows or macOS hidden attribute. @@ -93,7 +100,8 @@ pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, Entr /// 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 -/// at `limits` (see [`Walked::truncated`]). Unreadable folders are skipped. +/// at `limits` (see [`Walked::truncated`]). Unreadable folders are skipped and counted +/// ([`Walked::unreadable`]), as are the files `keep` refuses ([`Walked::skipped`]). pub fn files_in(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool) -> Walked { walk(root, skip, limits, keep, |_| true, None) } @@ -140,6 +148,8 @@ fn walk( if !is_dir { if keep(&path) { out.files.push(path); + } else { + out.skipped = out.skipped.saturating_add(1); } continue; } @@ -150,7 +160,10 @@ fn walk( out.truncated = true; continue; } - let Ok(rd) = std::fs::read_dir(&path) else { continue }; + let Ok(rd) = std::fs::read_dir(&path) else { + out.unreadable = out.unreadable.saturating_add(1); + continue; + }; let mut children: Vec<(PathBuf, bool)> = Vec::new(); // (the folder's listing, for who asked for it; all of it unless something below says otherwise) let mut listed = note.is_some().then(Vec::new); @@ -348,6 +361,50 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// Files the caller's `keep` refuses are counted (an import reports most of them as + /// unsupported), and so are only those: hidden files and the skipped folder are left out without a count, and + /// the files returned are the same ones in the same order. + #[test] + fn unkept_files_are_counted_as_skipped() { + let d = tmp("skipped"); + for f in ["a.jpg", "b.txt", "c.png", "sub/d.jpg", "sub/e.md", ".hidden.txt", "lib/l.txt"] { + let p = d.join(f); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, b"x").unwrap(); + } + let lib = d.join("lib"); + let w = files_in(&d, Some(&lib), Limits::default(), |p| p.extension().is_some_and(|e| e == "jpg")); + let rel: Vec = w.files.iter().map(|p| p.strip_prefix(&d).unwrap().to_string_lossy().replace('\\', "/")).collect(); + assert_eq!(rel, ["a.jpg", "sub/d.jpg"]); + assert_eq!((w.skipped, w.unreadable, w.truncated), (3, 0, false), "{w:?}"); + let _ = std::fs::remove_dir_all(&d); + } + + /// A folder that is gone by the time the walk reaches it (here removed while an earlier file is + /// looked at, as an unplugged disk or a deleted folder would be) is counted as unreadable; + /// the walk carries on and still returns the other files. + #[test] + fn a_folder_that_vanishes_is_counted_as_unreadable() { + let d = tmp("vanished"); + for f in ["a.jpg", "b/b.jpg", "c.jpg"] { + let p = d.join(f); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, b"x").unwrap(); + } + let gone = d.join("b"); + // `a.jpg` is looked at before the folder `b` is entered + let w = files_in(&d, None, Limits::default(), |p| { + if p.ends_with("a.jpg") { + let _ = std::fs::remove_dir_all(&gone); + } + true + }); + let rel: Vec = w.files.iter().map(|p| p.strip_prefix(&d).unwrap().to_string_lossy().replace('\\', "/")).collect(); + assert_eq!(rel, ["a.jpg", "c.jpg"]); + assert_eq!((w.unreadable, w.skipped, w.truncated), (1, 0, false), "{w:?}"); + let _ = std::fs::remove_dir_all(&d); + } + /// Folder imports must not revisit the user's own library through symlinks /// or through an alias to the library's parent. #[cfg(unix)] diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index e65ad627ef..d642bc85ae 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -320,5 +320,7 @@ "Panel layout could not be restored: {error}": "Rozložení panelů se nepodařilo obnovit: {error}", "Panel move was not applied: {error}": "Přesun panelu nebyl použit: {error}", "{name} is installed": "{name} je nainstalován", - "{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto" + "{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto", + "{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 95f52edb1b..5cb9ba0e45 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2449,5 +2449,6 @@ "Set up name suggestions…": "Nastavit návrhy jmen…", "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", - "Bottom bar": "Dolní lišta" + "Bottom bar": "Dolní lišta", + "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 70ced17114..8c119e8ec9 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -161,6 +161,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "{n} Änderung(en) konnten nicht auf den Datenträger geschrieben werden{0:.0}: {e}\nWenn du jetzt beendest, gehen sie verloren.{1:.0}", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} Änderung(en) nur im Arbeitsspeicher, nicht auf dem Datenträger gespeichert{0:.0}: {e}\nLightCraft versucht es automatisch erneut; wenn du jetzt beendest, gehen sie verloren.{1:.0}", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "{n} Änderung(en) nur im Arbeitsspeicher gespeichert{:.0}: {e} – LightCraft versucht es erneut", + "{n} file{} skipped (not a supported photo type)": "Übersprungene Dateien (kein unterstützter Fototyp): {n}{:.0}", + "{n} folder{} could not be read": "Ordner, die nicht gelesen werden konnten: {n}{:.0}", "{n} found · {sel} selected": "{n} gefunden · {sel} ausgewählt", "{n} photos": "Fotos: {n}", "{n} photos in {} are hidden by the filters above": "{n} Fotos in {} werden durch die obigen Filter ausgeblendet", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index c05a66246b..12dae2c870 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2087,6 +2087,7 @@ "Metadata read": "Metadaten gelesen", "Failed": "Fehlgeschlagen", "Stopped": "Angehalten", + "Stopped at the scan limit: there may be more photos": "Am Suchlimit angehalten: Es gibt möglicherweise weitere Fotos", "Stopped by an error (see the log)": "Durch einen Fehler angehalten (siehe Protokoll)", "Not saved": "Nicht gespeichert", "A folder is being synchronized": "Ein Ordner wird gerade synchronisiert", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 7b697e946b..2a001f3891 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -161,6 +161,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Cambios que no se pudieron escribir en el disco: {n}{0:.0}: {e}\nSi se sale ahora, se perderán.{1:.0}", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "Cambios guardados en memoria, pero no escritos en el disco: {n}{0:.0}: {e}\nLightCraft vuelve a intentarlo automáticamente; si se sale ahora, se perderán.{1:.0}", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "Cambios guardados solo en memoria: {n}{:.0}: {e}; LightCraft volverá a intentarlo", + "{n} file{} skipped (not a supported photo type)": "Archivos omitidos (no son de un tipo de foto compatible): {n}{:.0}", + "{n} folder{} could not be read": "Carpetas que no se pudieron leer: {n}{:.0}", "{n} found · {sel} selected": "{n} encontradas · {sel} seleccionadas", "{n} photos": "{n} fotos", "{n} photos in {} are hidden by the filters above": "Los filtros de arriba ocultan {n} fotos en {}", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index bacf411182..b4aaf400a8 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2114,6 +2114,7 @@ "Metadata read": "Metadatos leídos", "Failed": "Con errores", "Stopped": "Detenido", + "Stopped at the scan limit: there may be more photos": "Se detuvo en el límite de exploración: puede haber más fotos", "Stopped by an error (see the log)": "Detenido por un error (ver el registro)", "Not saved": "Sin guardar", "A folder is being synchronized": "Se está sincronizando una carpeta", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 720519a1cc..12cdf13df8 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -317,5 +317,7 @@ "Panel layout could not be restored: {error}": "Paneelien asettelua ei voitu palauttaa: {error}", "Panel move was not applied: {error}": "Paneelin siirtoa ei otettu käyttöön: {error}", "{name} is installed": "{name} on asennettu", - "{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä" + "{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä", + "{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 43be15d273..d5dc27d8c0 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2360,5 +2360,6 @@ "Set up name suggestions…": "Määritä nimiehdotukset…", "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", - "Bottom bar": "Alapalkki" + "Bottom bar": "Alapalkki", + "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 3aa2166971..cc78f8331e 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -161,6 +161,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Impossible d’écrire {n} modification{} sur le disque : {e}\nSi vous quittez maintenant, {} seront perdues.", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} modification{} enregistrée(s) en mémoire mais non écrite(s) sur le disque : {e}\nLightCraft réessaiera automatiquement ; quitter maintenant entraînerait la perte de {}.", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "{n} modification{} enregistrée(s) en mémoire mais non écrite(s) sur le disque : {e} — LightCraft réessaiera.", + "{n} file{} skipped (not a supported photo type)": "Fichiers ignorés (type de photo non pris en charge) : {n}{:.0}", + "{n} folder{} could not be read": "Dossiers illisibles : {n}{:.0}", "{n} found · {sel} selected": "{n} trouvé(s) · {sel} sélectionné(s)", "{n} photos": "{n} photos", "{n} photos in {} are hidden by the filters above": "Les filtres ci-dessus masquent {n} photos dans {}", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 974347cc4d..8406d3e2ae 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1922,6 +1922,7 @@ "Metadata read": "Métadonnées lues", "Failed": "Échecs", "Stopped": "Arrêté", + "Stopped at the scan limit: there may be more photos": "Arrêt à la limite d'analyse : il peut y avoir d'autres photos", "Stopped by an error (see the log)": "Arrêté par une erreur (voir le journal)", "Not saved": "Non enregistré", "A folder is being synchronized": "Un dossier est en cours de synchronisation", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 22eb2d49e3..85c06ed3e1 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -320,5 +320,7 @@ "{name} is installed and in use: face recognition is on": "{name} sudah terinstal dan digunakan: pengenalan wajah aktif", "Creates {stacks} stack{} from {photos} of {scope}": "Membuat {stacks} tumpukan dari {photos} foto ({scope}){:.0}", "{n} selected photo{} · {pages} page{}": "{n} foto dipilih · {pages} halaman{:.0}{:.0}", - "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}" + "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}", + "{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 70999cc4f5..8805697868 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2374,5 +2374,6 @@ "Set up name suggestions…": "Siapkan saran nama…", "Top bar": "Bilah atas", "Tool strip": "Bilah alat", - "Bottom bar": "Bilah bawah" + "Bottom bar": "Bilah bawah", + "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 729c27a0f1..c3227a1aa4 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -320,5 +320,7 @@ "Panel layout could not be restored: {error}": "Non è stato possibile ripristinare la disposizione dei pannelli: {error}", "Panel move was not applied: {error}": "Lo spostamento del pannello non è stato applicato: {error}", "{name} is installed": "{name} è installato", - "{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo" + "{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo", + "{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index cf5082aba1..617b0d9fea 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2567,5 +2567,6 @@ "Unit": "Unità", "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", - "Bottom bar": "Barra inferiore" + "Bottom bar": "Barra inferiore", + "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index b25ef53978..2cf2c0f83a 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -96,6 +96,8 @@ "{name} On": "{name}を有効にする", "{name} — double-click to reset it": "{name}:ダブルクリックでリセット", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n}件の変更{:.0}をディスクに保存できません:{e}\n自動で再試行します。終了すると変更が失われます{:.0}", + "{n} file{} skipped (not a supported photo type)": "スキップしたファイル(非対応の写真形式):{n}個{:.0}", + "{n} folder{} could not be read": "読み取れなかったフォルダー:{n}個{:.0}", "{n} found · {sel} selected": "{n}枚検出・{sel}枚選択", "{n} photos": "{n}枚", "{n} photos in {} are hidden by the filters above": "{}の{n}枚は上のフィルターで非表示になっています", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 3a9c49e79a..9178aad528 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1935,6 +1935,7 @@ "Metadata read": "メタデータ読み込み", "Failed": "失敗", "Stopped": "停止しました", + "Stopped at the scan limit: there may be more photos": "スキャンの上限で停止しました。ほかにも写真がある可能性があります", "Stopped by an error (see the log)": "エラーで停止しました(ログを参照)", "Not saved": "保存されていません", "A folder is being synchronized": "フォルダを同期中です", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 612178c0e8..c058aa9b04 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -323,5 +323,7 @@ "Panel layout could not be restored: {error}": "პანელების განლაგების აღდგენა ვერ მოხერხდა: {error}", "Panel move was not applied: {error}": "პანელის გადატანა არ შესრულდა: {error}", "{name} is installed": "{name} დაინსტალირებულია", - "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია" + "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია", + "{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index e3a773e93f..e7e3e6e9c5 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3670,5 +3670,6 @@ "Top bar": "ზედა ზოლი", "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", + "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index e5d3e8d068..3ca9d0503d 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -320,5 +320,7 @@ "Panel layout could not be restored: {error}": "Nie udało się przywrócić układu paneli: {error}", "Panel move was not applied: {error}": "Przeniesienie panelu nie zostało zastosowane: {error}", "{name} is installed": "{name} jest zainstalowany", - "{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone" + "{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone", + "{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 44719aacbf..27eca8dfc1 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2325,5 +2325,6 @@ "Set up name suggestions…": "Skonfiguruj propozycje imion…", "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", - "Bottom bar": "Dolny pasek" + "Bottom bar": "Dolny pasek", + "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 83d5a37518..5ac3194d78 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -121,6 +121,8 @@ "{name} On": "{name} ativado", "{name} — double-click to reset it": "{name} — clique duas vezes para redefinir", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} alteração{:.0} salva na memória mas não gravada no disco: {e}\nO LightCraft tenta novamente automaticamente; encerrar agora perderia {}.", + "{n} file{} skipped (not a supported photo type)": "Arquivos ignorados (tipo de foto sem suporte): {n}{:.0}", + "{n} folder{} could not be read": "Pastas que não puderam ser lidas: {n}{:.0}", "{n} found · {sel} selected": "{n} encontradas · {sel} selecionadas", "{n} photos": "{n} fotos", "{n} photos in {} are hidden by the filters above": "{n} fotos em {} estão ocultas pelos filtros acima", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 47c8098394..82d695bba8 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1933,6 +1933,7 @@ "Metadata read": "Metadados lidos", "Failed": "Com falha", "Stopped": "Interrompido", + "Stopped at the scan limit: there may be more photos": "Parou no limite da verificação: pode haver mais fotos", "Stopped by an error (see the log)": "Interrompido por um erro (veja o log)", "Not saved": "Não salvo", "A folder is being synchronized": "Uma pasta está sendo sincronizada", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 02f8126d96..0bcc2d98f8 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -166,6 +166,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Изменений не удалось записать на диск: {n}{0:.0}: {e}\nЕсли выйти сейчас, они будут потеряны.{1:.0}", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "Не записано на диск, хранится только в памяти (изменений: {n}): {e}\nLightCraft повторяет попытку автоматически; при выходе сейчас они будут потеряны.{:.0}{:.0}", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "Изменений сохранено в памяти, но не записано на диск: {n}{:.0}: {e} — LightCraft повторит попытку", + "{n} file{} skipped (not a supported photo type)": "Пропущено файлов (неподдерживаемый тип фото): {n}{:.0}", + "{n} folder{} could not be read": "Папок, которые не удалось прочитать: {n}{:.0}", "{n} found · {sel} selected": "Найдено: {n} · выбрано: {sel}", "{n} photos": "Фото: {n}", "{n} photos in {} are hidden by the filters above": "Фильтры выше скрывают фото в разделе «{}»: {n}", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 4bec3def29..a34312643d 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1862,6 +1862,7 @@ "Metadata read": "Метаданные прочитаны", "Failed": "Ошибки", "Stopped": "Остановлено", + "Stopped at the scan limit: there may be more photos": "Остановлено на пределе сканирования: возможно, есть другие фото", "Stopped by an error (see the log)": "Остановлено из-за ошибки (см. журнал)", "Not saved": "Не сохранено", "A folder is being synchronized": "Папка синхронизируется", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 7d40388d1b..d6619228aa 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -320,5 +320,7 @@ "{name} is installed and in use: face recognition is on": "{name} är installerad och används: ansiktsigenkänning är på", "Creates {stacks} stack{} from {photos} of {scope}": "Skapar staplar: {stacks} · foton: {photos} av {scope}{:.0}", "{n} selected photo{} · {pages} page{}": "Markerade foton: {n} · sidor: {pages}{:.0}{:.0}", - "{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}" + "{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}", + "{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index f88ce066d7..df2b0859ae 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2463,5 +2463,6 @@ "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Knappen Taggar visar platshållare för mallen, till exempel {date} eller {seq}. Varje fil byter namn på disken tillsammans med sin XMP-sidofil; ett namn som redan finns får -1, -2…", "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", - "Bottom bar": "Nedre fältet" + "Bottom bar": "Nedre fältet", + "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 1bdab6dc34..70dae2280f 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -161,6 +161,8 @@ "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Змін не вдалося записати на диск: {n}{0:.0}: {e}\nЯкщо вийти зараз, їх буде втрачено.{1:.0}", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "Змін збережено в пам’яті, але не записано на диск: {n}{:.0}: {e}\nLightCraft повторює спроби автоматично; вихід зараз призведе до їхньої втрати.{:.0}", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "Змін збережено в пам’яті, але не записано на диск: {n}{:.0}: {e} — LightCraft повторить спробу", + "{n} file{} skipped (not a supported photo type)": "Пропущено файлів (непідтримуваний тип фото): {n}{:.0}", + "{n} folder{} could not be read": "Папок, які не вдалося прочитати: {n}{:.0}", "{n} found · {sel} selected": "Знайдено: {n} · вибрано: {sel}", "{n} photos": "Фото: {n}", "{n} photos in {} are hidden by the filters above": "Фільтри вище приховують фото в «{}»: {n}", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index a2c3c9ea0d..5980811b38 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2116,6 +2116,7 @@ "Metadata read": "Метадані прочитано", "Failed": "Помилки", "Stopped": "Зупинено", + "Stopped at the scan limit: there may be more photos": "Зупинено на межі сканування: можливо, є й інші фото", "Stopped by an error (see the log)": "Зупинено через помилку (див. журнал)", "Not saved": "Не збережено", "A folder is being synchronized": "Тека синхронізується", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index dbf1d28db5..a3a944ce39 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -317,5 +317,7 @@ "Panel layout could not be restored: {error}": "Không thể khôi phục bố cục bảng: {error}", "Panel move was not applied: {error}": "Việc di chuyển bảng chưa được áp dụng: {error}", "{name} is installed": "{name} đã được cài đặt", - "{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật" + "{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật", + "{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}", + "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index c0d3bfdbfb..95369fa1f9 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2688,5 +2688,6 @@ "Set up name suggestions…": "Thiết lập gợi ý tên…", "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", - "Bottom bar": "Thanh dưới cùng" + "Bottom bar": "Thanh dưới cùng", + "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 900d30b428..b81b358848 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -96,6 +96,8 @@ "{name} On": "已开启 {name}", "{name} — double-click to reset it": "{name} — 双击可重置", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} 项更改已保存在内存中,但尚未写入磁盘:{e}\nLightCraft 会自动重试;现在退出将丢失这些更改。{0:.0}{1:.0}", + "{n} file{} skipped (not a supported photo type)": "已跳过的文件(不是支持的照片类型):{n} 个{:.0}", + "{n} folder{} could not be read": "无法读取的文件夹:{n} 个{:.0}", "{n} found · {sel} selected": "找到 {n} 张 · 已选 {sel} 张", "{n} photos": "{n} 张照片", "{n} photos in {} are hidden by the filters above": "{0} 中的 {n} 张照片被上方的过滤器隐藏", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index c7201b9a56..995a204f4f 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1927,6 +1927,7 @@ "Metadata read": "已读取元数据", "Failed": "失败", "Stopped": "已停止", + "Stopped at the scan limit: there may be more photos": "已在扫描上限处停止:可能还有更多照片", "Stopped by an error (see the log)": "因错误而停止(见日志)", "Not saved": "未保存", "A folder is being synchronized": "正在同步文件夹", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index a451e955d5..fc93b2b603 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -117,6 +117,8 @@ "{name} On": "開啟{name}", "{name} — double-click to reset it": "{name} — 按兩下可重設", "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} 項變更{:.0}已保留在記憶體,但尚未寫入磁碟:{e}\nLightCraft 會自動重試;現在結束程式會遺失{}。", + "{n} file{} skipped (not a supported photo type)": "已略過的檔案(不是支援的照片類型):{n} 個{:.0}", + "{n} folder{} could not be read": "無法讀取的資料夾:{n} 個{:.0}", "{n} found · {sel} selected": "找到 {n} 張 · 已選取 {sel} 張", "{n} photos": "{n} 張照片", "{n} photos in {} are hidden by the filters above": "{}中的 {n} 張照片被上方篩選條件隱藏", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 3b75e1ab6e..d8b6d143b0 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1933,6 +1933,7 @@ "Metadata read": "已讀取中繼資料", "Failed": "失敗", "Stopped": "已停止", + "Stopped at the scan limit: there may be more photos": "已在掃描上限處停止:可能還有更多照片", "Stopped by an error (see the log)": "因錯誤而停止(請見記錄)", "Not saved": "未儲存", "A folder is being synchronized": "正在同步資料夾", diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index c927608e01..4336e5e82f 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -3,10 +3,11 @@ //! a grid of thumbnails with checkboxes (duplicates marked and unchecked; Shift-click sets a //! range), the destination (add in place / copy or move into the library's `Originals/` or a //! chosen folder, filed by day, by month, into one folder or by a custom folder template, -//! optionally renamed), an album (existing or new), a preset and keywords to apply. Importing -//! runs on a worker thread (files are probed, copied or moved there) and its batches join the -//! catalog between frames, with a row and ✕ in the activity stack (issue #345); the whole import is -//! one undo step. +//! optionally renamed), an album (existing or new), a preset and keywords to apply. When the scan +//! left something out (a walk cut at its limit, folders it couldn't read, files that are not +//! photos) one line under the count says so ([`scan_note`]). Importing runs on a worker thread +//! (files are probed, copied or moved there) and its batches join the catalog between frames, with +//! a row and ✕ in the activity stack (issue #345); the whole import is one undo step. use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; use lightcraft_engine::import::{ @@ -28,6 +29,7 @@ mod task; #[cfg(test)] pub(crate) use body::grid_height; +pub(crate) use body::scan_note; #[cfg(test)] pub(crate) use body::thumb_edge; #[cfg(test)] @@ -80,6 +82,14 @@ pub struct ImportDialog { /// What to do with those: `restore` (the default: the photo comes back with its edits), `fresh` /// (imported as a new photo, the old record deleted) or "" (leave them) — the `onDeleted` param. pub on_deleted: String, + /// The scan's folder walk stopped at a depth or entry limit: there may be more photos than the + /// review lists ([`ScanOutput::truncated`]; `scanLimited` in the `library.importPreview` reply). + pub scan_limited: bool, + /// Folders the scan couldn't list ([`ScanOutput::unreadable`]). + pub unreadable: usize, + /// Files in the scanned folders that are not a supported photo type, XMP sidecars not counted + /// ([`ScanOutput::unsupported`]). + pub unsupported: usize, /// The candidate clicked last: where a Shift-click range starts ([`ImportDialog::click`]). #[serde(skip)] pub last_clicked: Option, diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 61e0bfb1bd..d461d690ab 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -78,6 +78,24 @@ pub(super) fn dup_counts(d: &ImportDialog) -> (usize, usize, usize) { (dups, in_source, trashed) } +/// The one line that says what the scan left out, for the review's header: a folder walk that +/// stopped at its limit, folders it couldn't read, files that are not a supported photo type. +/// `None` when it left nothing out (the review then shows no line at all). +pub(crate) fn scan_note(d: &ImportDialog) -> Option { + let plural = |n: usize| if n == 1 { "" } else { "s" }; + let mut parts: Vec = Vec::new(); + if d.scan_limited { + parts.push(crate::i18n::tr("Stopped at the scan limit: there may be more photos").to_string()); + } + if d.unreadable > 0 { + parts.push(crate::i18n::tr_format!("{n} folder{} could not be read", plural(d.unreadable), n = d.unreadable)); + } + if d.unsupported > 0 { + parts.push(crate::i18n::tr_format!("{n} file{} skipped (not a supported photo type)", plural(d.unsupported), n = d.unsupported)); + } + (!parts.is_empty()).then(|| parts.join(" · ")) +} + /// The dialog body: options, then the candidate grid. pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let t = Tokens::get(ui.ctx()); @@ -107,6 +125,11 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { } }); }); + // what the scan left out, when it left something out + if let Some(note) = scan_note(d) { + let r = ui.label(egui::RichText::new(note).color(t.caution).small()); + register(ui, "label:importScanNote", r.rect); + } // with more than one file type: a toggle per type checks or unchecks all of its files let types = d.file_types(); if types.len() > 1 { diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index c82f67123c..f4d22079a4 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -239,7 +239,13 @@ 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 - let _ = tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates, probes: input.take_probes() })); + let _ = tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { + candidates, + probes: input.take_probes(), + truncated: false, + unreadable: 0, + unsupported: 0, + })); }; #[cfg(not(target_arch = "wasm32"))] std::thread::spawn(job); @@ -360,11 +366,19 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { return; } if out.candidates.is_empty() { - app.toast(ctx, crate::i18n::tr("No photos found")); + // (what the scan left out is said here too: a scan that found no photos may have had folders it + // could not read, or files that are not photos, and the note is the same one the review shows) + let left_out = ImportDialog { scan_limited: out.truncated, unreadable: out.unreadable, unsupported: out.unsupported, ..Default::default() }; + let text = match super::scan_note(&left_out) { + Some(note) => format!("{} · {note}", crate::i18n::tr("No photos found")), + None => crate::i18n::tr("No photos found").to_string(), + }; + app.toast(ctx, text); return; } app.renderer.forget_imports(); let mut d = ImportDialog::new(out.candidates); + (d.scan_limited, d.unreadable, d.unsupported) = (out.truncated, out.unreadable, out.unsupported); let trashed = d .candidates .iter() diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 08094f8410..a9f8b72cba 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -40,6 +40,7 @@ mod grid; mod grid_drag; mod guided_guides; mod histogram_drag; +mod import_scan_note; mod import_thumbnails; mod info_dialogs; mod keymap; diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index 6136ccf93f..ad661e9f19 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -1198,7 +1198,14 @@ fn auto_import_waits_for_a_browse_that_starts_during_its_listing() { assert!(h.app.import.is_none(), "no Auto Import for the browse to replace"); // the browse finds one photo of its own and imports it let found = ImportCandidate { path: dir.path("trip/a.png"), ..Default::default() }; - tx.send(crate::import::ScanEnd::Done(ScanOutput { candidates: vec![found], probes: Default::default() })).unwrap(); + tx.send(crate::import::ScanEnd::Done(ScanOutput { + candidates: vec![found], + probes: Default::default(), + truncated: false, + unreadable: 0, + unsupported: 0, + })) + .unwrap(); drop(tx); assert!(h.step_until(T, |h| h.app.import.is_some()), "the browse starts its import"); assert!(h.step_until(T, |h| h.app.import.is_none()), "and it ends"); diff --git a/crates/ui-egui/src/tests/import_scan_note.rs b/crates/ui-egui/src/tests/import_scan_note.rs new file mode 100644 index 0000000000..f0cf4bf816 --- /dev/null +++ b/crates/ui-egui/src/tests/import_scan_note.rs @@ -0,0 +1,242 @@ +//! The import review says what its scan left out: one line, and only when it left something out. +//! +//! * Files in the folder that are not photos (a text file beside the pictures): the review lists +//! the pictures and says how many files were skipped. +//! * A folder tree deeper than a scan goes: the review says that there may be more photos. +//! * A folder of pictures only: no line at all. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde_json::json; + +use crate::dialogs::import::{ImportDialog, scan_note}; +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +const STOPPED: &str = "Stopped at the scan limit: there may be more photos"; + +/// A scratch folder that goes away with the test, however it ends. +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("lc-ui-scan-note-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn write_png(path: &Path, seed: u8) { + let (w, h) = (24usize, 16usize); + let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 9) as u8, (i / w * 13) as u8, seed, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); +} + +fn headless() -> Headless { + let app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services { png: None, ..Default::default() }); + Headless::new(app, [1300.0, 900.0], 1.0) +} + +/// File → Import from Folder… for `dir`, and wait for the review to open. +fn open_review(h: &mut Headless, dir: &Scratch) { + let r = h.request("engine.execute", json!({"command": "file.addFolder", "params": {"path": dir.0.to_string_lossy()}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.step_until(T, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "no import review: {:?}", h.app.ui.dialog); +} + +fn review(h: &mut Headless) -> &mut ImportDialog { + let Some(Dialog::Import { opts }) = &mut h.app.ui.dialog else { panic!("no import review") }; + opts +} + +/// The review painted a text that is exactly `line`. +fn shows(h: &Headless, line: &str) -> bool { + h.painted_text().iter().any(|t| t == line) +} + +/// The review painted any of the scan's notes. +fn shows_any_note(h: &Headless) -> bool { + h.painted_text().iter().any(|t| t.contains(STOPPED) || t.contains("could not be read") || t.contains("skipped (not a supported photo type)")) +} + +fn has_note_widget(h: &mut Headless) -> bool { + h.request("ui.widgets", json!({}), T).to_string().contains("label:importScanNote") +} + +/// A text file beside the pictures: the review lists the pictures, and says one file was skipped. +#[test] +fn the_review_says_how_many_files_were_skipped() { + let dir = Scratch::new("skipped"); + write_png(&dir.0.join("a.png"), 1); + write_png(&dir.0.join("trip").join("b.png"), 2); + std::fs::write(dir.0.join("notes.txt"), b"not a photo").unwrap(); + let mut h = headless(); + open_review(&mut h, &dir); + let d = review(&mut h); + assert_eq!(d.candidates.len(), 2); + assert_eq!((d.scan_limited, d.unreadable, d.unsupported), (false, 0, 1)); + h.step(); + assert!(shows(&h, "1 file skipped (not a supported photo type)"), "{:?}", h.painted_text()); + assert!(has_note_widget(&mut h), "the line is a registered widget"); +} + +/// Nothing to import but a file that is not a photo: no review opens, and the message says why +/// nothing was found, the same skipped count the review would have shown. +#[test] +fn an_empty_scan_says_what_it_left_out() { + let dir = Scratch::new("empty-skipped"); + std::fs::write(dir.0.join("notes.txt"), b"not a photo").unwrap(); + let mut h = headless(); + assert_eq!(scan_empty_folder(&mut h, &dir), "No photos found · 1 file skipped (not a supported photo type)"); + assert!(!matches!(h.app.ui.dialog, Some(Dialog::Import { .. })), "no review for a scan with no photos"); +} + +/// A folder with nothing in it: the plain message, as before. +#[test] +fn an_empty_folder_keeps_the_plain_message() { + let dir = Scratch::new("empty"); + let mut h = headless(); + assert_eq!(scan_empty_folder(&mut h, &dir), "No photos found"); +} + +/// File → Import from Folder… for `dir` (no photos in it): the message the scan leaves. +fn scan_empty_folder(h: &mut Headless, dir: &Scratch) -> String { + let r = h.request("engine.execute", json!({"command": "file.addFolder", "params": {"path": dir.0.to_string_lossy()}}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.step_until(SETTLE, |h| h.app.ui.toast.is_some()), "no message: {:?}", h.app.ui.toast); + h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default() +} + +/// XMP sidecars beside the pictures are read with them, so they are not "skipped": no note for +/// them, but a text file in the same folder still gets its line. +#[test] +fn xmp_sidecars_do_not_make_the_review_say_files_were_skipped() { + let dir = Scratch::new("sidecars"); + write_png(&dir.0.join("a.png"), 1); + std::fs::write(dir.0.join("a.xmp"), b"x").unwrap(); + std::fs::write(dir.0.join("b.XMP"), b"x").unwrap(); + let mut h = headless(); + open_review(&mut h, &dir); + let d = review(&mut h); + assert_eq!((d.candidates.len(), d.scan_limited, d.unreadable, d.unsupported), (1, false, 0, 0)); + h.step(); + assert!(!shows_any_note(&h), "{:?}", h.painted_text()); + assert!(!has_note_widget(&mut h)); + + std::fs::write(dir.0.join("notes.txt"), b"not a photo").unwrap(); + h.app.ui.dialog = None; + open_review(&mut h, &dir); + assert_eq!(review(&mut h).unsupported, 1, "only the text file"); + h.step(); + assert!(shows(&h, "1 file skipped (not a supported photo type)"), "{:?}", h.painted_text()); +} + +/// A tree deeper than a scan goes: the review says that there may be more photos. +#[test] +fn the_review_says_when_the_scan_stopped_at_its_limit() { + let dir = Scratch::new("deep"); + write_png(&dir.0.join("top.png"), 1); + let mut deepest = dir.0.clone(); + for _ in 0..lightcraft_engine::walk::MAX_DEPTH { + deepest = deepest.join("d"); + } + std::fs::create_dir_all(&deepest).unwrap(); + let mut h = headless(); + open_review(&mut h, &dir); + let d = review(&mut h); + assert_eq!((d.candidates.len(), d.scan_limited, d.unreadable, d.unsupported), (1, true, 0, 0)); + h.step(); + assert!(shows(&h, STOPPED), "{:?}", h.painted_text()); +} + +/// Nothing left out: no line, and no widget for it. +#[test] +fn the_review_has_no_note_when_the_scan_left_nothing_out() { + let dir = Scratch::new("clean"); + write_png(&dir.0.join("a.png"), 1); + write_png(&dir.0.join("trip").join("b.png"), 2); + let mut h = headless(); + open_review(&mut h, &dir); + let d = review(&mut h); + assert_eq!((d.candidates.len(), d.scan_limited, d.unreadable, d.unsupported), (2, false, 0, 0)); + h.step(); + assert!(!shows_any_note(&h), "{:?}", h.painted_text()); + assert!(!has_note_widget(&mut h)); +} + +/// The line follows the counters while the review is open, and is written in the language in use. +#[test] +fn the_note_follows_the_counters_and_the_language() { + let dir = Scratch::new("follow"); + write_png(&dir.0.join("a.png"), 1); + let mut h = headless(); + open_review(&mut h, &dir); + assert!(!shows_any_note(&h)); + + let all = format!("{STOPPED} · 2 folders could not be read · 3 files skipped (not a supported photo type)"); + { + let d = review(&mut h); + (d.scan_limited, d.unreadable, d.unsupported) = (true, 2, 3); + } + h.step(); + h.step(); + assert!(shows(&h, &all), "{:?}", h.painted_text()); + + { + let d = review(&mut h); + (d.scan_limited, d.unreadable, d.unsupported) = (false, 1, 1); + } + h.step(); + h.step(); + assert!(shows(&h, "1 folder could not be read · 1 file skipped (not a supported photo type)"), "{:?}", h.painted_text()); + + { + let d = review(&mut h); + (d.scan_limited, d.unreadable, d.unsupported) = (true, 1, 1); + } + assert_eq!(h.request("engine.execute", json!({"command": "app.language.german"}), T)["ok"], true); + h.settle(SETTLE); + let german = "Am Suchlimit angehalten: Es gibt möglicherweise weitere Fotos · Ordner, die nicht gelesen werden konnten: 1 · Übersprungene Dateien (kein unterstützter Fototyp): 1"; + assert!(shows(&h, german), "{:?}", h.painted_text()); + assert_eq!(h.request("engine.execute", json!({"command": "app.language.english"}), T)["ok"], true); + + { + let d = review(&mut h); + (d.scan_limited, d.unreadable, d.unsupported) = (false, 0, 0); + } + h.step(); + h.step(); + assert!(!shows_any_note(&h), "back to nothing left out: {:?}", h.painted_text()); +} + +/// The wording, one part per thing left out, joined into one line; singular and plural. +#[test] +fn the_note_names_each_thing_that_was_left_out() { + let note = |scan_limited, unreadable, unsupported| scan_note(&ImportDialog { scan_limited, unreadable, unsupported, ..Default::default() }); + assert_eq!(note(false, 0, 0), None); + assert_eq!(note(true, 0, 0).as_deref(), Some(STOPPED)); + assert_eq!(note(false, 1, 0).as_deref(), Some("1 folder could not be read")); + assert_eq!(note(false, 4, 0).as_deref(), Some("4 folders could not be read")); + assert_eq!(note(false, 0, 1).as_deref(), Some("1 file skipped (not a supported photo type)")); + assert_eq!(note(false, 0, 12).as_deref(), Some("12 files skipped (not a supported photo type)")); + assert_eq!( + note(true, 2, 2).as_deref(), + Some(format!("{STOPPED} · 2 folders could not be read · 2 files skipped (not a supported photo type)").as_str()) + ); +} diff --git a/crates/ui-egui/src/tests/scan_probes.rs b/crates/ui-egui/src/tests/scan_probes.rs index 04c7ad10d0..a8a5bf116f 100644 --- a/crates/ui-egui/src/tests/scan_probes.rs +++ b/crates/ui-egui/src/tests/scan_probes.rs @@ -68,7 +68,14 @@ fn a_scan_closed_with_its_cross_hands_back_its_probes_when_the_worker_ends() { h.step(); assert!(h.app.scan.is_none(), "✕ closes the scan at once"); // the worker ends later, with the probes it took - tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates: Vec::new(), probes: probes() })).unwrap(); + tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { + candidates: Vec::new(), + probes: probes(), + truncated: false, + unreadable: 0, + unsupported: 0, + })) + .unwrap(); assert!(h.step_until(T, kept), "the probes came back"); assert!(h.app.ui.dialog.is_none(), "no review opened"); assert!(!failed_toast(&h)); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e8c0e1a709..ef39208967 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -69,7 +69,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with a remembered 80–320 pt thumbnail-size slider (default 116, independent of the library grid), density-aware previews capped at 1024 px and retention limited to nearby cells; tiny sources are tried once per requested size bucket; renderable raws use a sharper render when the camera JPEG is undersized, retaining the JPEG for preview-only raws or an unavailable/failed render; the pre-import loupe and keyboard culling remain open under #2056; thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step; when a Copy rename sequence runs out, remaining files are reported as failed and earlier completed transfers stay accounted for. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`). An import (and a scan of a folder scanned before) checks that each file a scan already probed is as it was by asking the disk about up to 16 files at a time (an import batch's files, at most), not one after another (`stat_all`, `crates/engine/src/import/files.rs`), and looks up the sidecars of a batch's photos the same way (`sidecars_of`); on a network share each file was a round trip | +| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with a remembered 80–320 pt thumbnail-size slider (default 116, independent of the library grid), density-aware previews capped at 1024 px and retention limited to nearby cells; tiny sources are tried once per requested size bucket; renderable raws use a sharper render when the camera JPEG is undersized, retaining the JPEG for preview-only raws or an unavailable/failed render; the pre-import loupe and keyboard culling remain open under #2056; thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step; when a Copy rename sequence runs out, remaining files are reported as failed and earlier completed transfers stay accounted for. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`). An import (and a scan of a folder scanned before) checks that each file a scan already probed is as it was by asking the disk about up to 16 files at a time (an import batch's files, at most), not one after another (`stat_all`, `crates/engine/src/import/files.rs`), and looks up the sidecars of a batch's photos the same way (`sidecars_of`); on a network share each file was a round trip When the scan left something out, one line under the count says so: the folder walk stopped at its depth or entry limit (“Stopped at the scan limit: there may be more photos”), folders it could not read, and files in the folders that are not a supported photo type (XMP sidecars, which the import reads with their photos, and hidden files are never counted; a file named on its own is always tried); nothing is shown when nothing was left out. `library.importPreview` returns the same as `scanLimited` and `skipped` (`unreadable`, `unsupported`). Browse Folder, Find Missing Photos and the command-line / MCP folder expansion walk with the same limits but do not report these counts (`crates/engine/src/walk.rs`, `crates/engine/src/import.rs`) | | LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → the import review), `crates/ui-egui/src/drop_overlay.rs`, `crates/ui-egui/src/tests/drop_import.rs` | while files are dragged over the window a veil and a card say what dropping does (review N items for import, import N presets, open the face model; a note to close the open dialog first when one is open); photos and folders open the import review as File ▸ Import does (Settings ▸ Import ▸ Import dropped files without review imports them at once; the web build always does); with no library open on the desktop (the launch list, a library that couldn't open) photos wait for the library opened and presets are refused, and the card says so; a drop while a dialog is open (also in the web build) or while an import is running is refused with a toast, and the card says so; a finished scan waits for an open dialog to close before its review opens; the control channel's `ui.dropFiles` hovers or drops files for scripts; dropping onto a specific album not supported | | LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests/import.rs` | | | LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/dialogs/import.rs`) | @@ -923,6 +923,8 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-13 | minor | KEY-SLIDER-RESET: hovering a slider's name or thumb says a double-click resets it; a double-click on the thumb is one undo step, not two; a disabled slider's name doesn't reset it (issue #1436); status unchanged (✅) | | 2026-10-20 | patch | LR-MASK-BRUSH: extreme segments skip intermediate dabs; ordinary spacing and endpoints preserved; status unchanged (🟡) | | 2026-10-12 | minor | LR-META-XMP: bounded complete-APP1 manual JPEG reread, fail-closed sidecar precedence and scoped regression coverage; LR-META-EXIF-FULL: reuse loaded bytes; statuses unchanged | +| 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type; no walk behaviour changes; status unchanged (✅) | +| 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type (XMP sidecars are not counted); no walk behaviour changes; status unchanged (✅) | | 2026-10-11 | minor | LR-MERGE-HDR: HDR and panorama merges of raws without colour matrices (CR2, NEF, ARW…) write the colour they open with as DNG tags (issue #965); status unchanged | | 2026-10-12 | minor | LR-META-XMP: Read Metadata from File no longer auto-writes the sidecar it has just read, which added `lc:settings` and hid another app's later `crs:` edits (#934); status unchanged (✅) | | 2026-10-12 | patch | LR-IMP-CAMERA-COVERAGE: CR2 white level from the active area, not the saturated masked rows above it (issue #1272); status unchanged (🟡) |