mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-28 17:29:31 +01:00
Merge pull request #2971 from nledford/import-browsed-photos
LR-IMP-DUPES: a photo browsed in Local is offered by Import and no longer blocks the library's own file
This commit is contained in:
34 files changed
+974
-55
No files matched your search
@@ -224,16 +224,31 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
|
||||
let mut purged: std::collections::HashSet<PhotoId> = Default::default();
|
||||
for it in prepared.items {
|
||||
match it {
|
||||
PreparedItem::Promote(id) => {
|
||||
PreparedItem::Promote(id, fresh) => {
|
||||
// the file was replaced since it was browsed: the record takes what it is now before it joins the library
|
||||
if let Some(info) = &fresh {
|
||||
crate::cmd::convert::reload_ops(&s.catalog, id, info, &mut ops, &mut Vec::new());
|
||||
}
|
||||
if s.catalog.photo(id).is_some_and(|p| p.local) {
|
||||
ops.push(Op::SetLocal { id, local: false });
|
||||
}
|
||||
// "Import as new": a trashed photo with the same content is replaced, as for a new file
|
||||
let content =
|
||||
fresh.as_ref().and_then(|i| i.content_hash.clone()).or_else(|| s.catalog.photo(id).and_then(|p| p.content_hash.clone()));
|
||||
if let Some(old) = content.as_ref().and_then(|h| trash_hash.get(h))
|
||||
&& purged.insert(*old)
|
||||
{
|
||||
purge.push(*old);
|
||||
}
|
||||
report.imported.push(id.0);
|
||||
}
|
||||
PreparedItem::Duplicate { path, existing, reason, hash, file } => {
|
||||
let existing = existing.or_else(|| {
|
||||
let h = hash?;
|
||||
new_hash.get(&h).copied().or_else(|| s.catalog.photos().find(|p| p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id))
|
||||
new_hash
|
||||
.get(&h)
|
||||
.copied()
|
||||
.or_else(|| s.catalog.photos().find(|p| !p.local && p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id))
|
||||
});
|
||||
let trashed = existing.filter(|id| s.catalog.photo(*id).is_some_and(|p| p.deleted));
|
||||
match trashed {
|
||||
@@ -243,7 +258,11 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
|
||||
ops.push(Op::SetDeleted { id, deleted: false });
|
||||
// matched by content from another path, and the file the record
|
||||
// points at is gone (moved, renamed): the photo follows the file
|
||||
if reason == "content" && trashed_file_is_gone(&s.catalog, id) {
|
||||
// (not onto a path another record holds, a file only browsed in Local)
|
||||
if reason == "content"
|
||||
&& trashed_file_is_gone(&s.catalog, id)
|
||||
&& !s.catalog.photos().any(|p| matches!(&p.source, Source::File { path: held } if *held == path))
|
||||
{
|
||||
ops.push(crate::cmd::missing::relink_op(id, &path));
|
||||
}
|
||||
report.restored.push(id.0);
|
||||
|
||||
@@ -487,6 +487,44 @@ pub(super) fn reusable_probes(
|
||||
held.into_iter().map(|h| h.filter(|info| seen.next().is_some_and(|s| s != Seen::Unchecked && ok(s, info)))).collect()
|
||||
}
|
||||
|
||||
/// What looking at the file of a browsed (Local) record found ([`browsed_files_changed`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum BrowsedFile {
|
||||
/// As it was browsed, or not to be told: a record without a size, and a file that can't be read (one that is
|
||||
/// gone is the record's own business) count as unchanged.
|
||||
Unchanged,
|
||||
/// Its size on disk is not the recorded one: another application replaced it since it was browsed (the check the
|
||||
/// probes kept from a scan go by).
|
||||
Changed,
|
||||
/// Not looked at: `cancel` was set first.
|
||||
Unchecked,
|
||||
}
|
||||
|
||||
/// Look at the file of each of `files` (path, the size its browsed record has), several at once ([`stat_all`]: one
|
||||
/// at a time, each is a round trip to a network share, and thousands of browsed photos waited minutes for them).
|
||||
/// The answers come in the order of `files`; a record with no size is not asked about.
|
||||
pub(super) fn browsed_files_changed(files: &[(&str, u64)], cancel: &std::sync::atomic::AtomicBool) -> Vec<BrowsedFile> {
|
||||
// (the web's files are not std::fs files)
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return vec![BrowsedFile::Unchanged; files.len()];
|
||||
}
|
||||
let asked: Vec<&str> = files.iter().filter(|(_, recorded)| *recorded > 0).map(|(path, _)| *path).collect();
|
||||
let mut seen = stat_all(&asked, cancel, stat_file).into_iter();
|
||||
files
|
||||
.iter()
|
||||
.map(|(_, recorded)| {
|
||||
if *recorded == 0 {
|
||||
return BrowsedFile::Unchanged;
|
||||
}
|
||||
match seen.next() {
|
||||
Some(Seen::At { is_file: true, len }) if len != *recorded => BrowsedFile::Changed,
|
||||
Some(Seen::Unchecked) | None => BrowsedFile::Unchecked,
|
||||
Some(_) => BrowsedFile::Unchanged,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Copy `src` into `dir` as `name` (default: its own name), made unique with -1, -2…; returns the
|
||||
/// new path. The copy is verified ([`crate::import_move::copy_new`]: a new file, synced and
|
||||
/// checked against `probe_hash`, the content hash the probe computed — or compared byte for byte
|
||||
@@ -725,6 +763,32 @@ mod prepared_tests {
|
||||
assert!(seen.iter().all(|s| matches!(s, Seen::Gone | Seen::Unchecked)));
|
||||
}
|
||||
|
||||
/// The files of browsed records are looked at together, and only a file of another size than its record has is changed:
|
||||
/// a record with no size, a file that is gone and a folder in its place count as unchanged, and ✕ leaves them all unchecked.
|
||||
#[test]
|
||||
fn browsed_files_are_told_changed_by_their_size() {
|
||||
let dir = temp_dir("browsed-sizes");
|
||||
let name = |n: &str| dir.join(n).to_string_lossy().into_owned();
|
||||
std::fs::write(dir.join("same.jpg"), [0u8; 10]).unwrap();
|
||||
std::fs::write(dir.join("bigger.jpg"), [0u8; 20]).unwrap();
|
||||
std::fs::write(dir.join("unsized.jpg"), [0u8; 5]).unwrap();
|
||||
std::fs::create_dir(dir.join("folder.jpg")).unwrap();
|
||||
let names = ["same.jpg", "bigger.jpg", "unsized.jpg", "gone.jpg", "folder.jpg"].map(name);
|
||||
let files: Vec<(&str, u64)> = names.iter().map(String::as_str).zip([10, 10, 0, 10, 10]).collect();
|
||||
let cancel = std::sync::atomic::AtomicBool::new(false);
|
||||
let found = browsed_files_changed(&files, &cancel);
|
||||
use BrowsedFile::{Changed, Unchanged, Unchecked};
|
||||
assert_eq!(found, [Unchanged, Changed, Unchanged, Unchanged, Unchanged]);
|
||||
cancel.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let found = browsed_files_changed(&files, &cancel);
|
||||
assert_eq!(
|
||||
found,
|
||||
[Unchecked, Unchecked, Unchanged, Unchecked, Unchecked],
|
||||
"a record with no size isn't asked about, so ✕ doesn't matter to it"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A probe a scan left is used again for a file that is as it was, and only for it: a file that
|
||||
/// changed size, one that is gone and one with no probe are read.
|
||||
#[test]
|
||||
|
||||
@@ -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, sidecars_of};
|
||||
use super::files::{BrowsedFile, Seen, browsed_files_changed, 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};
|
||||
|
||||
@@ -38,7 +38,10 @@ pub struct ImportJob {
|
||||
/// as the options said when the import was set up).
|
||||
pub(super) library: Option<(lightcraft_catalog::Catalog, bool)>,
|
||||
/// path → (photo, a Local browse record?)
|
||||
pub(super) by_path: HashMap<String, (PhotoId, bool)>,
|
||||
pub(super) by_path: HashMap<String, (PhotoId, bool, Option<String>)>,
|
||||
/// path → the size the record of a browsed (Local) file has: a file of another size has been replaced since
|
||||
/// it was browsed ([`super::files::browsed_files_changed`])
|
||||
local_sizes: HashMap<String, u64>,
|
||||
/// content hash → the photo that has it (`None`: a file earlier in this import)
|
||||
pub(super) by_hash: HashMap<String, Option<PhotoId>>,
|
||||
pub(super) probe: Option<crate::media::FileProbe>,
|
||||
@@ -69,8 +72,9 @@ pub struct Prepared {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) enum PreparedItem {
|
||||
/// A Local (browsed) record imported for real.
|
||||
Promote(PhotoId),
|
||||
/// A Local (browsed) record imported for real; with what its file is now when the file was replaced since it was
|
||||
/// browsed (the record is brought up to date).
|
||||
Promote(PhotoId, Option<Box<ProbeInfo>>),
|
||||
Duplicate {
|
||||
path: String,
|
||||
existing: Option<PhotoId>,
|
||||
@@ -195,6 +199,7 @@ impl ImportJob {
|
||||
copy_root,
|
||||
library: Some((s.catalog.clone(), fresh)),
|
||||
by_path: HashMap::new(),
|
||||
local_sizes: HashMap::new(),
|
||||
by_hash: HashMap::new(),
|
||||
probe: s.media.file_probe.clone(),
|
||||
file_bytes: s.media.file_bytes.clone(),
|
||||
@@ -268,15 +273,72 @@ impl ImportJob {
|
||||
continue;
|
||||
}
|
||||
if let Source::File { path } = &p.source {
|
||||
self.by_path.insert(path.clone(), (p.id, p.local));
|
||||
self.by_path.insert(path.clone(), (p.id, p.local, p.content_hash.clone()));
|
||||
if p.local {
|
||||
self.local_sizes.insert(path.clone(), p.file_size);
|
||||
}
|
||||
}
|
||||
if let Some(h) = &p.content_hash {
|
||||
// (a copy that was only browsed in Local isn't in the library)
|
||||
if !p.local
|
||||
&& let Some(h) = &p.content_hash
|
||||
{
|
||||
self.by_hash.insert(h.clone(), Some(p.id));
|
||||
}
|
||||
}
|
||||
Some(library)
|
||||
}
|
||||
|
||||
/// The batch's files the library already knows of, by path: a duplicate, a browsed file promoted (or a replaced
|
||||
/// one probed again, noted in `changed`), the others left in `todo` to be probed.
|
||||
fn sort_by_library(
|
||||
&mut self,
|
||||
files: Vec<String>,
|
||||
verdicts: Vec<Option<BrowsedFile>>,
|
||||
local: bool,
|
||||
out: &mut Prepared,
|
||||
changed: &mut HashMap<String, PhotoId>,
|
||||
todo: &mut Vec<String>,
|
||||
) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
for (f, verdict) in files.into_iter().zip(verdicts) {
|
||||
match self.by_path.get(f.as_str()).cloned() {
|
||||
Some((id, true, hash)) if !local => match verdict {
|
||||
// ✕ before its size was looked at: nothing is decided about it, so it isn't promoted
|
||||
Some(BrowsedFile::Unchecked) => {}
|
||||
Some(BrowsedFile::Changed) => {
|
||||
changed.insert(f.clone(), id);
|
||||
todo.push(f);
|
||||
}
|
||||
Some(BrowsedFile::Unchanged) | None => {
|
||||
out.items.push(self.promote_browsed(f, id, hash));
|
||||
self.done.fetch_add(1, Relaxed);
|
||||
}
|
||||
},
|
||||
Some((id, _, _)) => {
|
||||
out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file: None });
|
||||
self.done.fetch_add(1, Relaxed);
|
||||
}
|
||||
None => todo.push(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A browsed file this import brings into the library (its size unchanged): a duplicate of a library photo with
|
||||
/// the same content, or promoted (and from then on the library's).
|
||||
fn promote_browsed(&mut self, f: String, id: PhotoId, hash: Option<String>) -> PreparedItem {
|
||||
// a library photo with the same content comes first, and a file promoted earlier
|
||||
// (here or in a previous batch) counts as the library's from then on
|
||||
if let Some(h) = &hash {
|
||||
if let Some(existing) = self.by_hash.get(h) {
|
||||
return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, file: None };
|
||||
}
|
||||
self.by_hash.insert(h.clone(), Some(id));
|
||||
}
|
||||
// a file that was only browsed (Local) joins the library when it is imported for real
|
||||
self.by_path.insert(f, (id, false, hash));
|
||||
PreparedItem::Promote(id, None)
|
||||
}
|
||||
|
||||
/// [`ImportJob::prepare`] for files [`ImportJob::expand`] returned.
|
||||
pub fn prepare_files(&mut self, files: Vec<String>, cancel: &std::sync::atomic::AtomicBool) -> Prepared {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
@@ -287,21 +349,16 @@ impl ImportJob {
|
||||
let mode = self.mode;
|
||||
let mut out = Prepared { scanned: files.len(), items: Vec::new() };
|
||||
let mut todo = Vec::new();
|
||||
for f in files {
|
||||
match self.by_path.get(f.as_str()).copied() {
|
||||
Some((id, true)) if !opts.local => {
|
||||
// a file that was only browsed (Local) joins the library when it is imported for real
|
||||
self.by_path.insert(f, (id, false));
|
||||
out.items.push(PreparedItem::Promote(id));
|
||||
self.done.fetch_add(1, Relaxed);
|
||||
}
|
||||
Some((id, _)) => {
|
||||
out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file: None });
|
||||
self.done.fetch_add(1, Relaxed);
|
||||
}
|
||||
None => todo.push(f),
|
||||
}
|
||||
}
|
||||
// browsed files replaced since: probed again with `todo`, their records brought up to date as they join the library
|
||||
let mut changed: HashMap<String, PhotoId> = HashMap::new();
|
||||
// the sizes of the browsed files this import would promote, looked at together before they are decided one by one
|
||||
// (a file promoted in an earlier batch isn't asked about again; one path twice in a batch is, and its second answer is unused)
|
||||
let is_browsed = |f: &String| !opts.local && matches!(self.by_path.get(f.as_str()), Some((_, true, _)));
|
||||
let browsed: Vec<(&str, u64)> =
|
||||
files.iter().filter(|f| is_browsed(f)).map(|f| (f.as_str(), self.local_sizes.get(f.as_str()).copied().unwrap_or(0))).collect();
|
||||
let mut looked_at = browsed_files_changed(&browsed, cancel).into_iter();
|
||||
let verdicts: Vec<Option<BrowsedFile>> = files.iter().map(|f| is_browsed(f).then(|| looked_at.next()).flatten()).collect();
|
||||
self.sort_by_library(files, verdicts, opts.local, &mut out, &mut changed, &mut todo);
|
||||
|
||||
// files a preceding scan already probed are not read again (a network share is slow to read),
|
||||
// as long as they are still there, as they were: a file gone or changed since is probed again
|
||||
@@ -372,6 +429,19 @@ impl ImportJob {
|
||||
// when the import makes a record of it, once it is read as a file import reads it)
|
||||
let duplicate_of =
|
||||
info.content_hash.as_ref().filter(|_| !opts.local).and_then(|h| self.by_hash.get(h).map(|existing| (h.clone(), *existing)));
|
||||
// a browsed file replaced since it was browsed, and not a copy of what the library has: its record takes what the
|
||||
// file is now (size, dimensions, content) as it joins the library
|
||||
if duplicate_of.is_none()
|
||||
&& let Some(id) = changed.remove(&path)
|
||||
{
|
||||
if let Some(h) = &info.content_hash {
|
||||
self.by_hash.insert(h.clone(), Some(id));
|
||||
}
|
||||
self.by_path.insert(path, (id, false, info.content_hash.clone()));
|
||||
self.done.fetch_add(1, Relaxed);
|
||||
plan.slots.push(Slot::Item(PreparedItem::Promote(id, Some(Box::new(info)))));
|
||||
continue;
|
||||
}
|
||||
// the XMP sidecar (or a file's embedded XMP), read before copying: its capture time files
|
||||
// and names the copy when the file itself has none (a skipped duplicate needs only that time)
|
||||
let raw = info.kind == MediaKind::Raw;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::files::{Seen, expand, expand_report_knowing, is_supported, probe_all, reusable_probes};
|
||||
use super::files::{BrowsedFile, Seen, browsed_files_changed, expand, expand_report_knowing, is_supported, probe_all, reusable_probes};
|
||||
use super::types::ImportCandidate;
|
||||
use super::{HashMap, ListedFolders, Path, PathBuf, PhotoId, ProbeInfo, Session, Source};
|
||||
|
||||
@@ -19,7 +19,7 @@ pub struct ScanInput {
|
||||
/// The library's photos of `files`: path → (photo, its summary as a candidate that is there
|
||||
/// already). One pass over the library, and a record only for a file that was found: a folder of
|
||||
/// a hundred files in a library of millions costs a hundred records.
|
||||
pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[String]) -> HashMap<PathBuf, (PhotoId, ImportCandidate)> {
|
||||
pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[String]) -> HashMap<PathBuf, (PhotoId, ImportCandidate, Option<String>)> {
|
||||
let found: std::collections::HashSet<&Path> = files.iter().map(Path::new).collect();
|
||||
let mut by_path = HashMap::new();
|
||||
if found.is_empty() {
|
||||
@@ -37,18 +37,21 @@ pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[Stri
|
||||
height: p.height,
|
||||
file_size: p.file_size,
|
||||
captured: p.captured.clone(),
|
||||
duplicate: Some("path".into()),
|
||||
// a file that was only browsed (Local) is not in the library: importing it promotes it
|
||||
// (a trashed browse record still counts as the path's)
|
||||
duplicate: (!p.local || p.deleted).then(|| "path".into()),
|
||||
existing: Some(p.id.0),
|
||||
local: p.local && !p.deleted,
|
||||
..Default::default()
|
||||
};
|
||||
by_path.insert(PathBuf::from(path), (p.id, c));
|
||||
by_path.insert(PathBuf::from(path), (p.id, c, p.content_hash.clone()));
|
||||
}
|
||||
}
|
||||
by_path
|
||||
}
|
||||
|
||||
/// Which photo of the library has each of the contents `hashes` (the later one where several
|
||||
/// have it). One pass over the library, and an entry only for a content that was asked about.
|
||||
/// have it; a copy that was only browsed in Local isn't in the library). One pass over the library, and an entry only for a content that was asked about.
|
||||
pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes: impl Iterator<Item = &'a str>) -> HashMap<String, PhotoId> {
|
||||
let wanted: std::collections::HashSet<&str> = hashes.collect();
|
||||
let mut by_hash = HashMap::new();
|
||||
@@ -56,7 +59,8 @@ pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes:
|
||||
return by_hash;
|
||||
}
|
||||
for p in library.photos() {
|
||||
if let Some(h) = &p.content_hash
|
||||
if !p.local
|
||||
&& let Some(h) = &p.content_hash
|
||||
&& wanted.contains(h.as_str())
|
||||
{
|
||||
by_hash.insert(h.clone(), p.id);
|
||||
@@ -340,7 +344,28 @@ pub fn scan_with(mut input: ScanInput, paths: &[String], progress: &ScanProgress
|
||||
/// them ([`expand_report`](super::files::expand_report)).
|
||||
pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &ScanProgress) -> ScanOutput {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let by_path = library_files(&input.library, &files);
|
||||
let mut by_path = library_files(&input.library, &files);
|
||||
// a browsed file that was replaced since is not the one its record describes: it is read again like a new file
|
||||
// (the record's stored content, kept from the browse, would give the wrong answer against the library), and
|
||||
// its candidate still names the record and says it was only browsed, unless the library has that content.
|
||||
// Their sizes are looked at together; ✕ while that goes on leaves the files not reached to be read (and so
|
||||
// reported as not probed) like the ones after them, never vouched for as the record's own.
|
||||
let mut replaced: HashMap<PathBuf, PhotoId> = HashMap::new();
|
||||
let browsed: Vec<(&str, u64)> =
|
||||
files.iter().filter_map(|f| by_path.get(Path::new(f)).filter(|(_, c, _)| c.local).map(|(_, c, _)| (f.as_str(), c.file_size))).collect();
|
||||
for ((f, _), checked) in browsed.iter().zip(browsed_files_changed(&browsed, &progress.cancel)) {
|
||||
match checked {
|
||||
BrowsedFile::Unchanged => {}
|
||||
BrowsedFile::Changed => {
|
||||
if let Some((id, ..)) = by_path.remove(Path::new(f)) {
|
||||
replaced.insert(PathBuf::from(f), id);
|
||||
}
|
||||
}
|
||||
BrowsedFile::Unchecked => {
|
||||
by_path.remove(Path::new(f));
|
||||
}
|
||||
}
|
||||
}
|
||||
let todo: Vec<String> = files.iter().filter(|f| !by_path.contains_key(Path::new(f))).cloned().collect();
|
||||
progress.total.store(todo.len(), Relaxed);
|
||||
// probes from a preceding `scan` are reused when the file is unchanged (same size); a file that
|
||||
@@ -359,15 +384,39 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &Sc
|
||||
crate::memory::release();
|
||||
let mut probes: HashMap<String, Result<ProbeInfo, String>> = todo.into_iter().zip(probed).collect();
|
||||
// (who in the library has a content that was probed: asked once the probes are in)
|
||||
let probed_hashes = probes.values().filter_map(|r| r.as_ref().ok()).filter_map(|info| info.content_hash.as_deref());
|
||||
let probed_hashes = probes
|
||||
.values()
|
||||
.filter_map(|r| r.as_ref().ok())
|
||||
.filter_map(|info| info.content_hash.as_deref())
|
||||
// (and the browsed files the library has by path: they are offered unless it has the content too)
|
||||
.chain(by_path.values().filter(|(_, c, _)| c.local).filter_map(|(_, _, h)| h.as_deref()));
|
||||
let mut seen_hash: HashMap<String, Option<u64>> =
|
||||
library_hashes(&input.library, probed_hashes).into_iter().map(|(h, id)| (h, Some(id.0))).collect();
|
||||
let mut out = Vec::with_capacity(files.len());
|
||||
let mut kept = HashMap::new();
|
||||
// (a content's browsed first copy: its path, until the first file of its own with that content stands in for it)
|
||||
let mut browsed_first: HashMap<String, String> = HashMap::new();
|
||||
for f in files {
|
||||
if let Some((_, c)) = by_path.get(Path::new(&f)) {
|
||||
if let Some((_, c, hash)) = by_path.get(Path::new(&f)) {
|
||||
let mut c = c.clone();
|
||||
c.name = Path::new(&f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| f.clone());
|
||||
// a browsed file the library has the content of (or an earlier file here promotes) is a duplicate
|
||||
if c.local
|
||||
&& let Some(h) = hash
|
||||
{
|
||||
match seen_hash.get(h) {
|
||||
Some(existing) => {
|
||||
c.duplicate = Some("content".into());
|
||||
c.existing = *existing;
|
||||
}
|
||||
None => {
|
||||
// (the library doesn't have it: a browsed record isn't a library photo, and
|
||||
// the import looks the library up when it runs)
|
||||
seen_hash.insert(h.clone(), None);
|
||||
browsed_first.insert(h.clone(), f.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
@@ -385,12 +434,28 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &Sc
|
||||
Some(existing) => {
|
||||
c.duplicate = Some("content".into());
|
||||
c.existing = *existing;
|
||||
// (the first copy of a browsed photo that is a file of its own stands in for it when
|
||||
// copying leaves the browsed one out: said once per content; a browsed file doesn't)
|
||||
if existing.is_none() && !replaced.contains_key(Path::new(&f)) {
|
||||
c.browsed_twin = browsed_first.remove(h);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
seen_hash.insert(h.clone(), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(id) = replaced.get(Path::new(&f)) {
|
||||
// still the browsed record's file, as for one that is as browsed: Copy and Move leave it out, and the
|
||||
// first twin of its own stands in for it there
|
||||
c.local = true;
|
||||
if c.duplicate.is_none() {
|
||||
c.existing = Some(id.0);
|
||||
if let Some(h) = &info.content_hash {
|
||||
browsed_first.insert(h.clone(), f.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
kept.insert(f, info);
|
||||
}
|
||||
Some(Err(e)) => c.error = Some(e),
|
||||
|
||||
@@ -28,7 +28,7 @@ fn a_scan_knows_the_library_photos_of_the_files_it_found() {
|
||||
let files: Vec<String> = ["/pics/007/a.jpg", "/pics/007/b.jpg", "/pics/007/new.jpg", "/pics/007//c.jpg"].map(String::from).to_vec();
|
||||
let known = library_files(&c, &files);
|
||||
assert_eq!(known.len(), 3, "the three the library has (a path is compared as a path, not as text)");
|
||||
let (id, as_found) = known.get(Path::new("/pics/007/b.jpg")).expect("b");
|
||||
let (id, as_found, _) = known.get(Path::new("/pics/007/b.jpg")).expect("b");
|
||||
let p = c.photo(*id).unwrap();
|
||||
assert_eq!((as_found.path.as_str(), as_found.existing, as_found.duplicate.as_deref()), ("/pics/007/b.jpg", Some(id.0), Some("path")));
|
||||
assert_eq!((as_found.format.as_str(), as_found.width, as_found.height, as_found.file_size), (p.format.as_str(), p.width, p.height, p.file_size));
|
||||
@@ -39,7 +39,7 @@ fn a_scan_knows_the_library_photos_of_the_files_it_found() {
|
||||
let copy = c.alloc_photo_id();
|
||||
c.apply(Op::AddPhoto { photo: Box::new(Photo::new(copy, Source::File { path: "/pics/007/a.jpg".into() }, "a.jpg", "JPEG", 6, 4, "2026-01-02")) })
|
||||
.unwrap();
|
||||
assert_eq!(library_files(&c, &files).get(Path::new("/pics/007/a.jpg")).map(|(id, _)| *id), Some(copy));
|
||||
assert_eq!(library_files(&c, &files).get(Path::new("/pics/007/a.jpg")).map(|(id, _, _)| *id), Some(copy));
|
||||
}
|
||||
|
||||
/// Given a library and a folder on disk that holds a file the library has by its path, one it
|
||||
|
||||
@@ -141,8 +141,19 @@ pub struct ImportCandidate {
|
||||
/// `"path"` (already in the library), `"content"` (same bytes in the library or earlier in this
|
||||
/// list): skipped by the import.
|
||||
pub duplicate: Option<String>,
|
||||
/// The photo that already has it.
|
||||
/// The photo that already has it. On a browsed candidate (`local`): its record.
|
||||
pub existing: Option<u64>,
|
||||
/// The file was only browsed in Local: the library has a record of it (`existing`) that is not in
|
||||
/// the library, so it is not a duplicate and importing it promotes that record.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub local: bool,
|
||||
/// On the first `"content"` duplicate that is a file of its own, when no library photo has its
|
||||
/// bytes but a browsed candidate (`local`) earlier in this list does: the path of that browsed
|
||||
/// candidate. Adding in place the browsed photo is the one brought in, and this is a copy in the
|
||||
/// source; copying and moving leave the browsed photo out (the engine would add it where it is),
|
||||
/// and this file is what they bring in instead.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub browsed_twin: Option<String>,
|
||||
/// Not readable.
|
||||
pub error: Option<String>,
|
||||
/// A raw variant that can't be decoded yet (why): it imports as preview only.
|
||||
|
||||
@@ -280,14 +280,12 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges {
|
||||
if moved_from.values().any(|to| *to == c.path) {
|
||||
continue;
|
||||
}
|
||||
let browsed = c.existing.and_then(|id| labels.photo(PhotoId(id))).is_some_and(|p| p.local && !p.deleted);
|
||||
match (c.duplicate.as_deref(), &c.error) {
|
||||
// a file only looked at in Local is not in the library yet: it is new
|
||||
(Some("path"), _) if browsed => changes.new.push(ImportCandidate { duplicate: None, existing: None, ..c }),
|
||||
(Some("path"), _) => {}
|
||||
(Some(_), _) => changes.duplicates += 1,
|
||||
(None, Some(_)) => changes.unreadable.push(c),
|
||||
(None, None) => changes.new.push(c),
|
||||
// (a file only looked at in Local is not in the library yet: it is new)
|
||||
(None, None) => changes.new.push(ImportCandidate { existing: None, local: false, ..c }),
|
||||
}
|
||||
}
|
||||
let missing = std::mem::take(&mut changes.missing);
|
||||
@@ -346,7 +344,7 @@ fn match_moved(
|
||||
by_hash.entry(base_hash(h)).or_default().push_back(path);
|
||||
}
|
||||
}
|
||||
let usable = |c: &&ImportCandidate| c.error.is_none() && c.duplicate.as_deref() != Some("path");
|
||||
let usable = |c: &&ImportCandidate| c.error.is_none() && c.duplicate.as_deref() != Some("path") && !c.local;
|
||||
let mut moved: HashMap<String, String> = HashMap::new();
|
||||
for c in candidates.iter().filter(usable) {
|
||||
let hash = probes.get(&c.path).and_then(|i| i.content_hash.as_deref());
|
||||
@@ -895,3 +893,7 @@ impl SyncCommit {
|
||||
#[cfg(test)]
|
||||
#[path = "sync/tests_listing.rs"]
|
||||
mod tests_listing;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sync/tests_browsed.rs"]
|
||||
mod tests_browsed;
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Synchronize Folder's "moved" match never takes a file that is only browsed in Local as the new
|
||||
//! place of a missing photo: that file already has a record of its own.
|
||||
use super::*;
|
||||
use lightcraft_catalog::{Catalog, Op};
|
||||
|
||||
/// Given a missing photo with no hash on record and one file of the folder with its size and
|
||||
/// dimensions, when the files are matched, then the file is its new place, unless the file is one
|
||||
/// the library only browsed.
|
||||
#[test]
|
||||
fn a_browsed_file_is_not_where_a_missing_photo_went() {
|
||||
let mut c = Catalog::new();
|
||||
let id = c.alloc_photo_id();
|
||||
let mut p = Photo::new(id, Source::File { path: "/pics/old.jpg".into() }, "old.jpg", "JPEG", 6, 4, "2026-01-01");
|
||||
p.file_size = 1000;
|
||||
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
let missing = [FolderPhoto { id: id.0, path: "/pics/old.jpg".into() }];
|
||||
let mut found = ImportCandidate { path: "/pics/new.jpg".into(), width: 6, height: 4, file_size: 1000, existing: Some(99), ..Default::default() };
|
||||
let moved = match_moved(&missing, std::slice::from_ref(&found), &HashMap::new(), &c);
|
||||
assert_eq!(moved.get("/pics/old.jpg").map(String::as_str), Some("/pics/new.jpg"), "a new file is where it went");
|
||||
found.local = true;
|
||||
assert!(match_moved(&missing, &[found], &HashMap::new(), &c).is_empty(), "a browsed file has a record already");
|
||||
}
|
||||
@@ -25,7 +25,11 @@ const CLOCK: &str = "2026-01-14T05:58:48";
|
||||
|
||||
/// A small procedural PNG (distinct per seed).
|
||||
fn write_png(path: &Path, seed: u8) {
|
||||
let (w, h) = (48usize, 32usize);
|
||||
write_png_sized(path, seed, 48, 32);
|
||||
}
|
||||
|
||||
/// [`write_png`] of another size: a replaced file is noticed by its size, as probes kept from a scan are.
|
||||
fn write_png_sized(path: &Path, seed: u8, w: usize, h: usize) {
|
||||
let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 5) as u8, (i / w * 7) 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();
|
||||
@@ -92,6 +96,383 @@ fn recursive_discovery_includes_sony_sr2_and_srf_case_insensitively() {
|
||||
std::fs::remove_dir_all(src).unwrap();
|
||||
}
|
||||
|
||||
/// A file that was only browsed (Local) is not "already in the library": the scan offers it, and
|
||||
/// importing it brings the browsed record (with its edits) into the library.
|
||||
#[test]
|
||||
fn a_browsed_photos_own_file_is_offered_and_joins_the_library_when_imported() {
|
||||
let src = temp_dir("browsed-own");
|
||||
let f = src.join("a.png");
|
||||
write_png(&f, 75);
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [f], "local": true})).unwrap();
|
||||
let id = r["imported"][0].as_u64().unwrap();
|
||||
s.execute("photo.rate", &json!({"ids": [id], "rating": 3})).unwrap();
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [f]})).unwrap();
|
||||
assert_eq!(scan["duplicates"], 0, "{scan}");
|
||||
assert_eq!(scan["candidates"][0]["duplicate"], Value::Null, "{scan}");
|
||||
assert_eq!(scan["candidates"][0]["existing"], id, "the candidate still names the browsed record: {scan}");
|
||||
assert_eq!(scan["candidates"][0]["local"], true, "and says it was only browsed: {scan}");
|
||||
let r = s.execute("library.import", &json!({"paths": [f]})).unwrap();
|
||||
assert_eq!(r["imported"], json!([id]), "{r}");
|
||||
let p = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap();
|
||||
assert!(!p.local && p.rating == 3, "the same record, now in the library, edits kept");
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [f]})).unwrap();
|
||||
assert_eq!(scan["duplicates"], 1, "now it is in the library: {scan}");
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
/// A browse record in Recently Deleted still counts as the path's: the scan lists the file as it did,
|
||||
/// not as a new browsed file.
|
||||
#[test]
|
||||
fn a_deleted_browse_record_still_counts_as_the_files_own() {
|
||||
let src = temp_dir("browsed-deleted");
|
||||
let f = src.join("a.png");
|
||||
write_png(&f, 76);
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [f], "local": true})).unwrap();
|
||||
let id = r["imported"][0].as_u64().unwrap();
|
||||
s.execute("photo.delete", &json!({"ids": [id]})).unwrap();
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [f]})).unwrap();
|
||||
assert_eq!(scan["candidates"][0]["duplicate"], "path", "{scan}");
|
||||
assert_eq!(scan["candidates"][0].get("local"), None, "{scan}");
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
/// A browsed file that another application replaced since (it has another size) is not what its record says: the scan
|
||||
/// reads it again, so the content stored at the browse (the old file's, which the library also has) doesn't make it a
|
||||
/// duplicate, and importing it brings the record up to date as it joins the library.
|
||||
#[test]
|
||||
fn a_browsed_file_replaced_since_is_read_again_before_it_joins_the_library() {
|
||||
let src = temp_dir("browsed-replaced");
|
||||
let (a, b) = (src.join("a.png"), src.join("b.png"));
|
||||
write_png(&a, 75);
|
||||
std::fs::copy(&a, &b).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
// b is in the library; a was only browsed, with the same bytes
|
||||
s.execute("library.import", &json!({"paths": [b]})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap();
|
||||
let id = r["imported"][0].as_u64().unwrap();
|
||||
let old = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().content_hash.clone();
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [a]})).unwrap();
|
||||
assert_eq!(scan["candidates"][0]["duplicate"], "content", "the file is what was browsed, and the library has its bytes: {scan}");
|
||||
write_png_sized(&a, 9, 64, 40);
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [a]})).unwrap();
|
||||
assert!(scan["candidates"][0]["duplicate"].is_null(), "the file that is there now is new to the library: {scan}");
|
||||
assert_eq!(scan["candidates"][0]["width"], 64, "{scan}");
|
||||
assert_eq!(scan["candidates"][0]["local"], true, "it still says it was only browsed (Copy and Move leave it out): {scan}");
|
||||
assert_eq!(scan["candidates"][0]["existing"], id, "and names the record: {scan}");
|
||||
let r = s.execute("library.import", &json!({"paths": [a]})).unwrap();
|
||||
assert_eq!(r["imported"], json!([id]), "the same record joins the library: {r}");
|
||||
let p = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap();
|
||||
assert!(!p.local, "it is in the library now");
|
||||
assert_eq!((p.width, p.height, p.file_size), (64, 40, std::fs::metadata(&a).unwrap().len()), "the record describes the file it has now");
|
||||
assert_ne!(p.content_hash, old, "and holds its content, not the old file's");
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
/// A browsed file replaced by a copy of a photo the library has is a duplicate of that photo, and its record stays
|
||||
/// browsed.
|
||||
#[test]
|
||||
fn a_browsed_file_replaced_by_a_copy_of_a_library_photo_is_a_duplicate() {
|
||||
let src = temp_dir("browsed-replaced-dup");
|
||||
let (a, c) = (src.join("a.png"), src.join("c.png"));
|
||||
write_png(&a, 75);
|
||||
write_png_sized(&c, 9, 64, 40);
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [c]})).unwrap();
|
||||
let library_id = r["imported"][0].as_u64().unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap();
|
||||
let id = r["imported"][0].as_u64().unwrap();
|
||||
std::fs::copy(&c, &a).unwrap();
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [a]})).unwrap();
|
||||
assert_eq!(scan["candidates"][0]["duplicate"], "content", "{scan}");
|
||||
assert_eq!(scan["candidates"][0]["existing"], library_id, "of the library's photo: {scan}");
|
||||
assert_eq!(scan["candidates"][0]["local"], true, "it is still the browsed record's file (Copy and Move leave it out): {scan}");
|
||||
let r = s.execute("library.import", &json!({"paths": [a]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 0, "{r}");
|
||||
assert_eq!(r["duplicates"][0]["existing"], library_id, "{r}");
|
||||
assert!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().local, "the record was not brought in");
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
/// ✕ while the sizes of browsed files are checked: a file that wasn't checked is not promoted (it stays a browsed record),
|
||||
/// where the check used to run for every file whatever the ✕ said.
|
||||
#[test]
|
||||
fn a_cancelled_import_does_not_promote_a_browsed_file_it_did_not_check() {
|
||||
use crate::import::{ImportJob, ImportOptions, commit_prepared};
|
||||
let src = temp_dir("browsed-cancel-import");
|
||||
let a = src.join("a.png");
|
||||
write_png(&a, 75);
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap();
|
||||
let id = r["imported"][0].as_u64().unwrap();
|
||||
let mut job = ImportJob::new(&mut s, ImportOptions::default()).unwrap();
|
||||
let cancel = std::sync::atomic::AtomicBool::new(true);
|
||||
let prepared = job.prepare(&[a.to_string_lossy().to_string()], &cancel);
|
||||
let report = commit_prepared(&mut s, &job.opts, job.now(), prepared).unwrap();
|
||||
assert!(report.imported.is_empty() && report.duplicates.is_empty(), "nothing was decided about the file: {report:?}");
|
||||
assert!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().local, "the record is still only browsed");
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
/// ✕ while a scan checks the sizes of browsed files: a file that wasn't checked is not offered as the record's own (it is
|
||||
/// one of the files the scan didn't reach, like the ones after it).
|
||||
#[test]
|
||||
fn a_cancelled_scan_does_not_vouch_for_a_browsed_file_it_did_not_check() {
|
||||
use crate::import::{ScanInput, ScanProgress, scan_with};
|
||||
let src = temp_dir("browsed-cancel-scan");
|
||||
let a = src.join("a.png");
|
||||
write_png(&a, 75);
|
||||
let mut s = Session::new().with_fs();
|
||||
s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap();
|
||||
let (input, paths) = ScanInput::new(&mut s, &[a.to_string_lossy().to_string()]);
|
||||
let progress = ScanProgress::default();
|
||||
progress.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let out = scan_with(input, &paths, &progress);
|
||||
assert_eq!(out.candidates.len(), 1);
|
||||
assert!(!out.candidates[0].local && out.candidates[0].error.is_some(), "not vouched for as the browsed record's file: {:?}", out.candidates[0]);
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
/// A file of its own with the new content of a replaced browsed file stands in for it when copying leaves it out.
|
||||
#[test]
|
||||
fn a_twin_of_a_replaced_browsed_file_stands_in_for_it_when_copying() {
|
||||
let src = temp_dir("browsed-replaced-twin");
|
||||
let (a, d) = (src.join("a.png"), src.join("d.png"));
|
||||
write_png(&a, 75);
|
||||
let mut s = Session::new().with_fs();
|
||||
s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap();
|
||||
write_png_sized(&a, 9, 64, 40);
|
||||
std::fs::copy(&a, &d).unwrap();
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [a, d]})).unwrap();
|
||||
let found = scan["candidates"].as_array().unwrap();
|
||||
assert_eq!(found[0]["local"], true, "{scan}");
|
||||
assert_eq!(found[1]["duplicate"], "content", "{scan}");
|
||||
assert_eq!(found[1]["browsedTwin"], found[0]["path"], "{scan}");
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
/// A browsed file replaced by a copy of another browsed file isn't a stand-in: the first file of its own is.
|
||||
#[test]
|
||||
fn a_replaced_browsed_file_does_not_take_the_stand_in_of_another_browsed_file() {
|
||||
let src = temp_dir("browsed-replaced-standin");
|
||||
let (a, b, d) = (src.join("a.png"), src.join("b.png"), src.join("d.png"));
|
||||
write_png(&a, 75);
|
||||
write_png_sized(&b, 9, 64, 40);
|
||||
let mut s = Session::new().with_fs();
|
||||
s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap();
|
||||
std::fs::copy(&a, &b).unwrap();
|
||||
std::fs::copy(&a, &d).unwrap();
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [a, b, d]})).unwrap();
|
||||
let found = scan["candidates"].as_array().unwrap();
|
||||
assert!(found[1]["browsedTwin"].is_null(), "a browsed file doesn't stand in: {scan}");
|
||||
assert_eq!(found[2]["browsedTwin"], found[0]["path"], "the file of its own does: {scan}");
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
/// "Import as new" replaces the trashed library photo with the same content when the browsed twin
|
||||
/// is promoted, as it does for a new file.
|
||||
#[test]
|
||||
fn promoting_a_browsed_twin_as_new_replaces_the_trashed_library_photo() {
|
||||
let src = temp_dir("browsed-fresh");
|
||||
let original = src.join("original.png");
|
||||
let twin = src.join("browsed.png");
|
||||
write_png(&original, 77);
|
||||
std::fs::copy(&original, &twin).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [original]})).unwrap();
|
||||
let old = r["imported"][0].as_u64().unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [twin], "local": true})).unwrap();
|
||||
let local = r["imported"][0].as_u64().unwrap();
|
||||
s.execute("photo.delete", &json!({"ids": [old]})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [twin], "onDeleted": "fresh"})).unwrap();
|
||||
assert_eq!(r["imported"], json!([local]), "{r}");
|
||||
let trashed = s.catalog.photos().filter(|p| p.deleted).count();
|
||||
assert_eq!(trashed, 0, "the trashed twin is gone");
|
||||
assert!(s.catalog.photo(lightcraft_catalog::PhotoId(local)).is_some_and(|p| p.in_library()));
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
/// Restoring a trashed library photo by the content of a browsed file doesn't relink it onto the
|
||||
/// path the browse record holds: that would leave two records on one file.
|
||||
#[test]
|
||||
fn restoring_by_a_browsed_twin_does_not_relink_onto_its_path() {
|
||||
let src = temp_dir("browsed-restore");
|
||||
let original = src.join("original.png");
|
||||
let renamed = src.join("renamed.png");
|
||||
write_png(&original, 78);
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [original]})).unwrap();
|
||||
let old = r["imported"][0].as_u64().unwrap();
|
||||
std::fs::rename(&original, &renamed).unwrap();
|
||||
s.execute("photo.delete", &json!({"ids": [old]})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [renamed], "local": true})).unwrap();
|
||||
let local = r["imported"][0].as_u64().unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [renamed]})).unwrap();
|
||||
assert_eq!(r["restored"], json!([old]), "{r}");
|
||||
let on_path = s.catalog.photos().filter(|p| matches!(&p.source, lightcraft_catalog::Source::File { path } if Path::new(path) == renamed)).count();
|
||||
assert_eq!(on_path, 1, "one record holds the renamed file");
|
||||
assert!(s.catalog.photo(lightcraft_catalog::PhotoId(local)).is_some_and(|p| p.local), "the browse record is left alone");
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_twin_does_not_block_reimport_after_permanent_delete_and_restart() {
|
||||
use lightcraft_catalog::PhotoId;
|
||||
for mode in ["add", "copy"] {
|
||||
let src = temp_dir(&format!("local-twin-src-{mode}"));
|
||||
let lib = temp_dir(&format!("local-twin-lib-{mode}"));
|
||||
let original = src.join("original.png");
|
||||
let twin = src.join("browsed.png");
|
||||
write_png(&original, 71);
|
||||
std::fs::copy(&original, &twin).unwrap();
|
||||
let bytes = std::fs::read(&original).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [original], "mode": mode})).unwrap();
|
||||
let old = r["imported"][0].as_u64().unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [twin], "local": true})).unwrap();
|
||||
let local = PhotoId(r["imported"][0].as_u64().unwrap());
|
||||
let before = s.catalog.photo(local).unwrap().clone();
|
||||
s.execute("photo.delete", &json!({"ids": [old]})).unwrap();
|
||||
s.execute("library.source", &json!({"kind": "recentlyDeleted"})).unwrap();
|
||||
s.execute("library.select", &json!({"ids": [old]})).unwrap();
|
||||
s.execute("photo.deletePermanently", &json!({"ids": [old]})).unwrap();
|
||||
s.close_library().unwrap();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [original]})).unwrap();
|
||||
assert_eq!(scan["duplicates"], 0, "a browsed copy is not a library duplicate: {scan}");
|
||||
let r = s.execute("library.import", &json!({"paths": [original], "mode": mode})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1, "{r}");
|
||||
assert_eq!(ids(&r, "restored"), 0);
|
||||
assert_eq!(ids(&r, "duplicates"), 0);
|
||||
assert_ne!(r["imported"][0], old);
|
||||
assert_eq!(s.catalog.photo(local).unwrap(), &before, "leave the other path's browse record alone");
|
||||
assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1);
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [original]})).unwrap();
|
||||
assert_eq!(scan["duplicates"], 1, "the actual library photo still counts");
|
||||
assert_eq!(std::fs::read(&original).unwrap(), bytes);
|
||||
assert_eq!(std::fs::read(&twin).unwrap(), bytes);
|
||||
s.close_library().unwrap();
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
let _ = std::fs::remove_dir_all(lib);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_twin_import_matches_the_library_photo_before_promoting() {
|
||||
use lightcraft_catalog::PhotoId;
|
||||
let src = temp_dir("local-twin-priority");
|
||||
let original = src.join("original.png");
|
||||
let twin = src.join("browsed.png");
|
||||
write_png(&original, 72);
|
||||
std::fs::copy(&original, &twin).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [original]})).unwrap();
|
||||
let id = r["imported"][0].as_u64().unwrap();
|
||||
s.execute("photo.rate", &json!({"ids": [id], "rating": 5})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [twin], "local": true})).unwrap();
|
||||
let local = PhotoId(r["imported"][0].as_u64().unwrap());
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [twin]})).unwrap();
|
||||
assert_eq!(scan["duplicates"], 1, "{scan}");
|
||||
assert_eq!(scan["candidates"][0]["existing"], id);
|
||||
let r = s.execute("library.import", &json!({"paths": [twin]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 0);
|
||||
assert_eq!(r["duplicates"][0]["existing"], id);
|
||||
s.execute("photo.delete", &json!({"ids": [id]})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [twin], "onDeleted": "skip"})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 0, "skip must not promote the local twin: {r}");
|
||||
assert_eq!(r["duplicates"][0]["existingDeleted"], true);
|
||||
let r = s.execute("library.import", &json!({"paths": [twin]})).unwrap();
|
||||
assert_eq!(r["restored"], json!([id]));
|
||||
assert!(s.catalog.photo(local).unwrap().local);
|
||||
assert_eq!(s.catalog.photo(PhotoId(id)).unwrap().rating, 5);
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_twins_are_deduplicated_when_promoted_in_one_import() {
|
||||
let src = temp_dir("local-twin-batch");
|
||||
let a = src.join("a.png");
|
||||
let b = src.join("b.png");
|
||||
let c = src.join("c.png");
|
||||
write_png(&a, 73);
|
||||
std::fs::copy(&a, &b).unwrap();
|
||||
std::fs::copy(&a, &c).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 2, "browsing shows both paths: {r}");
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [a, b, c]})).unwrap();
|
||||
assert_eq!(scan["duplicates"], 2, "only one candidate per content: {scan}");
|
||||
let r = s.execute("library.import", &json!({"paths": [a, b, c]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1, "{r}");
|
||||
assert_eq!(ids(&r, "duplicates"), 2);
|
||||
assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1);
|
||||
assert_eq!(s.catalog.photos().filter(|p| p.local).count(), 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 0);
|
||||
assert_eq!(s.catalog.photos().filter(|p| p.local).count(), 2);
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twins_of_a_browsed_photo_are_copies_in_the_source_not_library_duplicates() {
|
||||
let src = temp_dir("local-twin-scan");
|
||||
let a = src.join("a.png");
|
||||
let b = src.join("b.png");
|
||||
let c = src.join("c.png");
|
||||
let d = src.join("d.png");
|
||||
write_png(&a, 75);
|
||||
std::fs::copy(&a, &b).unwrap();
|
||||
std::fs::copy(&a, &c).unwrap();
|
||||
std::fs::copy(&a, &d).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap();
|
||||
let scan = s.execute("library.importPreview", &json!({"paths": [a, b, c, d]})).unwrap();
|
||||
let found = scan["candidates"].as_array().unwrap();
|
||||
assert_eq!(found.len(), 4, "{scan}");
|
||||
assert_eq!(found[0]["local"], true, "{scan}");
|
||||
assert!(found[0]["duplicate"].is_null(), "the first browsed copy is offered: {scan}");
|
||||
for twin in &found[1..] {
|
||||
assert_eq!(twin["duplicate"], "content", "{scan}");
|
||||
assert!(twin["existing"].is_null(), "no library photo has these bytes, a browsed record isn't one: {scan}");
|
||||
}
|
||||
// (copying leaves the browsed photo out: the first file of its own stands in for it, once)
|
||||
assert!(found[1]["browsedTwin"].is_null(), "a browsed twin doesn't: {scan}");
|
||||
assert_eq!(found[2]["browsedTwin"], found[0]["path"], "{scan}");
|
||||
assert!(found[3]["browsedTwin"].is_null(), "{scan}");
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_twin_promotion_counts_across_background_import_batches() {
|
||||
use crate::import::{ImportJob, ImportOptions, commit_prepared};
|
||||
let src = temp_dir("local-twin-worker");
|
||||
let a = src.join("a.png");
|
||||
let b = src.join("b.png");
|
||||
let c = src.join("c.png");
|
||||
write_png(&a, 74);
|
||||
std::fs::copy(&a, &b).unwrap();
|
||||
std::fs::copy(&a, &c).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap();
|
||||
let id = r["imported"][0].as_u64().unwrap();
|
||||
s.execute("photo.rate", &json!({"ids": [id], "rating": 4})).unwrap();
|
||||
let mut job = ImportJob::new(&mut s, ImportOptions::default()).unwrap();
|
||||
let cancel = std::sync::atomic::AtomicBool::new(false);
|
||||
let first = job.prepare(&[a.to_string_lossy().to_string()], &cancel);
|
||||
let report = commit_prepared(&mut s, &job.opts, job.now(), first).unwrap();
|
||||
assert_eq!(report.imported, [id], "promote the existing record with its edits");
|
||||
assert_eq!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().rating, 4);
|
||||
let next = job.prepare(&[b.to_string_lossy().to_string(), c.to_string_lossy().to_string()], &cancel);
|
||||
let report = commit_prepared(&mut s, &job.opts, job.now(), next).unwrap();
|
||||
assert!(report.imported.is_empty());
|
||||
assert_eq!(report.duplicates.len(), 2);
|
||||
assert!(report.duplicates.iter().all(|d| d.existing == Some(id)));
|
||||
assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1);
|
||||
let _ = std::fs::remove_dir_all(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursive_import_with_duplicates() {
|
||||
let src = temp_dir("src");
|
||||
|
||||
@@ -2530,6 +2530,7 @@
|
||||
"Next": "Další",
|
||||
"Get Started": "Začít",
|
||||
"Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Klíčová slova a předvolby se použijí jen u nových souborů, ne u fotografií, které už jsou v Místních souborech",
|
||||
"This album is in a loop, so it shows nothing": "Toto album je ve smyčce, a proto nic nezobrazuje",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Testuje samo sebe: změňte jeho pravidla (Upravit inteligentní album…)",
|
||||
"Can't add to an album folder": "Nelze přidat do složky alb",
|
||||
|
||||
@@ -3587,6 +3587,7 @@
|
||||
"Welcome": "Willkommen",
|
||||
"Next": "Weiter",
|
||||
"Get Started": "Loslegen",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Stichwörter und Vorgaben gelten nur für neue Dateien, nicht für Fotos, die schon in „Lokal“ sind",
|
||||
"This album is in a loop, so it shows nothing": "Dieses Album ist in einem Kreis und zeigt deshalb nichts",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Es prüft sich selbst: Ändere seine Regeln (Smart-Album bearbeiten…)",
|
||||
"Can't add to an album folder": "Nicht zu einem Albenordner hinzufügbar",
|
||||
|
||||
@@ -2484,6 +2484,7 @@
|
||||
"Welcome": "Bienvenido",
|
||||
"Next": "Siguiente",
|
||||
"Get Started": "Empezar",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Las palabras clave y los ajustes preestablecidos solo se aplican a archivos nuevos, no a fotos que ya están en Local",
|
||||
"This album is in a loop, so it shows nothing": "Este álbum está en un bucle, así que no muestra nada",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Se comprueba a sí mismo: cambia sus reglas (Editar álbum inteligente…)",
|
||||
"Can't add to an album folder": "No se puede añadir a una carpeta de álbumes",
|
||||
|
||||
@@ -2432,6 +2432,7 @@
|
||||
"Folder name": "Kansion nimi",
|
||||
"Its templates move to User Templates.": "Sen mallipohjat siirretään kansioon Käyttäjän mallipohjat.",
|
||||
"Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Avainsanat ja esiasetukset koskevat vain uusia tiedostoja, eivät kuvia, jotka ovat jo Paikallisessa",
|
||||
"This album is in a loop, so it shows nothing": "Tämä albumi on silmukassa, joten se ei näytä mitään",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Se testaa itseään: muuta sen sääntöjä (Muokkaa älyalbumia…)",
|
||||
"Filter settings": "Suodata asetuksia",
|
||||
|
||||
@@ -3665,6 +3665,7 @@
|
||||
"Welcome": "Bienvenue",
|
||||
"Next": "Suivant",
|
||||
"Get Started": "Commencer",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Les mots-clés et les préréglages ne s'appliquent qu'aux nouveaux fichiers, pas aux photos déjà dans Local",
|
||||
"This album is in a loop, so it shows nothing": "Cet album est pris dans une boucle : il n'affiche rien",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Il se teste lui-même : modifiez ses règles (Modifier l'album intelligent…)",
|
||||
"Can't add to an album folder": "Impossible d’ajouter à un dossier d’albums",
|
||||
|
||||
@@ -2446,6 +2446,7 @@
|
||||
"Folder name": "Nama folder",
|
||||
"Its templates move to User Templates.": "Templatnya dipindahkan ke Templat pengguna.",
|
||||
"Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Kata kunci dan prasetel hanya berlaku untuk berkas baru, bukan foto yang sudah ada di Lokal",
|
||||
"This album is in a loop, so it shows nothing": "Album ini berada dalam perulangan, jadi tidak menampilkan apa pun",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Album ini menjadikan dirinya sendiri syarat: ubah aturannya (Edit album pintar…)",
|
||||
"Filter settings": "Filter pengaturan",
|
||||
|
||||
@@ -2645,6 +2645,7 @@
|
||||
"Next": "Avanti",
|
||||
"Get Started": "Inizia",
|
||||
"Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Parole chiave e preset si applicano solo ai file nuovi, non alle foto già in Locale",
|
||||
"This album is in a loop, so it shows nothing": "Questo album è in un ciclo, quindi non mostra nulla",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Verifica se stesso: modifica le sue regole (Modifica album smart…)",
|
||||
"Can't add to an album folder": "Impossibile aggiungere a una cartella di album",
|
||||
|
||||
@@ -2483,6 +2483,7 @@
|
||||
"Welcome": "ようこそ",
|
||||
"Next": "次へ",
|
||||
"Get Started": "始める",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "キーワードとプリセットは新しいファイルにのみ適用され、すでにローカルにある写真には適用されません",
|
||||
"This album is in a loop, so it shows nothing": "このアルバムは循環しているため、何も表示されません",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "自分自身を条件にしています。条件を変更してください(スマートアルバムを編集…)",
|
||||
"Can't add to an album folder": "アルバムフォルダには追加できません",
|
||||
|
||||
@@ -3742,6 +3742,7 @@
|
||||
"Folder name": "საქაღალდის სახელი",
|
||||
"Its templates move to User Templates.": "მისი შაბლონები გადავა „მომხმარებლის შაბლონებში“.",
|
||||
"Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "საკვანძო სიტყვები და პრესეტები მხოლოდ ახალ ფაილებზე მოქმედებს და არა იმ ფოტოებზე, რომლებიც უკვე ლოკალშია",
|
||||
"This album is in a loop, so it shows nothing": "ეს ალბომი ციკლშია, ამიტომ არაფერს აჩვენებს",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "ის საკუთარ თავს ამოწმებს: შეცვალეთ მისი წესები (სმარტ-ალბომის რედაქტირება…)",
|
||||
"Filter settings": "პარამეტრების გაფილტვრა",
|
||||
|
||||
@@ -2408,6 +2408,7 @@
|
||||
"Next": "Dalej",
|
||||
"Get Started": "Zaczynamy",
|
||||
"Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Słowa kluczowe i ustawienia predefiniowane dotyczą tylko nowych plików, nie zdjęć, które już są w Lokalnych",
|
||||
"This album is in a loop, so it shows nothing": "Ten album jest w pętli, więc niczego nie pokazuje",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Sprawdza samego siebie: zmień jego reguły (Edytuj album inteligentny…)",
|
||||
"Can't add to an album folder": "Nie można dodać do folderu albumów",
|
||||
|
||||
@@ -2328,6 +2328,7 @@
|
||||
"Welcome": "Bem-vindo",
|
||||
"Next": "Próximo",
|
||||
"Get Started": "Começar",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Palavras-chave e predefinições valem só para arquivos novos, não para fotos que já estão em Local",
|
||||
"This album is in a loop, so it shows nothing": "Este álbum está em um ciclo, então não mostra nada",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Ele testa a si mesmo: mude as regras dele (Editar álbum inteligente…)",
|
||||
"Can't add to an album folder": "Não é possível adicionar a uma pasta de álbuns",
|
||||
|
||||
@@ -2690,6 +2690,7 @@
|
||||
"Welcome": "Добро пожаловать",
|
||||
"Next": "Далее",
|
||||
"Get Started": "Начать",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Ключевые слова и пресеты применяются только к новым файлам, а не к фото, которые уже есть в «Локальных»",
|
||||
"This album is in a loop, so it shows nothing": "Этот альбом попал в цикл, поэтому ничего не показывает",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Он проверяет сам себя: измените его условия (Изменить смарт-альбом…)",
|
||||
"Can't add to an album folder": "Нельзя добавить в папку альбомов",
|
||||
|
||||
@@ -3859,6 +3859,7 @@
|
||||
"Folder name": "Mappnamn",
|
||||
"Its templates move to User Templates.": "Dess mallar flyttas till Användarmallar.",
|
||||
"Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Nyckelord och förinställningar gäller bara nya filer, inte foton som redan finns i Lokalt",
|
||||
"This album is in a loop, so it shows nothing": "Det här albumet ingår i en loop och visar därför ingenting",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Det testar sig självt: ändra dess regler (Redigera smart album…)",
|
||||
"Filter settings": "Filtrera inställningar",
|
||||
|
||||
@@ -2480,6 +2480,7 @@
|
||||
"Welcome": "Ласкаво просимо",
|
||||
"Next": "Далі",
|
||||
"Get Started": "Почати",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Ключові слова та пресети застосовуються лише до нових файлів, а не до фото, що вже є в «Локальних»",
|
||||
"This album is in a loop, so it shows nothing": "Цей альбом потрапив у цикл, тому нічого не показує",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Він перевіряє сам себе: змініть його правила (Редагувати смарт-альбом…)",
|
||||
"Can't add to an album folder": "Не можна додати до теки альбомів",
|
||||
|
||||
@@ -2758,6 +2758,7 @@
|
||||
"Folder name": "Tên thư mục",
|
||||
"Its templates move to User Templates.": "Các mẫu trong đó sẽ được chuyển vào Mẫu người dù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",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "Từ khóa và cài đặt sẵn chỉ áp dụng cho tệp mới, không áp dụng cho ảnh đã có trong Cục bộ",
|
||||
"This album is in a loop, so it shows nothing": "Album này nằm trong một vòng lặp nên không hiển thị gì",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "Album này tự kiểm tra chính nó: hãy đổi quy tắc của nó (Chỉnh sửa album thông minh…)",
|
||||
"Filter settings": "Lọc cài đặt",
|
||||
|
||||
@@ -2483,6 +2483,7 @@
|
||||
"Welcome": "欢迎",
|
||||
"Next": "下一步",
|
||||
"Get Started": "开始使用",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "关键词和预设仅应用于新文件,不适用于已在“本地”中的照片",
|
||||
"This album is in a loop, so it shows nothing": "此相册处于循环中,因此不显示任何内容",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "它引用了自身:请更改其规则(编辑智能相册…)",
|
||||
"Can't add to an album folder": "无法添加到相册文件夹",
|
||||
|
||||
@@ -2484,6 +2484,7 @@
|
||||
"Welcome": "歡迎",
|
||||
"Next": "下一步",
|
||||
"Get Started": "開始使用",
|
||||
"Keywords and presets apply to new files only, not to photos already in Local": "關鍵字和預設集僅套用於新檔案,不適用於已在「本機」中的照片",
|
||||
"This album is in a loop, so it shows nothing": "此相簿處於循環中,因此不顯示任何內容",
|
||||
"It tests itself: change its rules (Edit Smart Album…)": "它引用了自身:請變更其規則(編輯智慧型相簿…)",
|
||||
"Can't add to an album folder": "無法加入相簿資料夾",
|
||||
|
||||
@@ -150,10 +150,46 @@ impl ImportDialog {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Candidate `i` is a file whose photo is only browsed (Local): the scan offers it (it isn't in the
|
||||
/// library). Importing it brings that record into the library where
|
||||
/// the file is, whatever the transfer mode.
|
||||
pub fn is_browsed(&self, i: usize) -> bool {
|
||||
self.candidates.get(i).is_some_and(|c| c.error.is_none() && c.duplicate.is_none() && c.local)
|
||||
}
|
||||
/// Candidate `i` can be checked: a readable file the library doesn't have, or one whose photo
|
||||
/// is in Recently Deleted — even with "Leave them", a click picks it (issue #1285).
|
||||
/// is in Recently Deleted — even with "Leave them", a click picks it (issue #1285). A browsed
|
||||
/// photo can't be copied or moved: the engine would add it in place, so copying leaves it out
|
||||
/// (and brings in its first twin instead, [`ImportDialog::is_copy_twin`]).
|
||||
pub fn importable(&self, i: usize) -> bool {
|
||||
self.candidates.get(i).is_some_and(|c| c.error.is_none() && (c.duplicate.is_none() || self.is_trashed(i)))
|
||||
&& !(self.copy && self.candidates.get(i).is_some_and(|c| c.local))
|
||||
|| self.is_copy_twin(i)
|
||||
}
|
||||
/// Copying leaves a browsed photo out, so a file with the same bytes that no library photo has
|
||||
/// is what brings that content in: candidate `i` is that file (the scan names the browsed photo
|
||||
/// it stands in for, `browsed_twin`, on the first one only).
|
||||
pub fn is_copy_twin(&self, i: usize) -> bool {
|
||||
self.copy
|
||||
&& self.candidates.get(i).is_some_and(|c| {
|
||||
c.browsed_twin.is_some() && !c.local && c.error.is_none() && c.duplicate.as_deref() == Some("content") && c.existing.is_none()
|
||||
})
|
||||
}
|
||||
/// Choose how the files are brought in. Switching to copying offers the file that stands in for
|
||||
/// a browsed photo ([`ImportDialog::is_copy_twin`]), checked; switching to adding in place takes
|
||||
/// it away again.
|
||||
pub fn set_transfer(&mut self, copy: bool, move_files: bool) {
|
||||
let switched = copy != self.copy;
|
||||
self.copy = copy;
|
||||
self.move_files = copy && move_files;
|
||||
for i in (0..self.candidates.len()).filter(|_| switched) {
|
||||
if self.candidates[i].browsed_twin.is_some() && !self.candidates[i].local {
|
||||
// (a dialog read back may hold fewer check marks than candidates)
|
||||
let twin = self.is_copy_twin(i);
|
||||
if let Some(checked) = self.checked.get_mut(i) {
|
||||
*checked = twin;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Candidate `i` is checked by Check All and the file type toggles: with "Leave them", a file in
|
||||
/// Recently Deleted is only checked by hand.
|
||||
@@ -170,7 +206,7 @@ impl ImportDialog {
|
||||
}
|
||||
/// Any file of type `ty` is checked.
|
||||
pub fn type_checked(&self, ty: &str) -> bool {
|
||||
self.candidates.iter().zip(&self.checked).any(|(c, on)| *on && file_type(c) == ty)
|
||||
self.candidates.iter().zip(&self.checked).enumerate().any(|(i, (c, on))| *on && self.importable(i) && file_type(c) == ty)
|
||||
}
|
||||
/// Check (the importable ones) or uncheck every file of type `ty`: the raws only, say, and not
|
||||
/// the JPEGs kept beside them (issue #344).
|
||||
@@ -251,6 +287,22 @@ impl ImportDialog {
|
||||
o => Ok(Some(o.to_string())),
|
||||
}
|
||||
}
|
||||
/// Importing checked candidate `i` as it stands joins the library with the browsed record it
|
||||
/// names, as the engine's `Promote` does: a browsed file the library doesn't have, or one whose
|
||||
/// content is in Recently Deleted under "Import as new" (which replaces the trashed photo).
|
||||
/// "Restore them" brings the trashed photo back instead and "Leave them" skips the file.
|
||||
fn promotes_browsed(&self, i: usize) -> bool {
|
||||
!self.copy
|
||||
&& self.checked.get(i).copied().unwrap_or(false)
|
||||
&& self.candidates.get(i).is_some_and(|c| c.local && c.error.is_none())
|
||||
&& (self.is_browsed(i) || (self.is_trashed(i) && self.on_deleted == "fresh"))
|
||||
}
|
||||
/// Keywords or a preset are set while a checked browsed photo would join the library as it is:
|
||||
/// the engine applies them to new files only, so the review says so.
|
||||
fn options_skip_browsed(&self) -> bool {
|
||||
let has_options = !self.keywords().is_empty() || !self.preset.is_empty() || !self.metadata_preset.is_empty();
|
||||
has_options && (0..self.candidates.len()).any(|i| self.promotes_browsed(i))
|
||||
}
|
||||
fn keywords(&self) -> Vec<String> {
|
||||
self.keywords.split(',').map(str::trim).filter(|k| !k.is_empty()).map(str::to_string).collect()
|
||||
}
|
||||
@@ -294,6 +346,139 @@ mod tests {
|
||||
assert!(app.import.is_none());
|
||||
}
|
||||
|
||||
/// A file whose photo is only browsed (Local) comes from the scan as an ordinary candidate that
|
||||
/// still names its record: offered when adding in place; copying or moving would not copy it
|
||||
/// (the engine adds it where it is), so there it counts as already in the library.
|
||||
#[test]
|
||||
fn a_browsed_photo_is_importable_only_when_adding_in_place() {
|
||||
let mut d = dialog();
|
||||
d.candidates[5].local = true;
|
||||
assert!(d.is_browsed(5) && d.importable(5));
|
||||
assert_eq!(dup_counts(&d), (0, 1, 0), "adding in place: not skipped");
|
||||
d.copy = true;
|
||||
assert!(!d.importable(5), "copying leaves it where it is");
|
||||
assert!(!d.selected_paths().contains(&"img5.jpg".to_string()));
|
||||
assert_eq!(dup_counts(&d), (1, 1, 0));
|
||||
assert!(!d.is_browsed(3), "a duplicate isn't browsed");
|
||||
// its library twin is in Recently Deleted: still offered in place ("Import as new" brings it in), never copied
|
||||
d.copy = false;
|
||||
d.candidates[4].local = true;
|
||||
d.candidates[4].duplicate = Some("content".into());
|
||||
d.set_trashed(vec![false, false, false, false, true, false]);
|
||||
assert!(d.importable(4));
|
||||
d.copy = true;
|
||||
assert!(!d.importable(4), "copying would add it where it is");
|
||||
}
|
||||
|
||||
/// a.png and b.png are browsed copies of one content, c.png and d.png new files with it; the scan
|
||||
/// names a.png on c.png only (as in `twins_of_a_browsed_photo_are_copies_in_the_source_not_library_duplicates`).
|
||||
fn browsed_twins() -> ImportDialog {
|
||||
let a = ImportCandidate { path: "a.png".into(), local: true, existing: Some(1), ..Default::default() };
|
||||
let twin = |path: &str, local: bool, stands_in: bool| ImportCandidate {
|
||||
path: path.into(),
|
||||
local,
|
||||
duplicate: Some("content".into()),
|
||||
browsed_twin: stands_in.then(|| "a.png".into()),
|
||||
..Default::default()
|
||||
};
|
||||
ImportDialog::new(vec![a, twin("b.png", true, false), twin("c.png", false, true), twin("d.png", false, false)])
|
||||
}
|
||||
|
||||
/// Adding in place the browsed photo is the one brought in and its twins are copies in the
|
||||
/// source, not photos the library has.
|
||||
#[test]
|
||||
fn twins_of_a_browsed_photo_are_copies_in_the_source_not_in_the_library() {
|
||||
let d = browsed_twins();
|
||||
assert_eq!(d.selected_paths(), ["a.png"]);
|
||||
assert_eq!(dup_counts(&d), (0, 3, 0), "three identical copies, none already in the library");
|
||||
}
|
||||
|
||||
/// Copying leaves the browsed photo out (the engine would add it where it is), so the first
|
||||
/// twin that is a file of its own is what copying brings in: the content isn't in the library.
|
||||
#[test]
|
||||
fn copying_brings_in_the_first_twin_of_a_browsed_photo() {
|
||||
let mut d = browsed_twins();
|
||||
d.copy = true;
|
||||
assert!(!d.importable(0) && !d.importable(1), "browsed photos are not copied");
|
||||
assert!(d.importable(2), "the first copy that is a file of its own is");
|
||||
assert!(!d.importable(3), "the next one is a copy of it");
|
||||
d.checked[2] = true;
|
||||
assert_eq!(d.selected_paths(), ["c.png"]);
|
||||
assert_eq!(dup_counts(&d), (1, 2, 0), "a (browsed) counts as there already; b and d are copies; c is offered");
|
||||
// back in place: it is a copy again
|
||||
d.copy = false;
|
||||
assert!(!d.importable(2));
|
||||
assert_eq!(d.selected_paths(), ["a.png"]);
|
||||
}
|
||||
|
||||
/// Switching to Copy checks the twin that copying brings in, and switching back unchecks it.
|
||||
#[test]
|
||||
fn switching_the_transfer_checks_the_twin_that_copying_brings_in() {
|
||||
let mut d = browsed_twins();
|
||||
d.set_transfer(true, false);
|
||||
assert_eq!(d.selected_paths(), ["c.png"]);
|
||||
d.set_transfer(false, false);
|
||||
assert_eq!(d.selected_paths(), ["a.png"]);
|
||||
assert!(!d.checked[2]);
|
||||
}
|
||||
|
||||
/// Choosing the transfer already chosen doesn't undo what was checked by hand.
|
||||
#[test]
|
||||
fn choosing_the_transfer_again_keeps_a_manual_uncheck() {
|
||||
let mut d = browsed_twins();
|
||||
d.set_transfer(true, false);
|
||||
d.checked[2] = false;
|
||||
d.set_transfer(true, true);
|
||||
assert!(d.selected_paths().is_empty(), "Move after Copy keeps the choice");
|
||||
}
|
||||
|
||||
/// A file type's toggle is on only for files that can be imported now.
|
||||
#[test]
|
||||
fn a_file_type_toggle_ignores_browsed_photos_that_copying_cannot_import() {
|
||||
let mut c = ImportCandidate { path: "a.png".into(), local: true, ..Default::default() };
|
||||
c.format = "PNG".into();
|
||||
let mut d = ImportDialog::new(vec![c]);
|
||||
d.copy = true;
|
||||
assert!(!d.type_checked("PNG"));
|
||||
d.copy = false;
|
||||
assert!(d.type_checked("PNG"));
|
||||
}
|
||||
|
||||
/// The review warns that keywords and presets skip a browsed photo only when it matters.
|
||||
#[test]
|
||||
fn keywords_and_presets_are_flagged_only_when_a_browsed_photo_would_skip_them() {
|
||||
let c = ImportCandidate { path: "a.png".into(), local: true, ..Default::default() };
|
||||
let mut d = ImportDialog::new(vec![c]);
|
||||
assert!(!d.options_skip_browsed(), "nothing set, nothing to skip");
|
||||
d.keywords = "beach".into();
|
||||
assert!(d.options_skip_browsed());
|
||||
d.checked[0] = false;
|
||||
assert!(!d.options_skip_browsed(), "unchecked: not imported anyway");
|
||||
d.checked[0] = true;
|
||||
d.copy = true;
|
||||
assert!(!d.options_skip_browsed(), "copying doesn't offer it");
|
||||
}
|
||||
|
||||
/// A browsed photo whose content is in Recently Deleted is promoted only by "Import as new" (the
|
||||
/// engine's `Fresh`, which purges the trashed twin); "Restore them" brings the trashed photo back
|
||||
/// and "Leave them" skips the file, so neither imports the browsed record and the notice stays off.
|
||||
#[test]
|
||||
fn the_notice_follows_the_engines_promotion_of_a_browsed_photo_with_a_trashed_twin() {
|
||||
let c = ImportCandidate { path: "a.png".into(), local: true, duplicate: Some("content".into()), existing: Some(7), ..Default::default() };
|
||||
let mut d = ImportDialog::new(vec![c]);
|
||||
d.set_trashed(vec![true]);
|
||||
d.keywords = "beach".into();
|
||||
d.set_on_deleted("restore");
|
||||
assert!(d.checked[0] && !d.options_skip_browsed(), "Restore brings the trashed photo back, not the browsed one");
|
||||
d.set_on_deleted("fresh");
|
||||
assert!(d.checked[0] && d.options_skip_browsed(), "Import as new promotes the browsed record without the keywords");
|
||||
d.set_on_deleted("");
|
||||
assert!(!d.checked[0] && !d.options_skip_browsed(), "Leave them: unchecked");
|
||||
d.set_on_deleted("fresh");
|
||||
d.copy = true;
|
||||
assert!(!d.options_skip_browsed(), "copying doesn't offer it");
|
||||
}
|
||||
|
||||
/// Identical copies inside the source folder are not "already in the library" (a fresh library
|
||||
/// said "8 already in the library").
|
||||
#[test]
|
||||
|
||||
@@ -73,8 +73,12 @@ pub(crate) fn note_dialog_bottom(ui: &egui::Ui) {
|
||||
/// the same bytes as one earlier in the list (no library photo) is a copy in the source.
|
||||
pub(super) fn dup_counts(d: &ImportDialog) -> (usize, usize, usize) {
|
||||
let trashed = d.trashed.iter().filter(|t| **t).count();
|
||||
let in_source = d.candidates.iter().filter(|c| c.duplicate.as_deref() == Some("content") && c.existing.is_none()).count();
|
||||
let dups = d.candidates.iter().filter(|c| c.duplicate.is_some()).count().saturating_sub(trashed).saturating_sub(in_source);
|
||||
// (a copy of a browsed photo that copying brings in, because it leaves the browsed one out, is neither)
|
||||
let twins = (0..d.candidates.len()).filter(|i| d.is_copy_twin(*i)).count();
|
||||
let in_source = d.candidates.iter().filter(|c| c.duplicate.as_deref() == Some("content") && c.existing.is_none()).count() - twins;
|
||||
// (a browsed photo isn't offered while copying: it counts as already there)
|
||||
let browsed = if d.copy { (0..d.candidates.len()).filter(|i| d.is_browsed(*i)).count() } else { 0 };
|
||||
let dups = (d.candidates.iter().filter(|c| c.duplicate.is_some()).count() + browsed).saturating_sub(trashed + twins).saturating_sub(in_source);
|
||||
(dups, in_source, trashed)
|
||||
}
|
||||
|
||||
@@ -204,23 +208,20 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {
|
||||
.on_hover_text(crate::i18n::tr("Reference the files where they are"))
|
||||
.clicked()
|
||||
{
|
||||
d.copy = false;
|
||||
d.move_files = false;
|
||||
d.set_transfer(false, false);
|
||||
}
|
||||
let can_copy = app.session.library.as_ref().is_some_and(|l| l.on_disk) || app.services.pick_folder.is_some();
|
||||
let r =
|
||||
ui.add_enabled_ui(can_copy, |ui| crate::widgets::text_button(ui, "importCopy", crate::i18n::tr("Copy"), d.copy && !d.move_files)).inner;
|
||||
if r.on_hover_text(crate::i18n::tr("Copy the files (into the library's Originals/, or a folder you choose)")).clicked() {
|
||||
d.copy = true;
|
||||
d.move_files = false;
|
||||
d.set_transfer(true, false);
|
||||
}
|
||||
let r =
|
||||
ui.add_enabled_ui(can_copy, |ui| crate::widgets::text_button(ui, "importMove", crate::i18n::tr("Move"), d.copy && d.move_files)).inner;
|
||||
if r.on_hover_text(crate::i18n::tr("Move the files (into the library's Originals/, or a folder you choose), removing them from the source"))
|
||||
.clicked()
|
||||
{
|
||||
d.copy = true;
|
||||
d.move_files = true;
|
||||
d.set_transfer(true, true);
|
||||
}
|
||||
});
|
||||
let r = ui.label(
|
||||
@@ -337,6 +338,14 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {
|
||||
);
|
||||
}
|
||||
}
|
||||
if d.options_skip_browsed() {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.label(
|
||||
egui::RichText::new(crate::i18n::tr("Keywords and presets apply to new files only, not to photos already in Local"))
|
||||
.color(t.text_dim)
|
||||
.small(),
|
||||
);
|
||||
}
|
||||
if d.trashed.iter().any(|t| *t) {
|
||||
field(ui, "In Recently Deleted", |ui| {
|
||||
let cur = match d.on_deleted.as_str() {
|
||||
@@ -580,9 +589,11 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial
|
||||
let badge = match (&c.duplicate, &c.error) {
|
||||
// checked with "Leave them", the file goes without `onDeleted`: the engine restores it
|
||||
(Some(_), _) if in_trash && on => Some(if d.on_deleted == "fresh" { "Will be replaced" } else { "Will be restored" }),
|
||||
(Some(_), _) if d.is_copy_twin(i) => None,
|
||||
(Some(_), _) if in_trash => Some("In Recently Deleted"),
|
||||
(Some(r), _) if r == "path" => Some("In library"),
|
||||
(Some(_), _) => Some("Duplicate"),
|
||||
(None, None) if d.copy && d.is_browsed(i) => Some("In library"),
|
||||
(None, Some(_)) => Some("Unreadable"),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -359,7 +359,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
// what the library doesn't know yet joins the Local view
|
||||
let queue: Vec<String> =
|
||||
out.candidates.iter().filter(|c| c.duplicate != Some("path".into()) && c.error.is_none()).map(|c| c.path.clone()).collect();
|
||||
out.candidates.iter().filter(|c| c.duplicate != Some("path".into()) && !c.local && c.error.is_none()).map(|c| c.path.clone()).collect();
|
||||
if !queue.is_empty() {
|
||||
let undo0 = app.session.undo.len();
|
||||
let total = queue.len();
|
||||
@@ -391,7 +391,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) {
|
||||
})
|
||||
.collect();
|
||||
d.set_trashed(trashed);
|
||||
d.copy = task.copy;
|
||||
d.set_transfer(task.copy, false);
|
||||
// only an album the review offers (it may have been deleted while the scan ran)
|
||||
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;
|
||||
|
||||
@@ -204,6 +204,10 @@ impl ImportRun {
|
||||
/// import runs: replacing `app.import` would stop its worker.
|
||||
pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result<Value, String> {
|
||||
busy_synchronizing(app)?;
|
||||
// a Lightroom catalog import owns the catalog until it ends (its photos may share a file's content), as for a drop
|
||||
if app.lightroom.is_some() {
|
||||
return Err(crate::i18n::tr("Finish Lightroom catalog import before adding photos").to_string());
|
||||
}
|
||||
if !d.in_library(app) {
|
||||
return Err("another library was opened since the photos were scanned: nothing was imported".into());
|
||||
}
|
||||
|
||||
@@ -3277,6 +3277,41 @@ fn cmd_q_quits() {
|
||||
assert!(h.quit_requested());
|
||||
}
|
||||
|
||||
/// File → Import from Folder… on a folder that was browsed in Local offers its photos, adding
|
||||
/// them in place (they aren't "In library" yet), and confirming brings them into the library.
|
||||
#[test]
|
||||
fn import_from_folder_offers_the_photos_browsed_in_local() {
|
||||
let mut h = demo([1300.0, 900.0]);
|
||||
let t = Duration::from_secs(10);
|
||||
let dir = std::env::temp_dir().join(format!("lc-ui-browsed-import-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let img = lightcraft_raster::Rgba8::from_fn(24, 16, |x, y| [(x * 9) as u8, (y * 12) as u8, 80, 255]);
|
||||
let o = lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() };
|
||||
for (i, name) in ["a.png", "b.png"].iter().enumerate() {
|
||||
let mut img = img.clone();
|
||||
img.data[0][0] = i as u8; // different bytes per file
|
||||
std::fs::write(dir.join(name), lightcraft_engine::export::encode_image(&img, &o).unwrap()).unwrap();
|
||||
}
|
||||
let library_before = h.app.session.catalog.photos().filter(|p| !p.local).count();
|
||||
let r = h.request("engine.execute", json!({"command": "library.browse", "params": {"path": dir.to_string_lossy()}}), t);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
h.settle(SETTLE);
|
||||
assert_eq!(h.app.session.catalog.photos().filter(|p| p.local).count(), 2, "both browsed");
|
||||
let r = h.request("engine.execute", json!({"command": "file.addFolder", "params": {"path": dir.to_string_lossy()}}), t);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
h.settle(SETTLE);
|
||||
let Some(crate::state::Dialog::Import { opts }) = &h.app.ui.dialog else { panic!("no import review: {:?}", h.app.ui.dialog) };
|
||||
assert_eq!(opts.candidates.len(), 2);
|
||||
assert!(opts.candidates.iter().all(|c| c.duplicate.is_none()), "browsed is not \"In library\": {:?}", opts.candidates);
|
||||
assert_eq!(opts.selected_paths().len(), 2, "both offered, checked");
|
||||
assert_eq!(h.request("ui.dialog.confirm", json!({}), t)["ok"], true);
|
||||
h.settle(SETTLE);
|
||||
assert_eq!(h.app.session.catalog.photos().filter(|p| !p.local).count(), library_before + 2, "both joined the library");
|
||||
assert_eq!(h.app.session.catalog.photos().filter(|p| p.local).count(), 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// File → Import from Folder… opens the import review for a folder (searched recursively).
|
||||
#[test]
|
||||
fn add_folder_opens_the_import_review() {
|
||||
|
||||
@@ -657,6 +657,23 @@ fn a_queued_drop_waits_for_a_running_lightroom_import_instead_of_being_refused()
|
||||
);
|
||||
}
|
||||
|
||||
/// The review's OK is refused while a Lightroom catalog import owns the catalog, as a drop is: nothing is imported
|
||||
/// beside it (CodeRabbit on #2971).
|
||||
#[test]
|
||||
fn an_import_review_is_not_confirmed_while_a_lightroom_import_runs() {
|
||||
let dir = Scratch::new("review-lightroom");
|
||||
let mut h = app_with_library(&dir);
|
||||
h.app.ui.settings.import_dropped_directly = false;
|
||||
drop_files(&mut h, &[dir.path("trip/a.png")], false);
|
||||
assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens");
|
||||
let task = crate::lightroom_import::stall_import(&mut h.app);
|
||||
let reply = h.request("ui.dialog.confirm", json!({}), T);
|
||||
assert_ne!(reply["ok"], true, "{reply}");
|
||||
assert!(h.app.import.is_none(), "no import started");
|
||||
assert_eq!(photos(&h), 0);
|
||||
drop(task);
|
||||
}
|
||||
|
||||
/// Cancelling Open Another…'s asynchronous picker keeps the launch list up; the queued photo is
|
||||
/// then held for the library chosen rather than dropped behind the cancelling picker.
|
||||
#[test]
|
||||
|
||||
@@ -76,7 +76,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
|
||||
|---|---|---|---|---|---|
|
||||
| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `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-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests/import.rs`, `crates/ui-egui/src/dialogs/import.rs`, `crates/ui-egui/src/headless/tests.rs` | Only library records (including Recently Deleted) count as existing content; a copy merely browsed in Local does not block importing another path. A browsed file at the same path is offered by the scan (not "In library") and promoted with its edits, unless a library match or an earlier promotion already has its content; background import batches deduplicate promoted files too. The review offers such a file only when adding in place (copy and move would add it where it is), and notes that keywords and presets apply to new files only. |
|
||||
| LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/dialogs/import.rs`) |
|
||||
| LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/dialogs/settings.rs` | Settings ▸ Import ▸ Auto Import: a watched folder whose new photos are added (in place or copied) once complete, into an optional album; scanned every 3 s |
|
||||
| LR-IMP-PRESET | Preset on import | P2 | ✅ | `cmd:library.import` (`preset`) | chosen in the import review; one History entry |
|
||||
@@ -1048,6 +1048,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
|
||||
| 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) |
|
||||
| 2026-10-28 | patch | LR-VIEW-PHOTOGRID: the grid's empty-view message (shown when a view other than the library is empty) used a fixed "Cmd+Shift+I" (or a translation's fixed copy of it) whatever the platform or the binding, on one line that ran out of a narrow window; it now shows Import Photos' shortcut as the menu bar writes it and as it is bound on its own line, and none when it is unbound, and the sentence wraps; status unchanged (✅) |
|
||||
| 2026-10-22 | patch | LRC-LIB-MISSING: `library.missing` from the control channel (an agent, `mcp --connect`) checks the photos' files on a worker thread under a "Missing Photos" row in the activity stack (counts the files, ✕ stops it) and is answered when the check ends, instead of freezing the window while the UI thread looked at every file (minutes on a large library on a network share); status unchanged (✅) |
|
||||
| 2026-10-25 | minor | LR-IMP-DUPES: the Import review offers a file that was only browsed in Local (adding in place; copy and move leave it out) instead of listing it as "In library", and a copy browsed under another path no longer blocks importing the library's own file, including after permanent deletion and a restart; a library match is checked before a browsed copy is promoted, and promoted content counts across background batches; files with a browsed photo's content are identical copies in the source, not library duplicates, and Copy or Move (which leave the browsed photo out) offer the first of them that isn't browsed itself. Ported from #1433 (Clearfall); status unchanged (✅) |
|
||||
| 2026-10-27 | patch | MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Select Only Active Photo and Paste Settings from Previous were not in the Edit menu's layout and ended up after Settings…, near the end of the menu; they now sit with the other Select and Paste rows. On macOS the Edit menu no longer shows two separators in a row where Settings… moved to the app menu; status unchanged (✅) |
|
||||
| 2026-10-27 | patch | MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say that Close Window and the red close button of the main window quit the app, after the check Quit makes; kept on purpose; a user page says so; status unchanged (✅) |
|
||||
| 2026-10-19 | minor | LRC-LIB-SMARTCOLL: smart albums and the library filter gain a File ▸ Same Content as Another Photo rule (48 fields now) that finds photos whose file content matches another photo's, under another name or in another folder; virtual copies and Recently Deleted photos don't count, photos with no recorded content hash match nothing, and an album with the rule follows deletes, restores and removals; status unchanged (✅) |
|
||||
|
||||
@@ -427,6 +427,21 @@
|
||||
|
||||
## 2026-10-25
|
||||
|
||||
### Import from Folder… offers the photos you browsed in Local
|
||||
- A folder you browsed in Local no longer shows its photos as "In library" and out of reach in the Import review:
|
||||
they are offered, checked, and importing them brings the browsed photos (with their edits) into the library where
|
||||
they are. Copy and Move still leave them out, since they can't be copied from where they already are, and the
|
||||
review says keywords and presets apply to new files only when they are set for such photos.
|
||||
- A copy you only browsed in Local (another path with the same content) no longer makes the import report "already in
|
||||
the library", even after the library photo was permanently deleted and the library reopened, and a library photo
|
||||
with the same content is matched before a browsed copy is promoted. Several browsed copies of one file import once.
|
||||
- Files with the same content as a browsed photo are listed as identical copies in the folder, not as already in the
|
||||
library, which doesn't have them. With Copy or Move, which leave the browsed photo out, the first of those files
|
||||
that isn't browsed itself is offered and checked instead, so that content can still be copied in from the folder.
|
||||
- A browsed file that another application replaced since (its size on disk is no longer the one that was browsed) is
|
||||
read again: it is compared with the library by what it is now, and importing it brings its record up to date (size,
|
||||
dimensions, content) as it joins the library.
|
||||
|
||||
### A one-field white balance edit no longer shifts the other one
|
||||
- Settings that name only a white balance temperature, or only a tint — `develop.merge`,
|
||||
`lightcraft-cli render --settings <partial JSON>`, an MCP `set_develop {settings: …}` call, or a hand-written
|
||||
|
||||
Reference in new issue
Block a user