Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
155 changes: 155 additions & 0 deletions crates/catalog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,71 @@ pub struct Catalog {
/// Increments on every applied op.
#[serde(skip)]
pub revision: u64,
/// Which photos the latest ops touched ([`Catalog::touched_since`]).
#[serde(skip)]
changes: Changes,
}

/// What of a photo an op changed: enough to tell which tallies of the library an edit leaves as they were (a
/// rating changes no folder's count; a slider changes none at all).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Aspects(u16);

impl Aspects {
pub const NONE: Aspects = Aspects(0);
pub const RATING: Aspects = Aspects(1);
pub const FLAG: Aspects = Aspects(1 << 1);
pub const LABEL: Aspects = Aspects(1 << 2);
/// Develop settings, versions and history.
pub const DEVELOP: Aspects = Aspects(1 << 3);
/// Title, caption, keywords, people, place and the rest of the metadata.
pub const META: Aspects = Aspects(1 << 4);
pub const CAPTURED: Aspects = Aspects(1 << 5);
/// Where its file is.
pub const FILE: Aspects = Aspects(1 << 6);
pub const ANALYSIS: Aspects = Aspects(1 << 7);
/// Whether it is in the library at all: added, removed, deleted, restored, taken in from Local.
pub const PRESENCE: Aspects = Aspects(1 << 8);
/// Everything: the photo may count differently for any tally.
pub const ALL: Aspects = Aspects(u16::MAX);

pub const fn with(self, other: Aspects) -> Aspects {
Aspects(self.0 | other.0)
}

/// Whether any of `other` is among these.
pub const fn any_of(self, other: Aspects) -> bool {
self.0 & other.0 != 0
}
}

/// The most photos remembered as touched; older changes are then answered with "anything may have changed".
const MAX_TOUCHED: usize = 8192;

/// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can
/// follow a small edit without being worked out again from every photo.
#[derive(Clone, Debug, Default)]
struct Changes {
/// The photos ops changed, each with the revision the op made and what of the photo it changed. Oldest first.
touched: std::collections::VecDeque<(u64, PhotoId, Aspects)>,
/// What the op being applied changes of its photo.
now: Aspects,
/// The latest revision made by an op that changed more than photos of its own (an album, a stack, a keyword of
/// the list…): what it changed for which photos is not known.
broad: u64,
/// Changes up to this revision are no longer all in `touched`.
floor: u64,
/// The revision the last op recorded here made. When the catalog's revision is another, it was set from
/// outside (a library just loaded takes a range of its own, so that nothing kept from another library is
/// taken for this one's): nothing is known of how the catalog got to where it is.
seen: u64,
}

impl PartialEq for Changes {
/// Two catalogs are the same catalog whatever each remembers of how it got there.
fn eq(&self, _: &Self) -> bool {
true
}
}

impl Catalog {
Expand Down Expand Up @@ -479,20 +544,110 @@ impl Catalog {
// ---- writes

fn photo_mut(&mut self, id: PhotoId) -> Result<&mut Photo> {
self.touch(id);
self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))
}

/// The op being applied changes photo `id` (or adds or removes it).
fn touch(&mut self, id: PhotoId) {
// (the revision the op will make: `apply` counts up once it is done)
self.changes.touched.push_back((self.revision.saturating_add(1), id, self.changes.now));
while self.changes.touched.len() > MAX_TOUCHED {
if let Some((revision, _, _)) = self.changes.touched.pop_front() {
self.changes.floor = revision;
}
}
}

/// What of its photos the ops since `revision` changed, taken together ([`Aspects::NONE`] when there were
/// none). `None` when that is not known ([`Catalog::touched_since`]). A tally of the library that reads only
/// other things of a photo is still right.
pub fn aspects_since(&self, revision: u64) -> Option<Aspects> {
if !self.remembers(revision) {
return None;
}
Some(self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a)))
}

/// 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
}

/// 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();
ids.sort_unstable();
ids.dedup();
Some(ids)
}
fn album_mut(&mut self, id: AlbumId) -> Result<&mut Album> {
self.albums.get_mut(&id).ok_or(CatalogError::NoAlbum(id))
}

/// Apply an op; returns its inverse. On error nothing changes.
pub fn apply(&mut self, op: Op) -> Result<Op> {
if self.changes.seen != self.revision {
// the revision was set from outside: what is remembered is of another past
self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() };
}
let inv = self.apply_inner(op)?;
self.revision += 1;
self.changes.seen = self.revision;
Ok(inv)
}

fn apply_inner(&mut self, op: Op) -> Result<Op> {
// An op that changes one photo says which (`photo_mut`, and adding or removing it below). Every other kind
// can change what any photo matches or where it sorts: an album's photos or rules, a stack, a keyword's
// name. Listed kind by kind, so a new one has to be put on one side.
match &op {
// (a photo that comes, goes, or changes what it is to the library counts for every tally; so do the
// rare kinds whose reach nobody has to think about)
Op::AddPhoto { photo } => {
self.changes.now = Aspects::ALL;
self.touch(photo.id);
}
Op::RemovePhoto { id } => {
self.changes.now = Aspects::ALL;
self.touch(*id);
}
Op::SetDeleted { .. } | Op::SetLocal { .. } | Op::SetContent { .. } | Op::SetEmbeddedLens { .. } | Op::SetAsShotWb { .. } => {
self.changes.now = Aspects::ALL
}
Op::SetRating { .. } => self.changes.now = Aspects::RATING,
Op::SetFlag { .. } => self.changes.now = Aspects::FLAG,
Op::SetLabel { .. } => self.changes.now = Aspects::LABEL,
Op::SetMeta { .. } => self.changes.now = Aspects::META,
Op::SetCaptured { .. } => self.changes.now = Aspects::CAPTURED,
Op::SetFile { .. } | Op::Relink { .. } => self.changes.now = Aspects::FILE,
Op::SetAnalysis { .. } => self.changes.now = Aspects::ANALYSIS,
Op::SetDevelop { .. } | Op::SetVersions { .. } | Op::SetHistory { .. } | Op::PushHistory { .. } | Op::SetHistoryCursor { .. } => {
self.changes.now = Aspects::DEVELOP
}
// (its ops say for themselves, one by one)
Op::Batch { .. } => {}
Op::AddAlbum { .. }
| Op::RemoveAlbum { .. }
| Op::RenameAlbum { .. }
| Op::MoveAlbum { .. }
| Op::SetAlbumOrder { .. }
| Op::SetAlbumPhotos { .. }
| Op::SetAlbumCover { .. }
| Op::SetAlbumRules { .. }
| Op::AddStack { .. }
| Op::RemoveStack { .. }
| Op::SetStack { .. }
| Op::SetLabelName { .. }
| Op::SetBrowsed { .. }
| Op::SetKeyword { .. }
| Op::SetFolderRecord { .. } => self.changes.broad = self.revision.saturating_add(1),
}
Ok(match op {
Op::AddPhoto { photo } => {
if self.photos.contains_key(&photo.id) {
Expand Down
81 changes: 63 additions & 18 deletions crates/catalog/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,27 @@ pub struct Sort {
pub seed: u64,
}

impl Sort {
/// Which of two photos comes first in this order (never `Equal` for two photos: the id decides last).
pub fn order(&self, a: &Photo, b: &Photo) -> std::cmp::Ordering {
let o = match self.key {
SortKey::CaptureDate => a.captured.cmp(&b.captured).then_with(|| a.imported.cmp(&b.imported)),
SortKey::ImportDate => a.imported.cmp(&b.imported),
SortKey::EditDate => a.edited.cmp(&b.edited),
SortKey::FileName => cmp_name(&a.file_name, &b.file_name),
SortKey::Rating => a.rating.cmp(&b.rating),
SortKey::FileSize => a.file_size.cmp(&b.file_size),
SortKey::Random => shuffle_rank(self.seed, a.id).cmp(&shuffle_rank(self.seed, b.id)),
}
// Ties (one import batch, a burst within a second, equal ratings) sort by file name, the
// order cameras number frames, so the order doesn't depend on how ids were allocated;
// the id only keeps it stable.
.then_with(|| if self.key == SortKey::FileName { Equal } else { cmp_name(&a.file_name, &b.file_name) })
.then(a.id.cmp(&b.id));
if self.ascending { o } else { o.reverse() }
}
}

impl Default for Sort {
fn default() -> Self {
Sort { key: SortKey::CaptureDate, ascending: false, group: crate::GroupBy::Auto, seed: 0 }
Expand Down Expand Up @@ -369,28 +390,52 @@ pub fn cmp_name(a: &str, b: &str) -> std::cmp::Ordering {
impl Catalog {
/// Photos matching `filter`, in `sort` order (ties broken by file name, then id).
pub fn query(&self, filter: &Filter, sort: &Sort) -> Vec<PhotoId> {
self.query_keeping(filter, sort, &std::collections::HashSet::new(), filter)
}

/// [`Catalog::query`], and with them the photos of `keep` that still match `within`, each at its place in `sort`
/// order: a view that holds the photos it showed when an edit makes them stop matching `filter` (a smart
/// album's rules, the filter bar), as long as they are still where the view looks (`within`: in the library,
/// the album, the folder; not deleted).
pub fn query_keeping(&self, filter: &Filter, sort: &Sort, keep: &std::collections::HashSet<PhotoId>, within: &Filter) -> Vec<PhotoId> {
let root = filter.library_root();
let mut v: Vec<&Photo> = self.photos().map(|p| p.as_ref()).filter(|p| filter.matches_in(p, self, root.as_deref())).collect();
v.sort_by(|a, b| {
let o = match sort.key {
SortKey::CaptureDate => a.captured.cmp(&b.captured).then_with(|| a.imported.cmp(&b.imported)),
SortKey::ImportDate => a.imported.cmp(&b.imported),
SortKey::EditDate => a.edited.cmp(&b.edited),
SortKey::FileName => cmp_name(&a.file_name, &b.file_name),
SortKey::Rating => a.rating.cmp(&b.rating),
SortKey::FileSize => a.file_size.cmp(&b.file_size),
SortKey::Random => shuffle_rank(sort.seed, a.id).cmp(&shuffle_rank(sort.seed, b.id)),
}
// Ties (one import batch, a burst within a second, equal ratings) sort by file name, the
// order cameras number frames, so the order doesn't depend on how ids were allocated;
// the id only keeps it stable.
.then_with(|| if sort.key == SortKey::FileName { Equal } else { cmp_name(&a.file_name, &b.file_name) })
.then(a.id.cmp(&b.id));
if sort.ascending { o } else { o.reverse() }
});
let within_root = within.library_root();
let mut v: Vec<&Photo> = self
.photos()
.map(|p| p.as_ref())
.filter(|p| filter.matches_in(p, self, root.as_deref()) || (keep.contains(&p.id) && within.matches_in(p, self, within_root.as_deref())))
.collect();
v.sort_by(|a, b| sort.order(a, b));
v.into_iter().map(|p| p.id).collect()
}

/// The list `was` (a [`Catalog::query`] of `filter` in `sort` order, or a [`Catalog::query_keeping`]), after ops
/// that touched only the photos `touched` (sorted by id, each once: [`Catalog::touched_since`]): those photos
/// taken out, and the ones that match `filter` now put back at their place in the order. With `within`, a
/// touched photo that was in the list and still matches `within` stays, as `query_keeping` would keep it. What
/// the query would give, without asking every photo again.
pub fn follow(&self, was: &[PhotoId], touched: &[PhotoId], filter: &Filter, sort: &Sort, within: Option<&Filter>) -> Vec<PhotoId> {
let listed: std::collections::HashSet<PhotoId> = was.iter().copied().filter(|id| touched.binary_search(id).is_ok()).collect();
let mut ids: Vec<PhotoId> = was.iter().copied().filter(|id| !listed.contains(id)).collect();
let (root, within_root) = (filter.library_root(), within.and_then(Filter::library_root));
for id in touched {
let Some(p) = self.photo(*id) else { continue };
let kept = within.is_some_and(|w| listed.contains(id) && w.matches_in(p, self, within_root.as_deref()));
if filter.matches_in(p, self, root.as_deref()) || kept {
// (the list is in order without the touched photos, and stays so as each is put back)
let at = ids.partition_point(|other| self.photo(*other).is_some_and(|o| sort.order(o, p).is_lt()));
ids.insert(at, *id);
}
}
ids
}

/// How many photos match `filter`: [`Catalog::query`]'s length without its sorting.
pub fn count(&self, filter: &Filter) -> usize {
let root = filter.library_root();
self.photos().filter(|p| filter.matches_in(p, self, root.as_deref())).count()
}

/// Year → month → day counts for the "By Date" section (newest first).
pub fn date_groups(&self) -> Vec<DateGroup> {
use std::collections::BTreeMap;
Expand Down
78 changes: 78 additions & 0 deletions crates/catalog/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -737,3 +737,81 @@ fn cmp_name_ignores_case_without_allocating() {
assert_eq!(cmp_name("DSC_0001", "DSC_0002"), Less);
assert_eq!(cmp_name("a", "ab"), Less);
}

/// 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]
fn the_catalog_remembers_which_photos_its_latest_ops_changed_and_what_of_them() {
let mut c = Catalog::default();
let photo = |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) = (photo(&mut c, "a.jpg"), photo(&mut c, "b.jpg"));
let start = c.revision;
assert_eq!(c.touched_since(start), Some(vec![]));
assert_eq!(c.aspects_since(start), Some(Aspects::NONE));
// a rating, then a flag on another photo, as one batch
c.apply(Op::SetRating { id: a, rating: 3 }).unwrap();
assert_eq!(c.touched_since(start), Some(vec![a]));
assert_eq!(c.aspects_since(start), Some(Aspects::RATING));
let after_rating = c.revision;
c.apply(Op::Batch { ops: vec![Op::SetFlag { id: b, flag: Flag::Pick }, Op::SetRating { id: a, rating: 4 }] }).unwrap();
assert_eq!(c.touched_since(start), Some(vec![a, b]), "each once");
assert_eq!(c.touched_since(after_rating), Some(vec![a, b]));
assert_eq!(c.aspects_since(after_rating), Some(Aspects::FLAG.with(Aspects::RATING)));
assert_eq!(c.touched_since(c.revision), Some(vec![]));
// a photo that goes counts for everything
let before = c.revision;
c.apply(Op::RemovePhoto { id: b }).unwrap();
assert_eq!(c.touched_since(before), Some(vec![b]));
assert!(c.aspects_since(before).is_some_and(|x| x.any_of(Aspects::PRESENCE) && x.any_of(Aspects::FILE)));
// an op that changes more than photos of its own: nothing is said of what came before it
let before = c.revision;
let album = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album::new(album, "Trip") }).unwrap();
assert_eq!(c.touched_since(before), None);
assert_eq!(c.aspects_since(start), None);
assert_eq!(c.touched_since(c.revision), Some(vec![]), "from after it, it is known again");
// a revision that is not this catalog's past
assert_eq!(c.touched_since(c.revision + 5), None);
// a revision set from outside (a library just loaded): nothing is known of how the catalog got there, and after
// the next op nothing of before it
let old = c.revision;
c.revision = 7 << 32;
assert_eq!(c.touched_since(old), None);
assert_eq!(c.aspects_since(c.revision), None);
let loaded = c.revision;
c.apply(Op::SetRating { id: a, rating: 1 }).unwrap();
assert_eq!(c.touched_since(loaded), Some(vec![a]));
assert_eq!(c.touched_since(old), None);
// an op that fails changes nothing, and what is remembered never says less than what happened
let before = c.revision;
assert!(c.apply(Op::SetRating { id: PhotoId(9_999), rating: 1 }).is_err());
assert_eq!(c.revision, before);
c.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap();
assert!(c.touched_since(before).is_some_and(|ids| ids.contains(&a)));
assert!(c.aspects_since(before).is_some_and(|x| x.any_of(Aspects::FLAG)));
// a batch that fails midway is undone as a whole; a batch in a batch is remembered photo by photo; a batch
// with an op that changes more than photos is not
let before = c.revision;
assert!(c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 5 }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }).is_err());
assert_eq!((c.revision, c.photo(a).map(|p| p.rating)), (before, Some(1)));
c.apply(Op::Batch { ops: vec![Op::Batch { ops: vec![Op::SetRating { id: a, rating: 2 }] }] }).unwrap();
// (the photo the failed batch asked for and never found may be named too: more is said, never less)
assert!(c.touched_since(before).is_some_and(|ids| ids.contains(&a)));
let before = c.revision;
c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 3 }, Op::RenameAlbum { id: album, name: "Journey".into() }] }).unwrap();
assert_eq!(c.touched_since(before), None);
// more ops than are remembered: the oldest are answered with "anything"
let long_ago = c.revision;
for i in 0..9000u32 {
c.apply(Op::SetRating { id: a, rating: (i % 5) as u8 }).unwrap();
}
assert_eq!(c.touched_since(long_ago), None);
assert_eq!(c.touched_since(c.revision - 10), Some(vec![a]));
}
Loading