Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions crates/catalog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -706,20 +706,44 @@ impl Catalog {

/// Whether every change since the catalog was at `revision` is remembered photo by photo.
fn remembers(&self, revision: u64) -> bool {
self.changes.seen == self.revision && revision <= self.revision && revision >= self.changes.floor && self.changes.broad <= revision
self.remembers_photos(revision) && self.changes.broad <= revision
}

/// Whether every change to a photo since the catalog was at `revision` is remembered.
fn remembers_photos(&self, revision: u64) -> bool {
self.changes.seen == self.revision && revision <= self.revision && revision >= self.changes.floor
}

/// The photos changed, added or removed since the catalog was at `revision`, each once. `None` when that is not
/// known: an op since then changed more than photos of its own, or it was too long ago. Then anything may
/// have changed.
pub fn touched_since(&self, revision: u64) -> Option<Vec<PhotoId>> {
if !self.remembers(revision) {
return None;
}
let mut ids: Vec<PhotoId> = self.changes.touched.iter().filter(|(r, _, _)| *r > revision).map(|(_, id, _)| *id).collect();
self.remembers(revision).then(|| self.touched_after(revision, Aspects::ALL))
}

/// The photos whose `reads` (what a tally reads of them) changed since the catalog was at
/// `revision`, added and removed photos included, each once; ops that change no photo of their
/// own (an album, a stack, the keyword list, a folder's label) and other things of a photo (a
/// rating, a slider) aside: for what is counted from the photos alone (the folders, days and
/// keywords they carry). `None` when that is not known: too long ago, or the catalog was set
/// from outside (a library loaded).
pub fn photos_changed_since(&self, revision: u64, reads: Aspects) -> Option<Vec<PhotoId>> {
// (every op that changes a photo says which, in `photo_mut` or as it adds or removes it:
// the ops `apply_inner` marks broad change no photo)
self.remembers_photos(revision).then(|| self.touched_after(revision, reads))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

fn touched_after(&self, revision: u64, reads: Aspects) -> Vec<PhotoId> {
let mut ids: Vec<PhotoId> = self
.changes
.touched
.iter()
.filter(|(r, _, a)| *r > revision && (reads == Aspects::ALL || a.any_of(reads)))
.map(|(_, id, _)| *id)
.collect();
ids.sort_unstable();
ids.dedup();
Some(ids)
ids
}
fn album_mut(&mut self, id: AlbumId) -> Result<&mut Album> {
self.albums.get_mut(&id).ok_or(CatalogError::NoAlbum(id))
Expand Down
12 changes: 12 additions & 0 deletions crates/catalog/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,18 @@ impl Photo {
pub fn in_library(&self) -> bool {
!self.deleted && !self.local
}
/// The file Missing Photos checks for this photo, if it is in scope: a library photo (not in
/// Recently Deleted, not a Local-only record seen while browsing a folder) whose original is a
/// file. Browse records are out of scope on purpose: browsing can leave tens of thousands of
/// them in the catalog, they never show in library views (Missing Photos included), and a
/// folder that is gone is simply not browsed again. The sidebar count, the Missing Photos view,
/// `library.missing` and Find Missing Photos all use this one rule.
pub fn library_file(&self) -> Option<&str> {
match &self.source {
Source::File { path } if self.in_library() => Some(path),
_ => None,
}
}
/// Edited by the user: settings differ from what import gave the photo.
pub fn is_edited(&self) -> bool {
let mut defaults = self.import_defaults();
Expand Down
46 changes: 46 additions & 0 deletions crates/catalog/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -994,6 +994,52 @@ fn search_text_finds_people_and_quoted_values() {
assert_eq!(q(" \t jane \u{3000} "), vec![jane, both], "any whitespace separates tokens");
}

/// The photos a tally that reads only some things of a photo has to look at again: those whose file, presence or flag
/// changed, not those that were only rated, and not what an album, a stack or a folder label changed (no photo's own).
#[test]
fn photos_changed_since_names_the_photos_whose_read_aspects_changed() {
let mut c = Catalog::default();
let add = |c: &mut Catalog, name: &str| {
let id = c.alloc_photo_id();
c.apply(Op::AddPhoto {
photo: Box::new(Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00")),
})
.unwrap();
id
};
let (a, b) = (add(&mut c, "a.jpg"), add(&mut c, "b.jpg"));
let files = Aspects::PRESENCE.with(Aspects::FILE);
let start = c.revision;
assert_eq!(c.photos_changed_since(start, files), Some(vec![]));
// a rating changes neither; a flag is read by the flag reader only
c.apply(Op::SetRating { id: a, rating: 3 }).unwrap();
c.apply(Op::SetFlag { id: b, flag: Flag::Pick }).unwrap();
assert_eq!(c.photos_changed_since(start, files), Some(vec![]));
assert_eq!(c.photos_changed_since(start, Aspects::FLAG), Some(vec![b]));
assert_eq!(c.touched_since(start), Some(vec![a, b]), "touched_since says every photo that was touched");
// a photo that comes in, moves or goes
let new = add(&mut c, "c.jpg");
c.apply(Op::Relink { id: a, file_name: "m.jpg".into(), source: Source::File { path: "/p/m.jpg".into() }, format: None }).unwrap();
c.apply(Op::RemovePhoto { id: b }).unwrap();
assert_eq!(c.photos_changed_since(start, files), Some(vec![a, b, new]), "each once, in id order");
// an op that changes no photo of its own is remembered, and is not in the answer (touched_since gives up on it)
let before = c.revision;
let album = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { photos: vec![a], ..Album::new(album, "Trip") } }).unwrap();
assert_eq!(c.photos_changed_since(before, files), Some(vec![]));
assert_eq!(c.touched_since(before), None);
assert_eq!(c.photos_changed_since(start, files), Some(vec![a, b, new]), "what came before it is still known");
// not known: a revision that is not this catalog's past, and one set from outside (a library just loaded)
assert_eq!(c.photos_changed_since(c.revision + 5, files), None);
let old = c.revision;
c.revision = 7 << 32;
assert_eq!(c.photos_changed_since(old, files), None);
let loaded = c.revision;
c.apply(Op::SetRating { id: a, rating: 1 }).unwrap();
assert_eq!(c.photos_changed_since(loaded, files), Some(vec![]));
assert_eq!(c.photos_changed_since(old, files), None);
}

/// What the catalog remembers of its latest ops: which photos each changed and what of them, as long as that can be
/// said photo by photo.
#[test]
Expand Down
28 changes: 27 additions & 1 deletion crates/engine/src/activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl Unit {
pub struct TaskInfo {
pub id: u64,
/// A stable id: `import`, `export`, `scan`, `previews`, `smartPreviews`, `lightroom`, `merge`, `download`,
/// `faces`, `denoise`, `findMissing`, `applePhotos`, `cache`, `focus`.
/// `faces`, `facesGpu`, `denoise`, `findMissing`, `applePhotos`, `cache`, `focus`, `geocode`, `move`, `sync`, `recheck`, `reload`.
pub kind: &'static str,
/// English; the frontend translates it.
pub label: String,
Expand Down Expand Up @@ -213,6 +213,12 @@ impl Activity {
tasks.iter().filter(|e| e.try_cancel()).count()
}

/// Whether a task of one of `kinds` is in flight. Its guard's lifetime is the answer: a task that
/// ends, fails or panics stops counting.
pub fn any_of(&self, kinds: &[&str]) -> bool {
lock(&self.inner.tasks).iter().any(|e| kinds.contains(&e.kind))
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// Tasks that quitting would cut short: cancellable ones not already stopping.
pub fn running_cancellable(&self) -> Vec<TaskInfo> {
lock(&self.inner.tasks).iter().filter(|e| e.is_cancellable() && !e.is_cancelled()).map(|e| e.info()).collect()
Expand Down Expand Up @@ -398,6 +404,26 @@ mod tests {
assert_eq!(a.list().len(), 1);
}

#[test]
fn any_of_asks_for_the_kinds_in_flight_and_a_dropped_guard_stops_counting() {
let a = Activity::default();
assert!(!a.any_of(&["scan", "import"]));
let scan = a.start("scan", "Reading photos", Cancel::No);
let other = a.start("export", "Exporting", Cancel::No);
assert!(a.any_of(&["scan", "import"]) && a.any_of(&["export"]) && !a.any_of(&["import", "sync"]));
drop(scan);
assert!(!a.any_of(&["scan", "import"]), "the guard's lifetime is the answer");
// a task whose thread panics lets go as well
let a2 = a.clone();
let _ = std::thread::spawn(move || {
let _held = a2.start("import", "Importing", Cancel::No);
panic!("synthetic panic in an import");
})
.join();
assert!(!a.any_of(&["import"]));
drop(other);
}

/// Codex review of #643: a worker that turns cancelling off and then reads the cancel flag
/// (an export handing its files to Apple Photos) must either see a cancel that was accepted or
/// make it fail, never let one be accepted and then ignored. Here the test holds the task's gate
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/cmd/lens_refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub fn missing(cat: &Catalog, db: &lightcraft_lensdb::LensDb, ids: Option<&[Phot
Some(_) => again && from_database(p),
}
})
.filter_map(|p| crate::cmd::missing::checked_path(p).map(|path| Missing { id: p.id, path: path.to_string() }))
.filter_map(|p| p.library_file().map(|path| Missing { id: p.id, path: path.to_string() }))
.filter(|m| seen.insert(m.id))
.collect()
}
Expand Down Expand Up @@ -75,7 +75,7 @@ pub fn apply(s: &mut Session, results: Vec<(Missing, std::result::Result<ProbeIn
for (item, info) in results {
let Ok(info) = info else { continue };
// the photo moved or left the library while its file was read: the result is stale, for its copies too
if s.catalog.photo(item.id).and_then(|p| crate::cmd::missing::checked_path(p)) != Some(item.path.as_str()) {
if s.catalog.photo(item.id).and_then(|p| p.library_file()) != Some(item.path.as_str()) {
continue;
}
let family = std::iter::once(item.id).chain(copies.get(&item.id).into_iter().flatten().copied());
Expand Down
37 changes: 12 additions & 25 deletions crates/engine/src/cmd/missing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,15 @@ use serde_json::{Value, json};
use super::{CommandSpec, always, bad, cmd, str_param};
use crate::{Result, Session};

/// The file Missing Photos checks for `p`, if it is in scope: a library photo (not in Recently
/// Deleted, not a Local-only record seen while browsing a folder) whose original is a file.
///
/// Local browse records are out of scope on purpose: browsing can leave tens of thousands of
/// them in the catalog, they never show in library views (Missing Photos included), and a
/// folder that is gone is simply not browsed again. The sidebar count, the Missing Photos view,
/// `library.missing` and Find Missing Photos all use this one rule.
pub fn checked_path(p: &Photo) -> Option<&str> {
match &p.source {
Source::File { path } if p.in_library() => Some(path),
_ => None,
}
}

/// Every in-scope photo's file ([`checked_path`]), without touching the disk.
/// Every in-scope photo's file ([`Photo::library_file`]: the rule the sidebar count, the Missing
/// Photos view, `library.missing` and Find Missing Photos all use), without touching the disk.
pub fn candidates(cat: &Catalog) -> Vec<String> {
cat.photos().filter_map(|p| checked_path(p).map(str::to_string)).collect()
cat.photos().filter_map(|p| p.library_file().map(str::to_string)).collect()
}

/// [`missing`] with the existence check supplied (tests count the file-system calls).
pub fn missing_with(cat: &Catalog, mut exists: impl FnMut(&str) -> bool) -> Vec<(PhotoId, String)> {
cat.photos().filter_map(|p| checked_path(p).filter(|f| !exists(f)).map(|f| (p.id, f.to_string()))).collect()
cat.photos().filter_map(|p| p.library_file().filter(|f| !exists(f)).map(|f| (p.id, f.to_string()))).collect()
}

/// Library photos whose original file can't be found: (id, path).
Expand All @@ -45,11 +32,11 @@ pub fn missing(s: &Session) -> Vec<(PhotoId, String)> {
missing_with(&s.catalog, |f| exists(f))
}

/// Every in-scope photo with its file ([`checked_path`]), without touching the disk: what a
/// Every in-scope photo with its file ([`Photo::library_file`]), without touching the disk: what a
/// sweep ([`sweep`]) goes through, so a caller can take the list on its own thread and check
/// the files on another.
pub fn checked(cat: &Catalog) -> Vec<(PhotoId, String)> {
cat.photos().filter_map(|p| checked_path(p).map(|f| (p.id, f.to_string()))).collect()
cat.photos().filter_map(|p| p.library_file().map(|f| (p.id, f.to_string()))).collect()
}

fn fingerprint_of<'a>(entries: impl Iterator<Item = (PhotoId, &'a str)>) -> u64 {
Expand All @@ -66,7 +53,7 @@ fn fingerprint_of<'a>(entries: impl Iterator<Item = (PhotoId, &'a str)>) -> u64
/// files on another thread compares it with [`fingerprint_of_checked`] to know whether the photos
/// changed meanwhile.
pub fn fingerprint(cat: &Catalog) -> u64 {
fingerprint_of(cat.photos().filter_map(|p| checked_path(p).map(|f| (p.id, f))))
fingerprint_of(cat.photos().filter_map(|p| p.library_file().map(|f| (p.id, f))))
}

/// [`fingerprint`] of the list [`checked`] gave.
Expand All @@ -78,7 +65,7 @@ pub fn fingerprint_of_checked(files: &[(PhotoId, String)]) -> u64 {
/// photos still in scope that still point at the file that was not found. A photo removed, moved to
/// Recently Deleted or relinked since is not reported as missing; one added since was not checked.
pub fn still_missing(cat: &Catalog, gone: Vec<(PhotoId, String)>) -> Vec<(PhotoId, String)> {
gone.into_iter().filter(|(id, file)| cat.photo(*id).and_then(|p| checked_path(p)) == Some(file.as_str())).collect()
gone.into_iter().filter(|(id, file)| cat.photo(*id).and_then(|p| p.library_file()) == Some(file.as_str())).collect()
}

/// How many files [`sweep`] checks between two reports of its progress.
Expand Down Expand Up @@ -118,7 +105,7 @@ pub fn missing_json(gone: Vec<(PhotoId, String)>) -> Value {
/// the photos its query already narrowed to). In the app `avail` answers from its cache (files
/// not checked yet count as present until the background check finds them gone).
pub fn is_missing(cat: &Catalog, avail: &crate::availability::Availability, id: PhotoId) -> bool {
!cfg!(target_arch = "wasm32") && cat.photo(id).and_then(|p| checked_path(p)).is_some_and(|f| avail.is_offline(f))
!cfg!(target_arch = "wasm32") && cat.photo(id).and_then(|p| p.library_file()).is_some_and(|f| avail.is_offline(f))
}

pub(crate) fn relink_op(id: PhotoId, path: &str) -> Op {
Expand Down Expand Up @@ -240,7 +227,7 @@ mod tests {
}
}

/// An in-scope photo ([`checked_path`]) as Find Missing Photos sees it: its file, the size and
/// An in-scope photo ([`Photo::library_file`]) as Find Missing Photos sees it: its file, the size and
/// content hash the library knows (0 / `None` = unknown).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FindCandidate {
Expand All @@ -256,7 +243,7 @@ pub struct FindCandidate {
pub fn find_candidates(cat: &Catalog) -> Vec<FindCandidate> {
cat.photos()
.filter_map(|p| {
checked_path(p).map(|f| FindCandidate { id: p.id, path: f.to_string(), size: p.file_size, hash: stored_hash(p).map(str::to_string) })
p.library_file().map(|f| FindCandidate { id: p.id, path: f.to_string(), size: p.file_size, hash: stored_hash(p).map(str::to_string) })
})
.collect()
}
Expand Down Expand Up @@ -455,7 +442,7 @@ pub fn plan_find_missing(candidates: &[FindCandidate], folder: &str) -> std::res
/// used (that photo stays missing). `missing` is the plan's count, corrected for what changed
/// among the photos the plan names.
fn commit_find(s: &mut Session, plan: FindPlan) -> Result<Value> {
let still_at = |cat: &Catalog, id: PhotoId, from: &str| cat.photo(id).and_then(|p| checked_path(p)) == Some(from);
let still_at = |cat: &Catalog, id: PhotoId, from: &str| cat.photo(id).and_then(|p| p.library_file()) == Some(from);
let mut in_use: HashSet<String> = candidates(&s.catalog).into_iter().collect();
let mut found = Vec::new();
let mut missing = plan.missing;
Expand Down
6 changes: 2 additions & 4 deletions crates/engine/src/cmd/recheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ impl Stale {

/// The photo is still as it was listed: same file, flag and stamp.
fn current(&self, p: &Photo) -> bool {
crate::cmd::missing::checked_path(p) == Some(self.path.as_str())
&& p.preview_only == self.preview_only
&& p.preview_checked == self.preview_checked
p.library_file() == Some(self.path.as_str()) && p.preview_only == self.preview_only && p.preview_checked == self.preview_checked
}
}

Expand All @@ -48,7 +46,7 @@ impl Stale {
pub fn stale(cat: &Catalog, all: bool) -> Vec<Stale> {
cat.photos()
.filter(|p| p.copy_of.is_none() && (p.preview_only_stale() || (all && (p.preview_only.is_some() || p.format.eq_ignore_ascii_case("orf")))))
.filter_map(|p| crate::cmd::missing::checked_path(p).map(|path| Stale::of(p, path)))
.filter_map(|p| p.library_file().map(|path| Stale::of(p, path)))
.collect()
}

Expand Down
6 changes: 3 additions & 3 deletions crates/engine/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
//! - **new** files: supported files the library doesn't have, by path or by content (the import
//! scan's duplicate rules, [`crate::import::scan_with`]);
//! - **missing** photos: library photos in the folder whose file is gone (the Missing Photos rule,
//! [`crate::cmd::missing::checked_path`]);
//! [`lightcraft_catalog::Photo::library_file`]);
//! - **metadata** updates: photos whose XMP sidecar file was saved after the photo came into the
//! library or was last edited here, and says something the library doesn't (rating, flag,
//! label, metadata, capture time or develop settings). Reading one makes the sidecar win, as
Expand Down Expand Up @@ -267,7 +267,7 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges {
);
let mut changes = FolderChanges { path: folder, seen, ..Default::default() };
for ((p, _), check) in photos.iter().zip(checks) {
let Some(file) = crate::cmd::missing::checked_path(p) else { continue };
let Some(file) = p.library_file() else { continue };
let found = FolderPhoto { id: p.id.0, path: file.to_string() };
match check {
Check::Missing => changes.missing.push(found),
Expand Down Expand Up @@ -512,7 +512,7 @@ impl Listing {
}

fn check_photo(p: &Photo, naming: SidecarLookup, labels: &Catalog, listing: &Listing) -> Check {
let Some(file) = crate::cmd::missing::checked_path(p) else { return Check::Nothing };
let Some(file) = p.library_file() else { return Check::Nothing };
let file = Path::new(file);
if !listing.or_ask(listing.exists(file), || file.exists()) {
Check::Missing
Expand Down
Loading
Loading