diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a6972..90c671d738c 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -316,6 +316,9 @@ impl Aspects { 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); + /// The keyword list (keywords on their own and their attributes): of no photo, and read by no rule, filter or + /// sort, only by what lists keywords (the keyword tree, export names). + pub const KEYWORD_LIST: Aspects = Aspects(1 << 9); /// Everything: the photo may count differently for any tally. pub const ALL: Aspects = Aspects(u16::MAX); @@ -340,9 +343,11 @@ struct Changes { 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. + /// The latest revision made by an op that changed more than photos of its own (an album, a stack…): what it + /// changed for which photos is not known. broad: u64, + /// The latest revision made by an op that changed the keyword list ([`Aspects::KEYWORD_LIST`]). + keyword_list: 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 @@ -432,16 +437,23 @@ impl Catalog { self.albums.values().find(|a| a.quick).map(|a| a.id) } - /// Albums (regular and smart) that contain the photo. + /// Albums (regular and smart) that contain the photo; not the folders those albums are in. pub fn albums_of(&self, id: PhotoId) -> Vec { let Some(p) = self.photos.get(&id) else { return Vec::new() }; - self.albums.values().filter(|a| self.album_contains(a.id, p)).map(|a| a.id).collect() + self.albums.values().filter(|a| !a.folder && self.album_contains(a.id, p)).map(|a| a.id).collect() } /// Whether album `id` contains `p` (a smart album evaluates its rules; deleted photos are in - /// no smart album). + /// no smart album). A folder contains what the albums inside it do ([`Self::album_members`]). pub fn album_contains(&self, id: AlbumId, p: &Photo) -> bool { match self.albums.get(&id) { + // a folder first: one that also has rules (a damaged library) is still a folder. + // Within a pass over the library its photos were gathered once; for one photo, no + // list is built + Some(a) if a.folder => match gathered(self, id, || self.folder_photos(id)) { + Some(folder) => folder.holds(self, p), + None => self.albums.values().any(|m| !m.folder && self.album_is_within(m, id) && self.album_contains(m.id, p)), + }, Some(Album { smart: Some(rules), .. }) => self.smart_album_has(id, rules, &rules.prepare_one(), p), Some(a) => self.album_lists(a.id, p.id), None => false, @@ -454,21 +466,97 @@ impl Catalog { !p.deleted && rules::smart_album_holds(id, p.id, || rules.matches_in(p, self, prepared)) } - /// Whether smart album `from` tests `to`, directly or through the smart albums it tests (the - /// rules of `from` would then change when those of `to` do). Loops in saved rules end the - /// search, they don't repeat it. + /// The albums and smart albums whose photos `id` shows: those inside a folder, at any depth + /// (the folders themselves left out), or an album alone. Empty when there is no such album. + pub fn album_members(&self, id: AlbumId) -> Vec { + match self.albums.get(&id) { + Some(a) if a.folder => self.albums.values().filter(|m| !m.folder && self.album_is_within(m, id)).map(|m| m.id).collect(), + Some(a) => vec![a.id], + None => Vec::new(), + } + } + + /// Whether `album` sits inside `folder`, directly or through the folders between them, as the + /// sidebar lists it: a parent that is no folder, or is gone, leads nowhere. Parents that lead + /// round in a ring (a damaged library) end the search after one pass round it. + fn album_is_within(&self, album: &Album, folder: AlbumId) -> bool { + let mut parent = album.parent; + for _ in 0..=self.albums.len() { + match parent { + Some(p) if p == folder => return true, + Some(p) => match self.albums.get(&p) { + Some(between) if between.folder => parent = between.parent, + _ => return false, + }, + None => return false, + } + } + false + } + + /// What folder `id` shows, gathered for a question about many photos. + fn folder_photos(&self, id: AlbumId) -> FolderPhotos { + #[cfg(test)] + FOLDER_GATHERS.with(|n| n.set(n.get() + 1)); + let mut shown = FolderPhotos::default(); + for member in self.album_members(id).iter().filter_map(|m| self.albums.get(m)) { + match member.smart { + Some(_) => shown.smart.push(member.id), + None => shown.listed.extend(member.photos.iter().copied()), + } + } + shown + } + + /// Whether smart album `from` tests `to`, directly or through the smart albums it tests and the + /// folders they are in (the rules of `from` would then change when those of `to` do). Loops in + /// saved rules end the search, they don't repeat it. pub fn album_reaches(&self, from: AlbumId, to: AlbumId) -> bool { + self.album_search(self.album_leads_to(from), |a| a == to) + } + + /// Whether a smart album with `rules` would include itself if it were in folder `parent`: its + /// rules lead (as in [`Self::album_reaches`]) to that folder or to one around it. + pub fn smart_album_would_loop_in(&self, rules: &Filter, parent: AlbumId) -> bool { + let Some(inside) = self.albums.get(&parent) else { return false }; + self.album_search(rules.albums_tested(), |a| { + self.albums.get(&a).is_some_and(|f| f.folder) && (a == parent || self.album_is_within(inside, a)) + }) + } + + /// The smart album that would include itself if album or folder `id` were moved into folder + /// `parent`: `id` itself or, for a folder, one inside it ([`Self::smart_album_would_loop_in`]). + /// `None` when the move makes no loop. + pub fn album_move_would_loop(&self, id: AlbumId, parent: AlbumId) -> Option { + let moved = self.album_members(id); + moved + .into_iter() + .find(|m| self.albums.get(m).and_then(|a| a.smart.as_deref()).is_some_and(|rules| self.smart_album_would_loop_in(rules, parent))) + } + + /// The albums whose photos decide those of `a`: the albums a smart album tests, or the albums + /// inside a folder. + fn album_leads_to(&self, a: AlbumId) -> Vec { + match self.albums.get(&a) { + Some(al) if al.folder => self.album_members(a), + Some(al) => al.smart.as_deref().map(Filter::albums_tested).unwrap_or_default(), + None => Vec::new(), + } + } + + /// Whether `found` holds for one of `start` or for an album they lead to + /// ([`Self::album_leads_to`]); each album is looked at once. + fn album_search(&self, start: Vec, found: impl Fn(AlbumId) -> bool) -> bool { let mut seen: std::collections::HashSet = std::collections::HashSet::new(); - let mut next = vec![from]; + let mut next = start; while let Some(a) = next.pop() { if !seen.insert(a) { continue; } - let tested = self.albums.get(&a).and_then(|al| al.smart.as_deref()).map(Filter::albums_tested).unwrap_or_default(); - if tested.contains(&to) { + if found(a) { return true; } - next.extend(tested); + next.extend(self.album_leads_to(a)); } false } @@ -498,12 +586,14 @@ impl Catalog { }) } - /// The photos of an album: the stored list, or a smart album's current matches (id order). + /// The photos of an album: the stored list, or a smart album's current matches (id order). A + /// folder's are those of the albums inside it, each once, without the deleted ones (id order). pub fn album_photos(&self, id: AlbumId) -> Vec { match self.albums.get(&id) { + Some(a) if a.folder => gathering(|| self.photos.values().filter(|p| !p.deleted && self.album_contains(id, p)).map(|p| p.id).collect()), Some(Album { smart: Some(rules), .. }) => { let prepared = rules.prepare(); - self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).map(|p| p.id).collect() + gathering(|| self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).map(|p| p.id).collect()) } Some(a) => a.photos.clone(), None => Vec::new(), @@ -513,10 +603,11 @@ impl Catalog { /// Number of photos shown for an album in the sources list (excludes deleted photos). pub fn album_count(&self, id: AlbumId) -> usize { match self.albums.get(&id) { + Some(a) if a.folder => gathering(|| self.photos.values().filter(|p| !p.deleted && self.album_contains(id, p)).count()), // counted in place: no id list is built just for its length Some(Album { smart: Some(rules), .. }) => { let prepared = rules.prepare(); - self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).count() + gathering(|| self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).count()) } Some(a) => a.photos.iter().filter(|p| self.photos.get(p).is_some_and(|p| !p.deleted)).count(), None => 0, @@ -589,7 +680,8 @@ impl Catalog { if !self.remembers(revision) { return None; } - Some(self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a))) + let photos = self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a)); + Some(if self.changes.keyword_list > revision { photos.with(Aspects::KEYWORD_LIST) } else { photos }) } /// Whether every change since the catalog was at `revision` is remembered photo by photo. @@ -622,6 +714,7 @@ impl Catalog { self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() }; } let broad = self.changes.broad; + let keyword_list = self.changes.keyword_list; self.changes.torn = false; let inv = match self.apply_inner(op) { Ok(inv) => inv, @@ -643,6 +736,7 @@ impl Catalog { self.changes.touched.pop_back(); } self.changes.broad = broad; + self.changes.keyword_list = keyword_list; } return Err(e); } @@ -653,9 +747,9 @@ impl Catalog { } fn apply_inner(&mut self, op: Op) -> Result { - // 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. + // An op that changes one photo says which (`photo_mut`, and adding or removing it below). Most other kinds + // can change what any photo matches or where it sorts: an album's photos or rules, a stack. The keyword + // list changes only lists of keywords. 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) @@ -695,8 +789,9 @@ impl Catalog { | Op::SetStack { .. } | Op::SetLabelName { .. } | Op::SetBrowsed { .. } - | Op::SetKeyword { .. } | Op::SetFolderRecord { .. } => self.changes.broad = self.revision.saturating_add(1), + // (no photo matches, counts or sorts by it: only lists of keywords change) + Op::SetKeyword { .. } => self.changes.keyword_list = self.revision.saturating_add(1), } Ok(match op { Op::AddPhoto { photo } => { @@ -1186,9 +1281,68 @@ fn album_order_key(a: &Album) -> (bool, bool, u32, String, AlbumId) { (!a.folder, a.order.is_none(), a.order.unwrap_or(0), a.name.to_lowercase(), a.id) } +/// The photos a folder of albums shows: what the albums inside it list, and the smart albums +/// inside it, whose rules are asked per photo. +#[derive(Default)] +struct FolderPhotos { + listed: std::collections::HashSet, + smart: Vec, +} + +impl FolderPhotos { + fn holds(&self, cat: &Catalog, p: &Photo) -> bool { + self.listed.contains(&p.id) || self.smart.iter().any(|s| cat.album_contains(*s, p)) + } +} + +#[cfg(test)] +thread_local! { + /// How many times a folder's photos were gathered on this thread (tests count passes, not time). + static FOLDER_GATHERS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +thread_local! { + /// The folders asked about during a pass over the library ([`gathering`]), by catalog (where + /// it is, which holds for the pass: it is borrowed throughout) and id: `None` outside one. + static GATHERED: std::cell::RefCell>>> = + const { std::cell::RefCell::new(None) }; +} + +/// Run `pass`, a question put to many photos of one catalog: each folder of albums it asks about +/// (the one shown, or one a smart album is limited to) has its photos gathered once, not looked +/// up album by album for every photo. Forgotten when the outermost pass ends, however it ends. +pub(crate) fn gathering(pass: impl FnOnce() -> T) -> T { + struct Forget(bool); + impl Drop for Forget { + fn drop(&mut self) { + if self.0 { + GATHERED.with_borrow_mut(|g| *g = None); + } + } + } + let outermost = GATHERED.with_borrow_mut(|g| g.is_none().then(|| *g = Some(Default::default())).is_some()); + let _forget = Forget(outermost); + pass() +} + +/// Folder `id` of `cat`'s photos during a pass ([`gathering`]), made by `gather` the first time; +/// `None` outside one. +fn gathered(cat: &Catalog, id: AlbumId, gather: impl FnOnce() -> FolderPhotos) -> Option> { + let key = (std::ptr::from_ref(cat) as usize, id); + if let Some(known) = GATHERED.with_borrow(|g| g.as_ref().map(|folders| folders.get(&key).cloned()))? { + return Some(known); + } + // gathered with nothing borrowed, then kept + let folder = std::rc::Rc::new(gather()); + GATHERED.with_borrow_mut(|g| g.as_mut().map(|folders| folders.insert(key, folder.clone()))); + Some(folder) +} + #[cfg(test)] mod tests; #[cfg(test)] +mod tests_album_folder_photos; +#[cfg(test)] mod tests_album_order; #[cfg(test)] mod tests_background; diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index ff94268a8ba..02e625e9137 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -485,11 +485,13 @@ impl Catalog { let prepared = filter.prepare(); // `within` only decides for the few kept photos: worked out per photo, not hashed let within_prepared = within.prepare_one(); - let mut v: Vec<&Photo> = self - .photos() - .map(|p| p.as_ref()) - .filter(|p| filter.matches_in(p, self, &prepared) || (keep.contains(&p.id) && within.matches_in(p, self, &within_prepared))) - .collect(); + // one pass: a folder of albums it asks about is gathered once + let mut v: Vec<&Photo> = crate::gathering(|| { + self.photos() + .map(|p| p.as_ref()) + .filter(|p| filter.matches_in(p, self, &prepared) || (keep.contains(&p.id) && within.matches_in(p, self, &within_prepared))) + .collect() + }); v.sort_by(|a, b| sort.order(a, b)); v.into_iter().map(|p| p.id).collect() } @@ -503,22 +505,26 @@ impl Catalog { let listed: std::collections::HashSet = was.iter().copied().filter(|id| touched.binary_search(id).is_ok()).collect(); let mut ids: Vec = was.iter().copied().filter(|id| !listed.contains(id)).collect(); let (prepared, within_prepared) = (filter.prepare_one(), within.map(Filter::prepare_one)); - for id in touched { - let Some(p) = self.photo(*id) else { continue }; - let kept = within.zip(within_prepared.as_ref()).is_some_and(|(w, wp)| listed.contains(id) && w.matches_in(p, self, wp)); - if filter.matches_in(p, self, &prepared) || 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); + // one pass: a folder of albums it asks about is gathered once + crate::gathering(|| { + for id in touched { + let Some(p) = self.photo(*id) else { continue }; + let kept = within.zip(within_prepared.as_ref()).is_some_and(|(w, wp)| listed.contains(id) && w.matches_in(p, self, wp)); + if filter.matches_in(p, self, &prepared) || 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 prepared = filter.prepare(); - self.photos().filter(|p| filter.matches_in(p, self, &prepared)).count() + // one pass: a folder of albums it asks about is gathered once + crate::gathering(|| self.photos().filter(|p| filter.matches_in(p, self, &prepared)).count()) } /// Year → month → day counts for the "By Date" section (newest first). @@ -575,7 +581,8 @@ impl Catalog { let filter = Filter { person: None, ..filter.clone() }; let mut m: std::collections::HashMap = Default::default(); let prepared = filter.prepare(); - for p in self.photos().filter(|p| filter.matches_in(p, self, &prepared)) { + let matching: Vec<_> = crate::gathering(|| self.photos().filter(|p| filter.matches_in(p, self, &prepared)).collect()); + for p in matching { let mut seen: Vec = Vec::new(); for r in p.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) { let Some(name) = r.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue }; diff --git a/crates/catalog/src/tally.rs b/crates/catalog/src/tally.rs index e8fdc61979b..fc936c89829 100644 --- a/crates/catalog/src/tally.rs +++ b/crates/catalog/src/tally.rs @@ -3,14 +3,14 @@ //! A smart album's count asks every photo whether its rules hold. Asked again after every edit, that is a pass over //! the library for each smart album each time a keyword is given. [`AlbumTally`] remembers which photos each smart //! album holds, and after a small edit asks only the photos the edit touched ([`Catalog::touched_since`]). An op -//! that changes more than photos of its own (an album's rules or photos, a stack, the keyword list) has it counted -//! whole again, as before. +//! that changes more than photos of its own (an album's rules or photos, a stack) has to be counted whole again +//! ([`AlbumTally::of`]): the caller decides where (the app does it off the UI thread). use std::collections::{HashMap, HashSet}; use crate::query::Filter; use crate::rules::{AlbumPass, MAX_ALBUM_DEPTH}; -use crate::{Album, AlbumId, Aspects, Catalog, PhotoId}; +use crate::{AlbumId, Aspects, Catalog, PhotoId}; /// The most photos an edit may touch for the counts to follow it photo by photo. const MAX_FOLLOWED: usize = 256; @@ -20,7 +20,7 @@ const MAX_FOLLOWED: usize = 256; const WORDS_A_MEMBER: usize = 4; const WORDS_TO_START: usize = 1024; -/// The photos a smart album holds. +/// The photos a smart album or a folder of albums holds. #[derive(Clone, Debug)] pub(crate) enum Members { /// One bit a photo id, and how many are set. @@ -102,14 +102,49 @@ impl Members { } } } + + /// Every photo held. + fn ids(&self) -> Box + '_> { + match self { + Members::Bits { words, .. } => Box::new( + words + .iter() + .enumerate() + .flat_map(|(at, word)| (0..64u64).filter(move |b| word & (1u64 << b) != 0).map(move |b| PhotoId(at as u64 * 64 + b))), + ), + Members::Set(set) => Box::new(set.iter().copied()), + } + } + + /// Put every photo `other` holds in as well. + fn absorb(&mut self, other: &Members) { + if let (Members::Bits { words, len }, Members::Bits { words: more, .. }) = (&mut *self, other) { + if words.len() < more.len() { + words.resize(more.len(), 0); + } + for (word, more) in words.iter_mut().zip(more) { + *word |= more; + } + *len = words.iter().map(|word| word.count_ones() as usize).sum(); + return; + } + if let Members::Set(set) = self { + set.extend(other.ids()); + return; + } + for id in other.ids() { + self.set(id, true); + } + } } -/// [`Catalog::album_count`] of every album, as of one revision of the catalog. +/// [`Catalog::album_count`] of every album, as of one revision of the catalog. A folder of albums is counted from the +/// photos of the albums inside it, not by a pass over the library of its own. #[derive(Clone, Debug)] pub struct AlbumTally { revision: u64, counts: HashMap, - /// The smart albums' photos. + /// The photos each smart album and each folder of albums holds. members: HashMap, } @@ -122,9 +157,14 @@ impl AlbumTally { /// An album whose rules lead into a loop, or through a chain too deep to be sure of, is counted by its rules /// as before: the pass ends before the first of them (they sort last), so nothing they evaluate reads it. pub fn of(cat: &Catalog) -> AlbumTally { + // one pass: a folder of albums a smart album is limited to is gathered once + crate::gathering(|| AlbumTally::counted(cat)) + } + + fn counted(cat: &Catalog) -> AlbumTally { let heights = chain_heights(cat); let height_of = |id: AlbumId| heights.get(&id).copied().flatten().filter(|h| *h <= MAX_ALBUM_DEPTH); - let mut smart: Vec = cat.albums().filter(|a| a.is_smart()).map(|a| a.id).collect(); + let mut smart: Vec = cat.albums().filter(|a| a.is_smart() && !a.folder).map(|a| a.id).collect(); smart.sort_by_key(|id| height_of(*id).unwrap_or(usize::MAX)); let held_by = |id: AlbumId| { let mut held = Members::none(); @@ -152,9 +192,24 @@ impl AlbumTally { counts.insert(*id, held.len()); members.insert(*id, held); } - for album in cat.albums().filter(|a| !a.is_smart()) { + for album in cat.albums().filter(|a| !a.is_smart() && !a.folder) { counts.insert(album.id, cat.album_count(album.id)); } + // A folder holds what the albums inside it do: put together from theirs, with no pass over the library (and kept, + // so that an edit to a few photos is followed in folders too). The smart albums' photos go in first: bits OR + // together, where the photos of an album of chosen photos go in one by one. + for folder in cat.albums().filter(|a| a.folder) { + let inside: Vec<_> = cat.album_members(folder.id).into_iter().filter_map(|m| cat.album(m)).collect(); + let mut held = Members::none(); + for smart in inside.iter().filter_map(|m| members.get(&m.id)) { + held.absorb(smart); + } + for chosen in inside.iter().filter(|m| !members.contains_key(&m.id)) { + chosen.photos.iter().filter(|id| cat.photo(**id).is_some_and(|p| !p.deleted)).for_each(|id| held.set(*id, true)); + } + counts.insert(folder.id, held.len()); + members.insert(folder.id, held); + } AlbumTally { revision: cat.revision, counts, members } } @@ -168,44 +223,56 @@ impl AlbumTally { self.revision } - /// Bring the counts up to `cat` as it is now. `true` when that was done from the photos the ops since touched - /// (or nothing had changed), `false` when every photo was asked again. + /// Bring the counts up to `cat` as it is now from the photos the ops since touched. `true` when that was done (or + /// nothing had changed); `false` when it can't be, and every photo has to be asked again ([`AlbumTally::of`]): + /// the counts are then left as they were. /// /// `cat` has to be the catalog the counts were made of, further along. Another catalog is told apart only by - /// its revisions: a library that is loaded takes a range of its own (and then everything is counted again), but - /// two catalogs both counting from 0 look like one. + /// its revisions: a library that is loaded takes a range of its own (and then nothing is followed), but two + /// catalogs both counting from 0 look like one. pub fn update(&mut self, cat: &Catalog) -> bool { if self.revision == cat.revision { return true; } - let followed = match (cat.touched_since(self.revision), cat.aspects_since(self.revision)) { + match (cat.touched_since(self.revision), cat.aspects_since(self.revision)) { (Some(touched), Some(changed)) if touched.len() <= MAX_FOLLOWED => { self.follow(cat, &touched, changed); true } _ => false, - }; - if !followed { - *self = AlbumTally::of(cat); } - followed } - /// The counts after ops that touched only `touched`: each smart album asks those photos again; an album of - /// chosen photos counts again only when a photo came, went or was deleted (who is in it did not change: that - /// is an op on the album, and not followed). + /// The counts after ops that touched only `touched`: each smart album asks those photos again; an album of chosen + /// photos counts again only when a photo came, went or was deleted (who is in it did not change: that is an op on + /// the album, and not followed); a folder holds what the albums inside it now hold of them. fn follow(&mut self, cat: &Catalog, touched: &[PhotoId], changed: Aspects) { - for (album, held) in &mut self.members { + let folders: HashSet = cat.albums().filter(|a| a.folder).map(|a| a.id).collect(); + for (album, held) in self.members.iter_mut().filter(|(album, _)| !folders.contains(album)) { for id in touched { held.set(*id, cat.photo(*id).is_some_and(|p| cat.album_contains(*album, p))); } self.counts.insert(*album, held.len()); } if changed.any_of(Aspects::PRESENCE) { - for album in cat.albums().filter(|a| !a.is_smart()) { + for album in cat.albums().filter(|a| !a.is_smart() && !a.folder) { self.counts.insert(album.id, cat.album_count(album.id)); } } + // After the albums inside them, whose photos they are put together from. No deleted photo is in a folder's count. + for folder in &folders { + let inside = cat.album_members(*folder); + let holds = |p: &crate::Photo| { + !p.deleted && inside.iter().any(|m| self.members.get(m).map_or_else(|| cat.album_contains(*m, p), |held| held.holds(p.id))) + }; + let now: Vec<(PhotoId, bool)> = touched.iter().map(|id| (*id, cat.photo(*id).is_some_and(|p| holds(p)))).collect(); + if let Some(held) = self.members.get_mut(folder) { + for (id, is) in now { + held.set(id, is); + } + self.counts.insert(*folder, held.len()); + } + } self.revision = cat.revision; } } @@ -222,12 +289,13 @@ fn chain_heights(cat: &Catalog) -> HashMap> { } let tests = |id: AlbumId| -> Vec { let tested = cat.album(id).and_then(|a| a.smart.as_deref()).map(Filter::albums_tested).unwrap_or_default(); - tested.into_iter().filter(|t| cat.album(*t).is_some_and(Album::is_smart)).collect() + // (a folder of albums leads to the smart albums inside it, which its photos are gathered from) + tested.into_iter().flat_map(|t| cat.album_members(t)).filter(|t| cat.album(*t).is_some_and(|a| a.is_smart() && !a.folder)).collect() }; let frame = |id: AlbumId| Frame { id, tests: tests(id), next: 0, tallest: 0, loops: false }; let mut done: HashMap> = HashMap::new(); let mut open: HashSet = HashSet::new(); - for root in cat.albums().filter(|a| a.is_smart()).map(|a| a.id) { + for root in cat.albums().filter(|a| a.is_smart() && !a.folder).map(|a| a.id) { if done.contains_key(&root) { continue; } @@ -308,4 +376,38 @@ mod tests { assert!(matches!(&dense, Members::Bits { words, .. } if words.len() <= 200_000 / 64 + 1)); assert_eq!(dense.len(), 200_000); } + + #[test] + fn a_union_of_members_counts_each_photo_once_whether_they_are_bits_or_sets() { + let mut smart = Members::none(); + for id in 1..=500u64 { + smart.set(PhotoId(id), true); + } + let mut more = Members::none(); + for id in 400..600u64 { + more.set(PhotoId(id), true); + } + assert!(matches!((&smart, &more), (Members::Bits { .. }, Members::Bits { .. }))); + // bits into bits: stays bits, counted once each + let mut union = Members::none(); + union.absorb(&smart); + union.absorb(&more); + assert!(matches!(union, Members::Bits { .. })); + assert_eq!(union.len(), 599); + assert_eq!(ids(&union, &[0, 1, 450, 599, 600]), vec![1, 450, 599]); + // a set into bits, and bits into a set, and a set into a set + let mut sparse = Members::none(); + for id in [3, 9_000_000_000] { + sparse.set(PhotoId(id), true); + } + assert!(matches!(sparse, Members::Set(_))); + union.absorb(&sparse); + assert_eq!((union.len(), union.holds(PhotoId(3)), union.holds(PhotoId(9_000_000_000))), (600, true, true)); + let mut both = Members::none(); + both.absorb(&sparse); + both.absorb(&smart); + assert_eq!((both.len(), both.holds(PhotoId(9_000_000_000)), both.holds(PhotoId(450))), (501, true, true)); + both.absorb(&sparse); + assert_eq!(both.len(), 501, "a set taken into a set again adds nothing"); + } } diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index bf67b249580..8f4dbbdb8f4 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -960,6 +960,12 @@ fn history_handles_loaded_revisions_failed_batches_and_retention() { 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); + // the keyword list changes no photo: what was touched stays known, and the list is said to have changed + let before = c.revision; + c.apply(Op::SetKeyword { path: "travel|Rome".into(), info: Some(Default::default()) }).unwrap(); + assert_eq!(c.touched_since(before), Some(vec![])); + assert_eq!(c.aspects_since(before), Some(Aspects::KEYWORD_LIST)); + assert_eq!(c.aspects_since(c.revision), Some(Aspects::NONE), "and from after it, not"); // more ops than are remembered: the oldest are answered with "anything" let long_ago = c.revision; for i in 0..9000u32 { @@ -1000,6 +1006,13 @@ fn an_op_that_fails_leaves_no_touched_photos_behind() { assert_eq!(c.revision, start); assert_eq!(c.touched_since(start), Some(vec![])); assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); + // a keyword op that fails, alone or inside a batch that is rolled back, does not say the keyword list changed + assert!(c.apply(Op::SetKeyword { path: " | ".into(), info: Some(Default::default()) }).is_err()); + assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); + let ok = Op::SetKeyword { path: "travel|Rome".into(), info: Some(Default::default()) }; + assert!(c.apply(Op::Batch { ops: vec![ok, Op::SetRating { id: missing, rating: 1 }] }).is_err()); + assert_eq!(c.revision, start); + assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); assert_eq!(c.photo(a).map(|p| p.rating), Some(0)); // a batch that ends in a failed removal of a photo that exists assert!(c.apply(Op::Batch { ops: vec![Op::RemovePhoto { id: b }, Op::RemovePhoto { id: b }] }).is_err()); diff --git a/crates/catalog/src/tests_album_folder_photos.rs b/crates/catalog/src/tests_album_folder_photos.rs new file mode 100644 index 00000000000..45d11c6b124 --- /dev/null +++ b/crates/catalog/src/tests_album_folder_photos.rs @@ -0,0 +1,353 @@ +//! What a folder of albums shows (as a collection set does in Lightroom Classic): every photo of +//! the albums and smart albums inside it, at any depth, each photo once. +//! +//! Scenarios: +//! - Given a folder with two albums that share a photo, when the folder is shown, then it lists +//! the photos of both, the shared one once, and nothing from albums outside it. +//! - Given a smart album in the folder, then its current matches are shown too. +//! - Given a folder inside the folder, then the inner folder's albums count as well, and the +//! inner folder alone shows only its own. +//! - Given a photo in Recently Deleted, then the folder doesn't count or list it. +//! - Given an empty folder, then it shows nothing. +//! - A folder is not an album a photo is "in": `albums_of` names albums only. +//! - Given a smart album testing the folder it is in, then that is a loop: it is reported, and +//! asking still answers. +//! - Given a damaged library whose folders contain each other, then asking still answers. +//! - Given a folder of many big albums, then showing it, or a smart album limited to it, costs a +//! pass over the photos, not one per album. +//! - Given a smart album about to be put in a folder its rules lead to, then that is known +//! before it is made or moved. +//! - Given a damaged library (a folder that also has rules, an album inside a plain album), then +//! every question about the folder gives the same answer, and only what the sidebar lists counts. + +use serde_json::json; + +use crate::*; + +fn photo(c: &mut Catalog, name: &str) -> PhotoId { + let id = c.alloc_photo_id(); + let p = Photo::new(id, Source::Demo { scene: 1 }, name, "JPEG", 6000, 4000, "2026-09-30T10:00:00"); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id +} + +fn folder(c: &mut Catalog, name: &str, parent: Option) -> AlbumId { + let id = c.alloc_album_id(); + c.apply(Op::AddAlbum { album: Album { parent, folder: true, ..Album::new(id, name) } }).unwrap(); + id +} + +fn album(c: &mut Catalog, name: &str, parent: Option, photos: &[PhotoId]) -> AlbumId { + let id = c.alloc_album_id(); + c.apply(Op::AddAlbum { album: Album { parent, photos: photos.to_vec(), ..Album::new(id, name) } }).unwrap(); + id +} + +fn smart(c: &mut Catalog, name: &str, parent: Option, rules: Filter) -> AlbumId { + let id = c.alloc_album_id(); + c.apply(Op::AddAlbum { album: Album { parent, smart: Some(Box::new(rules)), ..Album::new(id, name) } }).unwrap(); + id +} + +/// What the grid shows for an album or folder, oldest first (these photos share a date, so in the +/// order they were added). +fn shown(c: &Catalog, id: AlbumId) -> Vec { + c.query(&Filter { album: Some(id), ..Default::default() }, &Sort { ascending: true, ..Default::default() }) +} + +#[test] +fn a_folder_shows_the_photos_of_its_albums_once_each() { + let mut c = Catalog::new(); + let [a, b, d, e] = ["a.jpg", "b.jpg", "d.jpg", "e.jpg"].map(|n| photo(&mut c, n)); + let trips = folder(&mut c, "Trips", None); + album(&mut c, "Rome", Some(trips), &[a, b]); + album(&mut c, "Paris", Some(trips), &[b, d]); + album(&mut c, "Elsewhere", None, &[e]); + assert_eq!(shown(&c, trips), [a, b, d], "b is in both albums and shows once; e is outside the folder"); + assert_eq!(c.album_photos(trips), [a, b, d]); + assert_eq!(c.album_count(trips), 3); + let in_trips = |id: PhotoId| c.album_contains(trips, c.photo(id).unwrap()); + assert!(in_trips(a) && in_trips(b) && in_trips(d) && !in_trips(e)); + assert_eq!(c.album_members(trips).len(), 2); +} + +#[test] +fn a_folder_shows_what_its_smart_albums_match_now() { + let mut c = Catalog::new(); + let [a, b, d] = ["a.jpg", "b.jpg", "d.jpg"].map(|n| photo(&mut c, n)); + let trips = folder(&mut c, "Trips", None); + album(&mut c, "Rome", Some(trips), &[a]); + smart(&mut c, "Best", Some(trips), Filter { rating: 4, ..Default::default() }); + assert_eq!(shown(&c, trips), [a]); + // a smart album is live, and so is the folder holding it + c.apply(Op::SetRating { id: b, rating: 5 }).unwrap(); + c.apply(Op::SetRating { id: a, rating: 5 }).unwrap(); + assert_eq!(shown(&c, trips), [a, b], "a is in the album and matches the smart album: once"); + assert_eq!(c.album_count(trips), 2); + assert!(!c.album_contains(trips, c.photo(d).unwrap())); +} + +#[test] +fn a_folder_shows_the_albums_of_the_folders_inside_it() { + let mut c = Catalog::new(); + let [a, b, d] = ["a.jpg", "b.jpg", "d.jpg"].map(|n| photo(&mut c, n)); + let trips = folder(&mut c, "Trips", None); + let europe = folder(&mut c, "Europe", Some(trips)); + let rome = album(&mut c, "Rome", Some(europe), &[a]); + let asia = album(&mut c, "Asia", Some(trips), &[b]); + album(&mut c, "Loose", None, &[d]); + assert_eq!(shown(&c, trips), [a, b]); + assert_eq!(shown(&c, europe), [a], "the inner folder shows only its own"); + let mut members = c.album_members(trips); + members.sort(); + assert_eq!(members, [rome, asia], "albums at any depth, the folders themselves left out"); + // an album is its own only member; nothing else is one + assert_eq!(c.album_members(rome), [rome]); + assert!(c.album_members(AlbumId(999)).is_empty()); +} + +#[test] +fn a_folder_leaves_out_deleted_photos() { + let mut c = Catalog::new(); + let [a, b] = ["a.jpg", "b.jpg"].map(|n| photo(&mut c, n)); + let trips = folder(&mut c, "Trips", None); + album(&mut c, "Rome", Some(trips), &[a, b]); + c.apply(Op::SetDeleted { id: b, deleted: true }).unwrap(); + assert_eq!(shown(&c, trips), [a]); + assert_eq!(c.album_photos(trips), [a]); + assert_eq!(c.album_count(trips), 1); +} + +#[test] +fn an_empty_folder_shows_nothing() { + let mut c = Catalog::new(); + let a = photo(&mut c, "a.jpg"); + let empty = folder(&mut c, "Empty", None); + let inner = folder(&mut c, "Inner", Some(empty)); + assert!(shown(&c, empty).is_empty() && shown(&c, inner).is_empty()); + assert_eq!((c.album_count(empty), c.album_photos(empty).len()), (0, 0)); + assert!(!c.album_contains(empty, c.photo(a).unwrap())); + assert!(c.album_members(empty).is_empty()); +} + +#[test] +fn a_photo_is_in_albums_not_in_their_folders() { + let mut c = Catalog::new(); + let a = photo(&mut c, "a.jpg"); + let trips = folder(&mut c, "Trips", None); + let rome = album(&mut c, "Rome", Some(trips), &[a]); + assert_eq!(c.albums_of(a), [rome]); +} + +/// A smart album inside a folder that is limited to that folder (by its album filter, or by an +/// Album rule saved before the check refused it) would include itself: reported as a loop, and it +/// holds nothing of its own, so the question still ends. +#[test] +fn a_smart_album_testing_its_own_folder_is_a_loop_that_ends() { + let mut c = Catalog::new(); + let a = photo(&mut c, "a.jpg"); + let trips = folder(&mut c, "Trips", None); + let europe = folder(&mut c, "Europe", Some(trips)); + album(&mut c, "Rome", Some(europe), &[a]); + let by_filter = smart(&mut c, "In Trips", Some(europe), Filter { album: Some(trips), ..Default::default() }); + let outside = smart(&mut c, "Trips, outside", None, Filter { album: Some(trips), ..Default::default() }); + let loops = |c: &Catalog, id: AlbumId| c.smart_album_problems(id).iter().any(|p| p.issue == crate::rules::Issue::AlbumLoop); + assert!(c.album_reaches(by_filter, by_filter) && loops(&c, by_filter), "it is inside the folder it is limited to"); + assert!(!c.album_reaches(outside, outside) && c.album_reaches(outside, by_filter)); + assert!(!loops(&c, outside), "limited to a folder it isn't in: no loop"); + // both answer; the one outside shows the folder's photos + assert_eq!(shown(&c, outside), [a]); + assert_eq!(shown(&c, trips), [a]); + assert_eq!(shown(&c, by_filter), [a], "what the folder holds without it"); + // the same through an Album rule + let rule: Filter = serde_json::from_value(serde_json::json!({"ruleSet": {"rules": [{"field": "album", "op": "is", "value": trips.0}]}})).unwrap(); + let by_rule = smart(&mut c, "Rule", Some(trips), rule.clone()); + assert!(c.album_reaches(by_rule, by_rule)); + let problems = rule.rule_set.unwrap().check_for(&c, Some(by_rule)); + assert!(!problems.is_empty(), "an Album rule still can't name a folder"); + let _ = shown(&c, by_rule); // returns + let _ = shown(&c, trips); +} + +/// Folders that contain each other can't be made here, but a damaged library file can say so. +#[test] +fn folders_containing_each_other_still_answer() { + let mut c = Catalog::new(); + let a = photo(&mut c, "a.jpg"); + let x = folder(&mut c, "X", None); + let y = folder(&mut c, "Y", Some(x)); + let inside = album(&mut c, "Inside", Some(y), &[a]); + c.albums.get_mut(&x).unwrap().parent = Some(y); + assert_eq!(c.album_members(x), [inside]); + assert_eq!(c.album_members(y), [inside]); + assert_eq!(shown(&c, x), [a]); + assert_eq!(c.album_count(y), 1); + // a folder that is its own parent + c.albums.get_mut(&x).unwrap().parent = Some(x); + assert_eq!(c.album_members(x), [inside]); + assert_eq!(shown(&c, y), [a]); + // and a ring the album asked about is not in + let other = folder(&mut c, "Other", None); + assert!(c.album_members(other).is_empty() && shown(&c, other).is_empty()); +} + +/// 200 albums of 2,000 photos each in one folder, and as many photos again in none of them: +/// asking each photo of each album's list is the slow way (it reads every list to the end for a +/// photo in none). A pass over the library gathers the folder's photos once; so does a smart +/// album limited to the folder. Counted by how often the folder is gathered, not by the clock. +#[test] +fn a_folder_of_big_albums_is_shown_in_one_pass() { + let mut c = Catalog::new(); + let photos: Vec = (0..8000).map(|i| photo(&mut c, &format!("p{i}.jpg"))).collect(); + let big = folder(&mut c, "Big", None); + for k in 0..200usize { + let list: Vec = photos[..4000].iter().copied().skip(k % 2).step_by(2).collect(); + album(&mut c, &format!("A{k}"), Some(big), &list); + } + let limited = smart(&mut c, "In Big", None, Filter { album: Some(big), ..Default::default() }); + // one photo at a time: nothing is gathered, which is why it is the slow way + let gathers = || crate::FOLDER_GATHERS.with(std::cell::Cell::get); + let before = gathers(); + let n = c.photos().filter(|p| c.album_contains(big, p)).count(); + assert_eq!((n, gathers() - before), (4000, 0)); + for (what, f) in [ + ("query", &(|| shown(&c, big).len()) as &dyn Fn() -> usize), + ("count", &|| c.album_count(big)), + ("photos", &|| c.album_photos(big).len()), + ("smart album's count", &|| c.album_count(limited)), + ("smart album's query", &|| shown(&c, limited).len()), + ] { + let before = gathers(); + assert_eq!(f(), 4000, "{what}"); + assert_eq!(gathers() - before, 1, "{what} gathered the folder's photos once for the whole pass"); + } +} + +/// A smart album placed in a folder its rules lead to would include itself: asked before it is +/// made or moved there (`smart_album_would_loop_in`). +#[test] +fn rules_that_lead_to_a_folder_cant_go_in_it() { + let mut c = Catalog::new(); + let trips = folder(&mut c, "Trips", None); + let europe = folder(&mut c, "Europe", Some(trips)); + let other = folder(&mut c, "Other", None); + let in_trips = Filter { album: Some(trips), ..Default::default() }; + assert!(c.smart_album_would_loop_in(&in_trips, trips), "in the folder it is limited to"); + assert!(c.smart_album_would_loop_in(&in_trips, europe), "or in a folder inside it"); + assert!(!c.smart_album_would_loop_in(&in_trips, other)); + let in_europe = Filter { album: Some(europe), ..Default::default() }; + assert!(!c.smart_album_would_loop_in(&in_europe, trips), "limited to an inner folder, beside it: no loop"); + // through another smart album: Outside is limited to Trips, and these rules test Outside + let outside = smart(&mut c, "Outside", None, in_trips); + let tests_outside: Filter = + serde_json::from_value(serde_json::json!({"ruleSet": {"rules": [{"field": "album", "op": "is", "value": outside.0}]}})).unwrap(); + assert!(c.smart_album_would_loop_in(&tests_outside, europe)); + assert!(!c.smart_album_would_loop_in(&tests_outside, other)); + assert!(!c.smart_album_would_loop_in(&Filter::default(), trips), "rules that test no album"); +} + +/// What moves with an album or folder: the first smart album in it that would include itself in +/// the folder it is going to (`album_move_would_loop`). +#[test] +fn a_move_that_would_loop_names_the_smart_album() { + let mut c = Catalog::new(); + let trips = folder(&mut c, "Trips", None); + let europe = folder(&mut c, "Europe", Some(trips)); + let boxed = folder(&mut c, "Box", None); + let view = smart(&mut c, "Trips view", Some(boxed), Filter { album: Some(trips), ..Default::default() }); + let plain = album(&mut c, "Plain", Some(boxed), &[]); + assert_eq!(c.album_move_would_loop(view, trips), Some(view)); + assert_eq!(c.album_move_would_loop(view, europe), Some(view)); + assert_eq!(c.album_move_would_loop(boxed, trips), Some(view), "inside the folder that moves"); + assert_eq!(c.album_move_would_loop(plain, trips), None); + assert_eq!(c.album_move_would_loop(trips, boxed), None, "the folder it shows may go beside it"); + assert_eq!(c.album_move_would_loop(AlbumId(999), trips), None); +} + +/// Two libraries asked in one pass (one's pass consulting the other): each folder's photos are +/// its own library's, though the folders share an id. +#[test] +fn a_pass_keeps_two_catalogs_apart() { + let mut one = Catalog::new(); + let a = photo(&mut one, "a.jpg"); + let f = folder(&mut one, "F", None); + album(&mut one, "In", Some(f), &[a]); + let mut two = Catalog::new(); + photo(&mut two, "a.jpg"); + assert_eq!(folder(&mut two, "F", None), f); + let (in_one, in_two) = crate::gathering(|| (one.album_contains(f, one.photo(a).unwrap()), two.album_contains(f, two.photo(a).unwrap()))); + assert_eq!((in_one, in_two), (true, false)); +} + +/// A library file that says a folder also has rules: it is a folder (as the sidebar shows it), to +/// every question. +#[test] +fn a_folder_with_rules_is_still_a_folder() { + let mut c = Catalog::new(); + let [a, b] = ["a.jpg", "b.jpg"].map(|n| photo(&mut c, n)); + c.apply(Op::SetRating { id: b, rating: 5 }).unwrap(); + let f = folder(&mut c, "F", None); + album(&mut c, "Inside", Some(f), &[a]); + c.albums.get_mut(&f).unwrap().smart = Some(Box::new(Filter { rating: 5, ..Default::default() })); + let holds = |id: PhotoId| c.album_contains(f, c.photo(id).unwrap()); + assert!(holds(a) && !holds(b)); + assert_eq!((shown(&c, f), c.album_photos(f), c.album_count(f)), (vec![a], vec![a], 1)); + // the whole count counts it from the albums inside it, as it does every folder (its rules are not asked) + assert_eq!(crate::tally::AlbumTally::of(&c).counts().get(&f), Some(&1)); +} + +/// A smart album limited to a folder, and a smart album inside that folder that tests it: a loop through the folder +/// (a library file saved anyway). The whole count must give each of them the count it gets alone. +#[test] +fn a_loop_through_a_folder_is_counted_by_its_rules() { + let mut c = Catalog::new(); + let [a, b, _d, _e] = ["a.jpg", "b.jpg", "d.jpg", "e.jpg"].map(|n| photo(&mut c, n)); + let f = folder(&mut c, "F", None); + album(&mut c, "Plain", Some(f), &[a, b]); + let view = c.alloc_album_id(); + let inner = c.alloc_album_id(); + let not_in_view = json!({"match": "all", "rules": [{"field": "album", "op": "isNot", "value": view.0}]}); + let limited = Filter { album: Some(f), ..Default::default() }; + c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(limited)), ..Album::new(view, "View") } }).unwrap(); + let rule_set = Some(serde_json::from_value(not_in_view).unwrap()); + let rules = Filter { rule_set, ..Default::default() }; + c.apply(Op::AddAlbum { album: Album { parent: Some(f), smart: Some(Box::new(rules)), ..Album::new(inner, "Inside") } }).unwrap(); + let together = crate::tally::AlbumTally::of(&c); + for id in [view, inner] { + assert_eq!(together.counts().get(&id).copied(), Some(c.album_count(id)), "album {id:?}"); + } +} + +/// A library file that puts an album inside a plain album: the sidebar lists nothing under an +/// album, so the folder around them doesn't show that album's photos. +#[test] +fn an_album_inside_a_plain_album_is_not_in_the_folder() { + let mut c = Catalog::new(); + let [a, b] = ["a.jpg", "b.jpg"].map(|n| photo(&mut c, n)); + let f = folder(&mut c, "F", None); + let plain = album(&mut c, "Plain", Some(f), &[a]); + let child = album(&mut c, "Child", None, &[b]); + c.albums.get_mut(&child).unwrap().parent = Some(plain); + assert_eq!(c.album_members(f), [plain]); + assert_eq!(shown(&c, f), [a]); + // nor one whose folder is gone + c.albums.get_mut(&child).unwrap().parent = Some(AlbumId(999)); + assert_eq!(c.album_members(f), [plain]); +} + +/// Folders that contain each other (a damaged library): moving something into the ring is +/// answered, not looked into for ever. +#[test] +fn moving_into_folders_that_contain_each_other_ends() { + let mut c = Catalog::new(); + let x = folder(&mut c, "X", None); + let y = folder(&mut c, "Y", Some(x)); + let loose = album(&mut c, "Loose", None, &[]); + c.albums.get_mut(&x).unwrap().parent = Some(y); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = c.apply(Op::MoveAlbum { id: loose, parent: Some(y) }); + let _ = tx.send(()); + }); + assert!(rx.recv_timeout(std::time::Duration::from_secs(20)).is_ok(), "the move never answered"); +} diff --git a/crates/catalog/src/tests_tally.rs b/crates/catalog/src/tests_tally.rs index 4953a8bd1ec..5d60f075721 100644 --- a/crates/catalog/src/tests_tally.rs +++ b/crates/catalog/src/tests_tally.rs @@ -47,7 +47,7 @@ fn path(op: &str, value: &str) -> serde_json::Value { json!({"field": "filePath", "op": op, "value": value}) } -/// Every album's count in `c`, each album counted alone (no pass, rules worked out per photo). +/// Every album's count in `c`, each album counted alone (no pass, rules worked out per photo), folders of albums too. fn counted_alone(c: &Catalog) -> Vec<(AlbumId, usize)> { let mut v: Vec<_> = c.albums().map(|a| (a.id, c.album_count(a.id))).collect(); v.sort_unstable(); @@ -70,6 +70,14 @@ fn a_whole_count_equals_each_album_counted_alone() { let folder = Album { folder: true, ..Album::new(AlbumId(2), "Trips") }; let inside = Album { parent: Some(AlbumId(2)), photos: (0..240).step_by(3).map(|i| PhotoId(i + 1)).collect(), ..Album::new(AlbumId(3), "In") }; ops.extend([plain, folder, inside].map(|album| Op::AddAlbum { album })); + // folders inside folders, with smart albums (one testing another) and an empty folder; a deleted photo is in none + let inner = Album { folder: true, parent: Some(AlbumId(2)), ..Album::new(AlbumId(4), "Rome") }; + let empty = Album { folder: true, ..Album::new(AlbumId(5), "Nothing") }; + ops.extend([inner, empty].map(|album| Op::AddAlbum { album })); + for (id, parent, rules) in [(40, 4, json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]})), (41, 2, json!({"rules": [is(40)]}))] { + let album = Album { parent: Some(AlbumId(parent)), ..smart(id, rules) }; + ops.push(Op::AddAlbum { album }); + } // the inner albums: #2-like, #14-like, then albums chained on it, the other way round, in groups and in different orders ops.push(Op::AddAlbum { album: smart( diff --git a/crates/engine/src/album_counts.rs b/crates/engine/src/album_counts.rs new file mode 100644 index 00000000000..7c466a91d80 --- /dev/null +++ b/crates/engine/src/album_counts.rs @@ -0,0 +1,101 @@ +//! The photo counts `albums.list` answers with. +//! +//! Counting a smart album asks every photo whether its rules hold: seconds in a large library, and a window that does +//! it on its UI thread stops answering for that long. So a window offers the counts it keeps +//! ([`Session::offer_album_counts`]; they are counted on a worker thread) and `albums.list` counts nothing itself. +//! +//! With no window (the CLI, the MCP server, a script) there is no UI thread to stop, and the caller wants the numbers: +//! they are counted here, once, and kept. An edit to a photo or a few is followed photo by photo, as the sidebar's +//! are ([`AlbumTally::update`]); anything more counts every photo again. + +use std::collections::HashMap; +use std::sync::Arc; + +use lightcraft_catalog::tally::AlbumTally; +use lightcraft_catalog::{AlbumId, Catalog}; + +/// Every album's count, as `albums.list` takes them. +pub(crate) type Counts = Arc>; + +/// How far the counts a window keeps are from the catalog and the session clock as they are now. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CountsAge { + /// Of the catalog as it is now, and of this minute. + Current, + /// Of the catalog as it is now, but of an earlier minute: only a smart album whose rules ask about "the last N + /// days" (its own, or those of an album it tests), or a folder holding one, can have changed since. + ClockBehind, + /// Of an earlier catalog, or none yet: every smart album's and folder's count is behind. + Behind, +} + +/// Counts, and how current they are. +pub(crate) struct Answer { + pub counts: Counts, + pub age: CountsAge, +} + +/// The counts a session keeps for `albums.list`. +#[derive(Default)] +pub(crate) struct AlbumCounts { + /// What a window offered for the next `albums.list`. + offered: Option, + /// Counted here, when no window offers any. + kept: Option, + /// How often every photo was counted here (tests check that a repeated list, and an edit to a photo or a few, + /// don't). + pub scans: usize, +} + +/// The counts made here. +struct Kept { + /// The library they are of ([`Session::library_generation`]): album ids start again in every library. + library: u64, + /// The minute they are of while a smart album asks about "the last N days" (else empty). + minute: String, + tally: AlbumTally, + shown: Counts, +} + +impl AlbumCounts { + /// `albums.list` takes `counts` next, `age` being how far they are from the catalog and the clock as they are now. + pub fn offer(&mut self, counts: Counts, age: CountsAge) { + self.offered = Some(Answer { counts, age }); + } + + /// Nothing is offered any more. + pub fn withdraw(&mut self) { + self.offered = None; + } + + /// The counts for `albums.list`: the ones offered, else counted here (`now` is the session clock). + pub fn answer(&mut self, cat: &Catalog, library: u64, now: &str) -> Answer { + if let Some(offered) = self.offered.take() { + return offered; + } + let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); + let minute = if relative { crate::clock_minute(now) } else { "" }; + if relative { + // "in the last N days" counts back from the session clock, as in the grid + lightcraft_catalog::rules::set_now(Some(now.to_string())); + } + let followed = self.kept.take().filter(|k| k.library == library && k.minute == minute).and_then(|mut k| { + if k.tally.revision() == cat.revision { + return Some(k); + } + k.tally.update(cat).then(|| { + k.shown = Arc::new(k.tally.counts().clone()); + k + }) + }); + let kept = followed.unwrap_or_else(|| { + self.scans += 1; + let tally = AlbumTally::of(cat); + let shown = Arc::new(tally.counts().clone()); + Kept { library, minute: minute.to_string(), tally, shown } + }); + let counts = kept.shown.clone(); + self.kept = Some(kept); + Answer { counts, age: CountsAge::Current } + } +} diff --git a/crates/engine/src/cmd/library/filters.rs b/crates/engine/src/cmd/library/filters.rs index f0a3a504f34..8f7dfc8acc9 100644 --- a/crates/engine/src/cmd/library/filters.rs +++ b/crates/engine/src/cmd/library/filters.rs @@ -38,6 +38,24 @@ pub(super) fn merge_rules( Ok(f) } +/// Why a smart album called `name` with `rules` can't be in folder `parent`: its rules lead to +/// that folder or one around it (the view of a folder, saved inside it), so it would be one of +/// the albums it asks about. `None` when it can. +pub(super) fn smart_loop_in(cat: &lightcraft_catalog::Catalog, name: &str, rules: &lightcraft_catalog::Filter, parent: AlbumId) -> Option { + cat.smart_album_would_loop_in(rules, parent).then(|| { + let folder = cat.album(parent).map(|f| f.name.as_str()).unwrap_or_default(); + format!("smart album “{name}” would include itself in folder “{folder}”: its rules show that folder or one around it. Put it outside them") + }) +} + +/// [`smart_loop_in`] for album or folder `id` on its way into `parent` (`None`: the top level, +/// where nothing loops): the first smart album among what moves that would include itself. +pub(super) fn moved_loop_in(cat: &lightcraft_catalog::Catalog, id: AlbumId, parent: Option) -> Option { + let parent = parent?; + let looping = cat.album(cat.album_move_would_loop(id, parent)?)?; + smart_loop_in(cat, &looping.name, looping.smart.as_deref()?, parent) +} + /// Whether `path` lies above a disk: some of its `ids` photos are on a disk (not the startup /// disk) that the folder does not lie in. Such a folder (`/Volumes`, `/mnt`…) is not a folder of /// one disk but a way to reach several. diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 2e7c1311d0c..5d64bd29903 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1,4 +1,4 @@ -use super::filters::{covers_other_disks, merge_rules, view_rules}; +use super::filters::{covers_other_disks, merge_rules, moved_loop_in, smart_loop_in, view_rules}; use super::gps::parse_gps; use super::import::{import_batch_done, import_params, list_auto_import_folder}; use super::selection::{ @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Show Source", [], None, - "{kind: all|recentlyAdded|album|recentlyDeleted|picks|missing|libraryFolder, id?: albumId, path?: a path from library.folders (for libraryFolder)}", + "{kind: all|recentlyAdded|album|recentlyDeleted|picks|missing|libraryFolder, id?: albumId (an album, a smart album, or a folder of albums: the photos of every album inside it, each once), path?: a path from library.folders (for libraryFolder)}", always, |s, p| { let kind = str_param(p, "kind").unwrap_or("all"); @@ -49,7 +49,8 @@ pub fn specs() -> Vec { "missing" => LibrarySource::Missing, "album" => { let a = album_param(p, "id", "library.source")?; - if s.catalog.album(a).is_none_or(|a| a.folder) { + // a folder of albums is a source too: what the albums inside it hold + if s.catalog.album(a).is_none() { return Err(bad("library.source", "no such album")); } // one album at a time: `to_filter` makes the album shown replace the filter's, and the @@ -818,6 +819,10 @@ pub fn specs() -> Vec { None => view_rules(s), }; let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId); + // the view of a folder, saved inside that folder, would be limited to itself + if let Some(folder) = parent { + smart_loop_in(&s.catalog, &name, &rules, folder).map_or(Ok(()), |why| Err(bad("album.createSmart", why)))?; + } let id = s.catalog.alloc_album_id(); let album = Album { parent, smart: Some(Box::new(rules)), ..Album::new(id, name) }; s.commit("New Smart Album", Op::AddAlbum { album })?; @@ -877,7 +882,7 @@ pub fn specs() -> Vec { view } else { let replace = bool_or(p, "replace", false); - let folder = cur.library_folder.clone(); + let (folder, album) = (cur.library_folder.clone(), cur.album); let base = if replace { Default::default() } else { cur }; let mut r = merge_rules(&base, p.get("rules").unwrap_or(&Value::Null), "album.setRules", &s.catalog, Some(id))?; // the rules dialog has no folder field: replacing its rules keeps the folder @@ -885,6 +890,11 @@ pub fn specs() -> Vec { if replace && p.get("rules").and_then(|r| r.get("libraryFolder")).is_none() { r.library_folder = folder; } + // nor one for the album or folder of albums a saved view is limited to + // (`album: null` drops it) + if replace && p.get("rules").and_then(|r| r.get("album")).is_none() { + r.album = album; + } r }; let set = Op::SetAlbumRules { id, rules: Box::new(rules) }; @@ -945,6 +955,7 @@ pub fn specs() -> Vec { cmd!("album.move", "Move Album", [], None, "{id, parent?: folderId|null}", always, |s, p| { let id = album_param(p, "id", "album.move")?; let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId); + moved_loop_in(&s.catalog, id, parent).map_or(Ok(()), |why| Err(bad("album.move", why)))?; s.commit("Move Album", Op::MoveAlbum { id, parent })?; ok() }), @@ -978,6 +989,9 @@ pub fn specs() -> Vec { }; order.insert(at.min(order.len()), id); let moved = me.parent != parent; + if moved { + moved_loop_in(&s.catalog, id, parent).map_or(Ok(()), |why| Err(bad("album.reorder", why)))?; + } let mut ops = Vec::new(); if moved { ops.push(Op::MoveAlbum { id, parent }); @@ -1229,7 +1243,7 @@ pub fn specs() -> Vec { return Err(bad("album.removePhotos", "smart albums update automatically: change their rules")); } if al.folder { - return Err(bad("album.removePhotos", "album folders don't hold photos")); + return Err(bad("album.removePhotos", "a folder shows the photos of the albums in it: remove them from those albums")); } let name = al.name.clone(); let targets: std::collections::HashSet = targets.into_iter().collect(); @@ -1243,6 +1257,9 @@ pub fn specs() -> Vec { ), cmd!("album.setCover", "Set as Album Cover", [], None, "{id: albumId, photo?: photoId}", has_active, |s, p| { let id = album_param(p, "id", "album.setCover")?; + if s.catalog.album(id).is_some_and(|a| a.folder) { + return Err(bad("album.setCover", "a folder has no cover: set one on an album in it")); + } let photo = p.get("photo").and_then(Value::as_u64).map(PhotoId).or(s.active()); s.commit("Set Album Cover", Op::SetAlbumCover { id, cover: photo })?; ok() diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs index a3926bc5144..bc82b4ce8c2 100644 --- a/crates/engine/src/cmd/query.rs +++ b/crates/engine/src/cmd/query.rs @@ -7,7 +7,7 @@ use lightcraft_develop::{CONTROLS, controls}; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, has_active}; -use crate::{LibrarySource, Session}; +use crate::{CountsAge, LibrarySource, Session}; pub fn photo_summary(p: &Photo) -> Value { json!({ @@ -38,20 +38,54 @@ pub fn photo_summary(p: &Photo) -> Value { /// instead of overflowing the stack. const MAX_ALBUM_DEPTH: usize = 64; -fn album_json(a: &Album, all: &[Album], counts: &HashMap, cat: &lightcraft_catalog::Catalog, depth: usize) -> Value { +/// The counts [`album_json`] shows a smart album or a folder with, and how far they are from the catalog and the clock +/// as they are now. +struct AlbumCounts<'a> { + counts: &'a HashMap, + age: CountsAge, +} + +impl AlbumCounts<'_> { + /// Whether the count of smart album or folder `a` is behind: any of them when the catalog moved on, only those with + /// rules about "the last N days" (of the album, or of one inside the folder) when only the clock did. + fn behind(&self, a: &Album, cat: &lightcraft_catalog::Catalog) -> bool { + match self.age { + CountsAge::Current => false, + CountsAge::Behind => true, + CountsAge::ClockBehind => cat + .album_members(a.id) + .iter() + .filter_map(|m| cat.album(*m)) + .filter_map(|m| m.smart.as_deref()) + .any(|rules| crate::filter_depends_on_clock(rules, cat)), + } + } +} + +fn album_json(a: &Album, all: &[Album], counts: &AlbumCounts, cat: &lightcraft_catalog::Catalog, depth: usize) -> Value { let children: Vec = if depth < MAX_ALBUM_DEPTH { all.iter().filter(|c| c.parent == Some(a.id)).map(|c| album_json(c, all, counts, cat, depth + 1)).collect() } else { Vec::new() }; + // An album of chosen photos is counted from its list, at once; a smart album's rules are asked of every photo, and a + // folder holds what the albums inside it do (a pass over the library of its own), so theirs are the counts kept. + let kept = a.is_smart() || a.folder; + let count = if kept { counts.counts.get(&a.id).copied().unwrap_or(0) } else { cat.album_count(a.id) }; let mut v = json!({ "id": a.id.0, "name": a.name, "folder": a.folder, - "count": counts.get(&a.id).copied().unwrap_or(0), + "count": count, "cover": a.cover.map(|c| c.0), "children": children, }); + if kept { + // Behind the catalog (an edit counted by every photo is under way), or behind the clock for an album whose rules, + // or those of an album inside the folder, ask about "the last N days": the count is the one before (0 before any), + // and the real one is being worked out. + v["countPending"] = json!(counts.behind(a, cat)); + } if let Some(rules) = &a.smart { v["smart"] = json!(true); v["rules"] = serde_json::to_value(rules).unwrap_or_default(); @@ -152,11 +186,14 @@ pub fn specs() -> Vec { .unwrap_or_default(); Ok(json!({"exif": exif, "xmp": xmp})) }), - cmd!(query "albums.list", "List Albums", [], None, "{}", always, |s, _| { + cmd!(query "albums.list", "List Albums", [], None, "{} → [{id, name, folder, count, cover, children, smart?, rules?, rulesText?, problems?, countPending?}] — the `count` of a smart album or a folder comes from the counts kept (`countPending: true`: not of the catalog as it is now yet, the ones before or 0)", always, |s, _| { let all: Vec = s.catalog.albums().cloned().collect(); - // every album counted in one pass, so a smart album tested by others is worked out once - let counts = lightcraft_catalog::tally::AlbumTally::of(&s.catalog); - Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all, counts.counts(), &s.catalog, 0)).collect())) + // counted nowhere here when a window keeps the counts; else every album in one pass, so a smart album tested + // by others is worked out once, and kept + let (now, library) = ((s.clock)(), s.library_generation()); + let counted = s.album_counts.answer(&s.catalog, library, &now); + let counts = AlbumCounts { counts: &counted.counts, age: counted.age }; + Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all, &counts, &s.catalog, 0)).collect())) }), cmd!(query "photo.inspect", "Inspect Photo", [], None, "{id?}", always, |s, p| { let id = photo_arg(s, p, "photo.inspect")?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index acaa1807009..d1015a49ecf 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ extern crate lightcraft_denoise_core as lightcraft_denoise; pub mod activity; +mod album_counts; #[cfg(not(target_arch = "wasm32"))] pub mod apple_photos; pub mod availability; @@ -85,6 +86,7 @@ pub mod walk; use std::sync::Arc; +pub use album_counts::CountsAge; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use errors::{AiModel, ErrorKind}; pub use fonts::{CRAFT_FONTS, CraftFont}; @@ -200,7 +202,8 @@ fn clock_minute(now: &str) -> &str { now.get(..16).unwrap_or(now) } -/// Whether a query can change membership without a catalog edit, including the smart albums it tests. +/// Whether a query can change membership without a catalog edit, including the smart albums it tests (and the ones +/// inside a folder of albums it tests, at any depth). fn filter_depends_on_clock(filter: &Filter, catalog: &Catalog) -> bool { if filter.depends_on_now() { return true; @@ -211,7 +214,12 @@ fn filter_depends_on_clock(filter: &Filter, catalog: &Catalog) -> bool { if !seen.insert(id) { continue; } - let Some(smart) = catalog.album(id).and_then(|album| album.smart.as_deref()) else { continue }; + let Some(album) = catalog.album(id) else { continue }; + if album.folder { + pending.extend(catalog.album_members(id)); + continue; + } + let Some(smart) = album.smart.as_deref() else { continue }; if smart.depends_on_now() { return true; } @@ -226,6 +234,8 @@ static LIBRARY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64: pub struct Session { library_generation: u64, + /// The counts `albums.list` answers with. + album_counts: album_counts::AlbumCounts, /// Auto Sync: edits to the active photo also change the other selected photos (the settings /// that changed, nothing else). pub auto_sync: bool, @@ -444,9 +454,23 @@ impl Session { self.library_generation } + /// The next `albums.list` answers with `counts` and counts nothing itself: a window that keeps the albums' counts + /// (counted off its UI thread) offers them with how far they are from the catalog and the clock as they are now, + /// and `albums.list` marks the smart albums whose count is behind as pending. + /// [`Session::withdraw_album_counts`] takes the offer back once the command has run. + pub fn offer_album_counts(&mut self, counts: Arc>, age: CountsAge) { + self.album_counts.offer(counts, age); + } + + /// Take back what [`Session::offer_album_counts`] offered, if `albums.list` didn't use it. + pub fn withdraw_album_counts(&mut self) { + self.album_counts.withdraw(); + } + pub fn new() -> Session { Session { library_generation: LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + album_counts: album_counts::AlbumCounts::default(), auto_sync: false, catalog: Catalog::new(), source: LibrarySource::All, @@ -1114,7 +1138,7 @@ impl Session { // its own order, Recently Added (how far back it reaches moves with every import), Missing Photos. let own_order = matches!(self.source, LibrarySource::Album(a) if self.sort.key == lightcraft_catalog::SortKey::CaptureDate && self.filter == Filter::default() - && self.catalog.album(a).is_some_and(|al| !al.is_smart())); + && self.catalog.album(a).is_some_and(|al| !al.is_smart() && !al.folder)); let whole = own_order || matches!(self.source, LibrarySource::RecentlyAdded | LibrarySource::Missing); // A view that asks about "the last N days" (itself, or through a smart album it looks into) changes // with the clock as well as with edits: a photo nobody touched can stop matching. It is asked whole. @@ -1154,7 +1178,9 @@ impl Session { && self.sort.key == lightcraft_catalog::SortKey::CaptureDate && let LibrarySource::Album(a) = self.source && let Some(al) = self.catalog.album(a) + // an album's own order; a smart album and a folder of albums have none && !al.is_smart() + && !al.folder && self.filter == Filter::default() { // each photo's place looked up, not searched for (a big album sorted in O(n log n)) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae03859d21f..8da481b1696 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2,6 +2,8 @@ use serde_json::{Value, json}; use crate::{Selection, Session, command_specs}; +mod album_counts; +mod album_folder_source; mod album_order; mod album_remove; mod albums_local; diff --git a/crates/engine/src/tests/album_counts.rs b/crates/engine/src/tests/album_counts.rs new file mode 100644 index 00000000000..7858752baf1 --- /dev/null +++ b/crates/engine/src/tests/album_counts.rs @@ -0,0 +1,150 @@ +//! `albums.list` and the smart albums' counts: a window offers the counts it keeps and the command counts nothing +//! (listing them pending when they aren't of the catalog as it is now); a session with no window counts every photo +//! once and follows edits to a few. + +use std::sync::{Arc, Mutex}; + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::{CountsAge, Session}; + +fn photo(id: u64, captured: &str, rating: u8) -> Op { + let mut p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 60, 40, "2026-01-01T00:00:00"); + p.captured = Some(captured.into()); + p.rating = rating; + Op::AddPhoto { photo: Box::new(p) } +} + +fn library(ratings: &[u8]) -> Session { + let mut s = Session::new(); + for (i, r) in ratings.iter().enumerate() { + s.catalog.apply(photo(i as u64 + 1, "2026-09-30T11:59:30", *r)).unwrap(); + } + s +} + +fn listed(s: &mut Session, id: u64) -> Value { + let list = s.execute("albums.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().find(|a| a["id"] == id).cloned().unwrap() +} + +fn smart(s: &mut Session, name: &str, rules: Value) -> u64 { + s.execute("album.createSmart", &json!({"name": name, "rules": rules})).unwrap()["id"].as_u64().unwrap() +} + +/// Without a window the command counts every photo once, keeps the counts, and follows an edit to a photo from them. +#[test] +fn without_a_window_the_albums_are_counted_once_and_edits_to_a_photo_are_followed() { + let mut s = library(&[5, 1, 1, 4]); + let good = smart(&mut s, "Good", json!({"rating": 4})); + let picked = s.execute("album.create", &json!({"name": "Picked", "addSelected": false})).unwrap()["id"].as_u64().unwrap(); + s.execute("library.select", &json!({"ids": [1, 2]})).unwrap(); + s.execute("album.addPhotos", &json!({"id": picked, "ids": [1, 2]})).unwrap(); + assert_eq!(s.album_counts.scans, 0); + + let a = listed(&mut s, good); + assert_eq!((a["count"].as_u64(), a["countPending"].as_bool()), (Some(2), Some(false)), "{a}"); + assert_eq!(listed(&mut s, picked)["count"], 2); + assert_eq!(s.album_counts.scans, 1); + listed(&mut s, good); + assert_eq!(s.album_counts.scans, 1, "listed again: nothing changed, nothing counted"); + + s.execute("library.select", &json!({"ids": [2]})).unwrap(); + s.execute("photo.rate", &json!({"ids": [2], "rating": 5})).unwrap(); + assert_eq!(listed(&mut s, good)["count"], 3, "the edit is in the count"); + assert_eq!(s.album_counts.scans, 1, "followed from the photo it touched"); + + s.execute("album.setRules", &json!({"id": good, "rules": {"rating": 5}})).unwrap(); + let a = listed(&mut s, good); + assert_eq!((a["count"].as_u64(), a["countPending"].as_bool()), (Some(2), Some(false)), "{a}"); + assert_eq!(s.album_counts.scans, 2, "new rules ask every photo again"); + assert_eq!(a["count"].as_u64().unwrap(), s.catalog.album_count(AlbumId(good)) as u64); +} + +/// The counts a window offers are used as they are, once, with nothing counted here; a smart album is pending when the +/// window says they aren't of the catalog as it is now, or (for an album asking about "the last N days") of this minute. +#[test] +fn counts_a_window_offers_are_listed_with_nothing_counted_here() { + let mut s = library(&[5, 1, 1, 4]); + s.clock = Box::new(|| "2026-09-30T12:00:00".to_string()); + let good = smart(&mut s, "Good", json!({"rating": 4})); + let recent_rules = json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}}); + let recent = smart(&mut s, "Recent", recent_rules); + let offered = Arc::new(std::collections::HashMap::from([(AlbumId(good), 7), (AlbumId(recent), 8)])); + let counts_and_flags = |s: &mut Session| -> Vec<(u64, bool)> { + let list = s.execute("albums.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().map(|a| (a["count"].as_u64().unwrap(), a["countPending"].as_bool().unwrap())).collect() + }; + + s.offer_album_counts(offered.clone(), CountsAge::Behind); + assert_eq!(counts_and_flags(&mut s), [(7, true), (8, true)]); + assert_eq!(s.album_counts.scans, 0, "nothing is counted for an offer"); + + s.offer_album_counts(offered.clone(), CountsAge::Current); + assert_eq!(counts_and_flags(&mut s), [(7, false), (8, false)]); + assert_eq!(s.album_counts.scans, 0); + + // a count of an earlier minute is behind only for the album whose rules ask about the clock + s.offer_album_counts(offered, CountsAge::ClockBehind); + assert_eq!(counts_and_flags(&mut s), [(7, false), (8, true)]); + assert_eq!(s.album_counts.scans, 0); + + // used once: the next answer is the session's own + assert_eq!(counts_and_flags(&mut s), [(2, false), (4, false)]); + assert_eq!(s.album_counts.scans, 1); + + // and an offer not used is taken back + s.offer_album_counts(Arc::new(Default::default()), CountsAge::Behind); + s.withdraw_album_counts(); + assert_eq!(counts_and_flags(&mut s), [(2, false), (4, false)]); +} + +/// "In the last hour" counts back from the session clock: the counts kept are of its minute, so an hour later they +/// are counted again though the catalog didn't change. +#[test] +fn counts_of_albums_asking_about_the_last_hour_follow_the_session_clock() { + let mut s = library(&[1]); + let now = Arc::new(Mutex::new("2026-09-30T12:00:00".to_string())); + let clock = now.clone(); + s.clock = Box::new(move || clock.lock().unwrap().clone()); + let rules = json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}}); + let recent = smart(&mut s, "Recent", rules); + assert_eq!(listed(&mut s, recent)["count"], 1); + assert_eq!(listed(&mut s, recent)["count"], 1); + assert_eq!(s.album_counts.scans, 1, "the same minute"); + *now.lock().unwrap() = "2026-09-30T13:00:10".into(); + assert_eq!(listed(&mut s, recent)["count"], 0, "an hour later the photo is out of it"); + assert_eq!(s.album_counts.scans, 2); + lightcraft_catalog::rules::set_now(None); +} + +/// A folder of albums is counted with the others, from the albums inside it, and is behind with them: when only the +/// clock moved, a folder is behind only if an album inside it asks about "the last N days". +#[test] +fn a_folder_is_counted_with_the_albums_inside_it_and_is_pending_with_them() { + let mut s = library(&[5, 1, 1, 4]); + s.clock = Box::new(|| "2026-09-30T12:00:00".to_string()); + let folder = |s: &mut Session, name: &str| s.execute("album.create", &json!({"name": name, "folder": true})).unwrap()["id"].as_u64().unwrap(); + let (quiet, loud) = (folder(&mut s, "Quiet"), folder(&mut s, "Loud")); + let inner = s.execute("album.create", &json!({"name": "Inner", "folder": true, "parent": quiet})).unwrap()["id"].as_u64().unwrap(); + s.execute("album.createSmart", &json!({"name": "Good", "rules": {"rating": 4}, "parent": inner})).unwrap(); + let recent_rules = json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}}); + s.execute("album.createSmart", &json!({"name": "Recent", "rules": recent_rules, "parent": loud})).unwrap(); + let tops = |s: &mut Session| -> Vec<(u64, bool)> { + let list = s.execute("albums.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().map(|a| (a["count"].as_u64().unwrap(), a["countPending"].as_bool().unwrap())).collect() + }; + // counted here without a window: every folder's photos are those of the albums inside it + assert_eq!(tops(&mut s), [(2, false), (4, false)]); + assert_eq!(s.album_counts.scans, 1); + assert_eq!(s.catalog.album_count(lightcraft_catalog::AlbumId(quiet)), 2); + + let offered = Arc::new(std::collections::HashMap::from([(lightcraft_catalog::AlbumId(quiet), 7), (lightcraft_catalog::AlbumId(loud), 8)])); + s.offer_album_counts(offered.clone(), CountsAge::ClockBehind); + assert_eq!(tops(&mut s), [(7, false), (8, true)]); + s.offer_album_counts(offered, CountsAge::Behind); + assert_eq!(tops(&mut s), [(7, true), (8, true)]); + assert_eq!(s.album_counts.scans, 1, "nothing counted for an offer"); + lightcraft_catalog::rules::set_now(None); +} diff --git a/crates/engine/src/tests/album_folder_source.rs b/crates/engine/src/tests/album_folder_source.rs new file mode 100644 index 00000000000..2f1cb52bc38 --- /dev/null +++ b/crates/engine/src/tests/album_folder_source.rs @@ -0,0 +1,327 @@ +//! A folder of albums as a source (`library.source {kind: "album", id: }`), as a +//! collection set is in Lightroom Classic: the grid shows the photos of every album and smart +//! album inside it, each once. +//! +//! Scenarios: +//! - Given a folder whose albums share a photo, when the folder is shown, then the grid lists +//! their photos once each, is titled with the folder's name and counts them. +//! - Given an inner folder and a smart album, then theirs are shown too, and the view follows +//! what the albums hold. +//! - Given a sort, newest or oldest first, then a folder follows it (it has no order by hand). +//! - Given a folder shown in the default order, when a photo is rated, then the view follows the edit +//! photo by photo (it has no order of its own to be worked out whole), and still shows the right photos. +//! - Given a filter, then it narrows the folder's photos like any other source's. +//! - When the shown folder is deleted, then the grid goes back to All Photos. +//! - Given a folder shown, when the view is saved as a smart album, then that album shows the +//! same photos and follows the folder. +//! - Given a folder's view saved as a smart album, when its rules are edited in the rules +//! dialog (which replaces them), then it is still limited to the folder; clearing the limit +//! takes saying so. +//! - A folder still holds no photos of its own: adding to it, removing from it or giving it a +//! cover is refused, and nothing is recorded to undo. +//! - Given a folder shown, when its view is saved as a smart album inside that folder, or a +//! smart album limited to the folder is moved into it, then that is refused (it would include +//! itself) and says where it can go. +//! - Agents see the folder's count in `albums.list`. +//! - The folder is still the source after the library is closed and opened again. + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::{LibrarySource, Session}; + +/// Photos `1..=n`, one a day from 2026-01-01 (so the newest has the highest id). +fn photos(s: &mut Session, n: u64) -> Vec { + (1..=n) + .map(|day| { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::Demo { scene: 1 }, &format!("p{day}.jpg"), "JPEG", 60, 40, "2026-02-01T10:00:00"); + p.captured = Some(format!("2026-01-{day:02}T10:00:00")); + // committed, so a library on disk records it + s.commit("Add Photo", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 + }) + .collect() +} + +fn make(s: &mut Session, params: Value) -> u64 { + s.execute("album.create", ¶ms).unwrap()["id"].as_u64().unwrap() +} + +fn album(s: &mut Session, name: &str, parent: Option, ids: &[u64]) -> u64 { + let id = make(s, json!({"name": name, "parent": parent})); + if !ids.is_empty() { + // the command wants a selection to be enabled, whatever `ids` says + s.selection.ids = ids.iter().map(|i| PhotoId(*i)).collect(); + s.execute("album.addPhotos", &json!({"id": id, "ids": ids})).unwrap(); + s.selection.ids.clear(); + } + id +} + +fn rate(s: &mut Session, ids: &[u64], rating: u8) { + s.selection.ids = ids.iter().map(|i| PhotoId(*i)).collect(); + s.execute("photo.rate", &json!({"ids": ids, "rating": rating})).unwrap(); + s.selection.ids.clear(); +} + +fn show(s: &mut Session, id: u64) { + s.execute("library.source", &json!({"kind": "album", "id": id})).unwrap(); +} + +fn shown(s: &mut Session) -> Vec { + s.visible_cloned().iter().map(|p| p.0).collect() +} + +/// Trips ▸ { Rome [1, 2], Paris [2, 3] }, and Elsewhere [4] outside it. +fn trips(s: &mut Session) -> u64 { + photos(s, 5); + let trips = make(s, json!({"name": "Trips", "folder": true})); + album(s, "Rome", Some(trips), &[1, 2]); + album(s, "Paris", Some(trips), &[2, 3]); + album(s, "Elsewhere", None, &[4]); + trips +} + +#[test] +fn a_folder_shows_the_photos_of_its_albums_once_each() { + let mut s = Session::new(); + let trips = trips(&mut s); + show(&mut s, trips); + assert_eq!(s.source, LibrarySource::Album(AlbumId(trips))); + assert_eq!(shown(&mut s), [3, 2, 1], "newest first; 2 is in both albums and shows once"); + assert_eq!(s.source.label(&s.catalog), "Trips"); + assert_eq!(s.source_total(), Some(3)); +} + +#[test] +fn a_folder_follows_its_inner_folders_and_smart_albums() { + let mut s = Session::new(); + let trips = trips(&mut s); + let europe = make(&mut s, json!({"name": "Europe", "folder": true, "parent": trips})); + let oslo = album(&mut s, "Oslo", Some(europe), &[5]); + show(&mut s, trips); + assert_eq!(shown(&mut s), [5, 3, 2, 1]); + show(&mut s, europe); + assert_eq!(shown(&mut s), [5], "the inner folder shows only its own"); + // a smart album inside is live + show(&mut s, trips); + s.execute("album.createSmart", &json!({"name": "Best", "parent": europe, "rules": {"rating": 5}})).unwrap(); + rate(&mut s, &[4], 5); + assert_eq!(shown(&mut s), [5, 4, 3, 2, 1]); + // and so is the folder: what leaves its albums leaves it, what is moved out of it too + s.selection.ids = vec![PhotoId(5)]; + s.execute("album.removePhotos", &json!({"id": oslo, "ids": [5]})).unwrap(); + assert_eq!(shown(&mut s), [4, 3, 2, 1]); + s.execute("album.move", &json!({"id": europe, "parent": null})).unwrap(); + assert_eq!(shown(&mut s), [3, 2, 1]); +} + +#[test] +fn a_folder_follows_the_sort() { + let mut s = Session::new(); + let trips = trips(&mut s); + show(&mut s, trips); + assert!(!s.sort.ascending, "newest first to begin with"); + assert_eq!(shown(&mut s), [3, 2, 1]); + s.sort.ascending = true; + assert_eq!(shown(&mut s), [1, 2, 3]); +} + +#[test] +fn a_folder_follows_a_small_edit_instead_of_being_worked_out_whole() { + let mut s = Session::new(); + let trips = trips(&mut s); + show(&mut s, trips); + assert_eq!(shown(&mut s), [3, 2, 1]); + let (followed, whole) = (s.view_followed, s.view_worked_out); + rate(&mut s, &[2], 5); + assert_eq!(shown(&mut s), [3, 2, 1]); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole), "a rating changes no album: followed"); + // what changes an album's photos is still asked whole, and shows them + s.selection.ids = vec![PhotoId(5)]; + let rome = s.catalog.album_members(AlbumId(trips))[0].0; + s.execute("album.addPhotos", &json!({"id": rome, "ids": [5]})).unwrap(); + assert!(shown(&mut s).contains(&5)); +} + +#[test] +fn a_filter_narrows_a_folder() { + let mut s = Session::new(); + let trips = trips(&mut s); + rate(&mut s, &[2, 4], 4); + show(&mut s, trips); + s.execute("library.filter", &json!({"rating": 4})).unwrap(); + assert_eq!(shown(&mut s), [2], "4 is rated too, but in no album of the folder"); + assert_eq!(s.source_total(), Some(3), "the folder's own count, whatever the filter hides"); +} + +#[test] +fn deleting_the_shown_folder_goes_back_to_all_photos() { + let mut s = Session::new(); + let trips = trips(&mut s); + show(&mut s, trips); + s.execute("album.delete", &json!({"id": trips})).unwrap(); + assert_eq!(s.source, LibrarySource::All); + assert_eq!(shown(&mut s).len(), 5); + // back with undo, and showable again with what it held + s.execute("edit.undo", &json!({})).unwrap(); + show(&mut s, trips); + assert_eq!(shown(&mut s), [3, 2, 1]); +} + +#[test] +fn a_folder_view_saves_as_a_smart_album() { + let mut s = Session::new(); + let trips = trips(&mut s); + show(&mut s, trips); + let r = s.execute("album.createSmart", &json!({"name": "From Trips"})).unwrap(); + assert_eq!(r["count"], 3); + let saved = r["id"].as_u64().unwrap(); + show(&mut s, saved); + assert_eq!(shown(&mut s), [3, 2, 1]); + assert!(s.catalog.smart_album_problems(AlbumId(saved)).is_empty()); + // it follows the folder + album(&mut s, "Oslo", Some(trips), &[5]); + assert_eq!(shown(&mut s), [5, 3, 2, 1]); +} + +#[test] +fn editing_a_saved_folder_view_keeps_the_folder() { + let mut s = Session::new(); + let trips = trips(&mut s); + rate(&mut s, &[2, 4], 5); + show(&mut s, trips); + let saved = s.execute("album.createSmart", &json!({"name": "From Trips"})).unwrap()["id"].as_u64().unwrap(); + let album_of = |s: &Session| s.catalog.album(AlbumId(saved)).unwrap().smart.as_ref().unwrap().album; + // what the rules dialog sends on OK: the rule set, replacing the rest + let rated = json!({"match": "all", "rules": [{"field": "rating", "op": "gte", "value": 5}]}); + let r = s.execute("album.setRules", &json!({"id": saved, "replace": true, "rules": {"ruleSet": rated}})).unwrap(); + assert_eq!(album_of(&s), Some(AlbumId(trips)), "still limited to the folder"); + assert_eq!(r["count"], 1, "photo 2: rated 5 and in the folder; 4 is rated but outside it"); + // also with no rules left + let r = s.execute("album.setRules", &json!({"id": saved, "replace": true, "rules": {"ruleSet": {"match": "all", "rules": []}}})).unwrap(); + assert_eq!((album_of(&s), r["count"].as_u64()), (Some(AlbumId(trips)), Some(3))); + // the limit goes when the call says so, or names another album + s.execute("album.setRules", &json!({"id": saved, "replace": true, "rules": {"album": null}})).unwrap(); + assert_eq!(album_of(&s), None); +} + +#[test] +fn a_folder_holds_no_photos_of_its_own() { + let mut s = Session::new(); + let trips = trips(&mut s); + show(&mut s, trips); + s.selection.ids = vec![PhotoId(1)]; + s.selection.active = Some(PhotoId(1)); + let steps = s.undo.len(); + for cmd in ["album.addPhotos", "album.removePhotos", "album.setCover"] { + let e = s.execute(cmd, &json!({"id": trips, "ids": [1]})).unwrap_err().to_string(); + assert!(e.contains("folder"), "{cmd}: {e}"); + } + assert_eq!(s.undo.len(), steps, "nothing to undo"); + assert!(s.catalog.album(AlbumId(trips)).unwrap().cover.is_none()); + assert_eq!(shown(&mut s), [3, 2, 1]); +} + +#[test] +fn a_smart_album_limited_to_a_folder_cant_be_made_inside_it() { + let mut s = Session::new(); + let trips = trips(&mut s); + let europe = make(&mut s, json!({"name": "Europe", "folder": true, "parent": trips})); + show(&mut s, trips); + let (albums, steps) = (s.catalog.albums().count(), s.undo.len()); + // the folder's own menu: New ▸ Create Smart Album from Filter… (the view, into the folder) + for params in [ + json!({"name": "Here", "parent": trips}), + json!({"name": "Deeper", "parent": europe}), + json!({"name": "By rules", "parent": trips, "rules": {"album": trips}}), + ] { + let e = s.execute("album.createSmart", ¶ms).unwrap_err().to_string(); + let (name, folder) = (params["name"].as_str().unwrap(), if params["parent"] == europe { "Europe" } else { "Trips" }); + assert!(e.contains(name) && e.contains(folder) && e.contains("include itself"), "{params}: {e}"); + } + assert_eq!((s.catalog.albums().count(), s.undo.len()), (albums, steps), "nothing was made"); + // beside the folder, or limited to something else, it is made + let other = make(&mut s, json!({"name": "Other", "folder": true})); + s.execute("album.createSmart", &json!({"name": "Beside", "parent": other})).unwrap(); + s.execute("album.createSmart", &json!({"name": "Rated", "parent": trips, "rules": {"rating": 4}})).unwrap(); + show(&mut s, europe); + s.execute("album.createSmart", &json!({"name": "Of Europe", "parent": trips})).unwrap(); +} + +#[test] +fn a_smart_album_limited_to_a_folder_cant_be_moved_into_it() { + let mut s = Session::new(); + let trips = trips(&mut s); + show(&mut s, trips); + let saved = s.execute("album.createSmart", &json!({"name": "From Trips"})).unwrap()["id"].as_u64().unwrap(); + let europe = make(&mut s, json!({"name": "Europe", "folder": true, "parent": trips})); + let box_ = make(&mut s, json!({"name": "Box", "folder": true})); + let steps = s.undo.len(); + for parent in [trips, europe] { + let e = s.execute("album.move", &json!({"id": saved, "parent": parent})).unwrap_err().to_string(); + assert!(e.contains("From Trips") && e.contains("include itself"), "{e}"); + } + // nor inside a folder that is moved there + s.execute("album.move", &json!({"id": saved, "parent": box_})).unwrap(); + let e = s.execute("album.move", &json!({"id": box_, "parent": trips})).unwrap_err().to_string(); + assert!(e.contains("From Trips"), "{e}"); + let e = s.execute("album.reorder", &json!({"id": saved, "parent": trips})).unwrap_err().to_string(); + assert!(e.contains("include itself"), "placing it by hand is a move too: {e}"); + assert_eq!(s.undo.len(), steps + 1, "only the move into Box happened"); + assert!(s.catalog.smart_album_problems(AlbumId(saved)).is_empty()); + assert_eq!(s.catalog.album(AlbumId(saved)).unwrap().parent, Some(AlbumId(box_))); + // everything else still moves: out again, and plain albums and folders into Trips + s.execute("album.move", &json!({"id": saved, "parent": null})).unwrap(); + s.execute("album.move", &json!({"id": box_, "parent": trips})).unwrap(); + let plain = album(&mut s, "Plain", None, &[4]); + s.execute("album.move", &json!({"id": plain, "parent": trips})).unwrap(); + show(&mut s, saved); + assert_eq!(shown(&mut s), [4, 3, 2, 1], "and it follows the folder"); +} + +#[test] +fn an_unknown_album_is_no_source() { + let mut s = Session::new(); + trips(&mut s); + let e = s.execute("library.source", &json!({"kind": "album", "id": 999})).unwrap_err().to_string(); + assert!(e.contains("no such album"), "{e}"); + assert!(s.execute("library.source", &json!({"kind": "album"})).is_err()); + assert_eq!(s.source, LibrarySource::All); +} + +#[test] +fn agents_see_a_folders_count() { + let mut s = Session::new(); + let trips = trips(&mut s); + let list = s.execute("albums.list", &json!({})).unwrap(); + let row = list.as_array().unwrap().iter().find(|a| a["id"] == trips).unwrap(); + assert_eq!((row["folder"].as_bool(), row["count"].as_u64()), (Some(true), Some(3))); + assert_eq!(row["children"].as_array().unwrap().len(), 2); +} + +#[test] +fn a_folder_is_still_the_source_after_reopening() { + /// Gone with the test, however it ends. + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let scratch = Scratch(std::env::temp_dir().join(format!("lc-album-folder-source-{}", std::process::id()))); + let dir = scratch.0.clone(); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + let trips = trips(&mut s); + show(&mut s, trips); + let want = shown(&mut s); + s.save_view(); + drop(s); + let mut back = Session::new(); + back.open_library(&dir, false).unwrap(); + assert_eq!(back.source, LibrarySource::Album(AlbumId(trips))); + assert_eq!(shown(&mut back), want); +} diff --git a/crates/engine/src/tests/view_follow.rs b/crates/engine/src/tests/view_follow.rs index bc47d94c94b..d23b4c7b474 100644 --- a/crates/engine/src/tests/view_follow.rs +++ b/crates/engine/src/tests/view_follow.rs @@ -233,6 +233,33 @@ fn relative_clock_direct_and_nested_smart_album_sources_expire() { } } +/// A folder of albums is a source too: a smart album inside it (at any depth) whose rules are relative to now +/// ("in the last day") makes the folder's view and count change when the minute passes, as it does for the smart album itself. +#[test] +fn relative_clock_folder_of_albums_source_expires() { + for deeper in [false, true] { + let (mut s, now, ids) = relative_clock_session(&["2026-10-23T12:00:30"]); + let id_of = |r: Value| r["id"].as_u64().unwrap(); + let folder = id_of(s.execute("album.create", &json!({"name": "Outer", "folder": true})).unwrap()); + let parent = + if deeper { id_of(s.execute("album.create", &json!({"name": "Inner", "folder": true, "parent": folder})).unwrap()) } else { folder }; + s.execute( + "album.createSmart", + &json!({"name": "Recent", "parent": parent, "rules": {"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}}}), + ) + .unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": folder})).unwrap(); + assert_eq!(s.visible_cloned(), ids, "deeper={deeper}"); + assert_eq!(s.source_total(), Some(1), "deeper={deeper}"); + let revision = s.catalog.revision; + + *now.lock().unwrap() = "2026-10-24T12:01:00".to_string(); + assert!(s.visible_cloned().is_empty(), "deeper={deeper}"); + assert_eq!(s.source_total(), Some(0), "deeper={deeper}"); + assert_eq!(s.catalog.revision, revision, "deeper={deeper}"); + } +} + #[test] fn relative_clock_source_total_expires_before_or_after_visible_refresh() { for refresh_visible in [false, true] { @@ -360,6 +387,35 @@ fn an_edit_to_many_photos_or_to_more_than_photos_is_worked_out_whole() { assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole + 2)); } +/// A keyword created in the keyword list, inside another and given to the selected photo at once, changes no photo +/// but that one: the view and the albums' counts follow it from that photo instead of asking every photo again. +#[test] +fn a_keyword_created_inside_another_and_given_to_a_photo_is_followed_from_that_photo() { + use lightcraft_catalog::{AlbumId, tally::AlbumTally}; + let (mut s, ids, _, smart) = library(600); + let _ = s.visible_cloned(); + let mut tally = AlbumTally::of(&s.catalog); + let (followed, whole) = (s.view_followed, s.view_worked_out); + // (the second photo has no keywords: it is in the smart album of those) + let bare = ids[1]; + assert!(s.catalog.photo(bare).is_some_and(|p| p.meta.keywords.is_empty())); + let unkeyworded = tally.counts()[&AlbumId(smart)]; + s.execute("library.select", &json!({"ids": [bare.0]})).unwrap(); + s.execute("keyword.create", &json!({"name": "Rome", "parent": "travel", "addToSelected": true})).unwrap(); + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole), "followed, not worked out whole"); + assert!(tally.update(&s.catalog), "the counts followed"); + assert_eq!(tally.counts()[&AlbumId(smart)], unkeyworded - 1, "the photo has a keyword now"); + // a keyword created on its own, for no photo: nothing else to follow + s.execute("keyword.create", &json!({"name": "Paris", "parent": "travel"})).unwrap(); + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 2, whole)); + assert!(tally.update(&s.catalog)); + // and what was followed is what every photo says + assert_eq!(s.visible_cloned(), s.visible_in_full()); + assert_eq!(tally.counts()[&AlbumId(smart)], s.catalog.album_count(AlbumId(smart))); +} + #[test] fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo() { use lightcraft_catalog::tally::AlbumTally; @@ -378,6 +434,13 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo let made = s.execute("album.createSmart", &json!({"name": "More", "rules": rules})); assert!(made.is_ok(), "{rules}: {made:?}"); } + // and folders of albums, one inside another: their counts are made from the albums inside them, and followed too + let folder = s.execute("album.create", &json!({"name": "Trips", "folder": true})).unwrap()["id"].as_u64().unwrap(); + let inner = s.execute("album.create", &json!({"name": "Rome", "folder": true, "parent": folder})).unwrap()["id"].as_u64().unwrap(); + s.execute("album.createSmart", &json!({"name": "Well rated here", "parent": folder, "rules": {"rating": 3}})).unwrap(); + s.execute("album.createSmart", &json!({"name": "Red here", "parent": inner, "rules": {"label": "red"}})).unwrap(); + s.execute("library.select", &json!({"ids": ids.iter().take(12).map(|id| id.0).collect::>()})).unwrap(); + s.execute("album.create", &json!({"name": "Chosen here", "parent": inner, "addSelected": true})).unwrap(); assert!(s.catalog.album(lightcraft_catalog::AlbumId(smart)).is_some_and(|a| a.is_smart())); let fresh = |s: &Session| -> Vec<(u64, usize)> { let mut v: Vec<(u64, usize)> = s.catalog.albums().map(|a| (a.id.0, s.catalog.album_count(a.id))).collect(); @@ -402,7 +465,10 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo let moved = tally.revision() != s.catalog.revision; match (moved, tally.update(&s.catalog)) { (true, true) => followed += 1, - (true, false) => whole += 1, + (true, false) => { + tally = AlbumTally::of(&s.catalog); + whole += 1; + } // (an edit that was refused changed nothing: nothing to follow) (false, _) => {} } @@ -428,8 +494,10 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo let many: Vec = if many.len() >= 300 { many } else { s.visible_cloned().iter().take(300).map(|id| id.0).collect() }; if many.len() > 256 { s.execute("library.select", &json!({"ids": many})).unwrap(); + let before = shown(&tally); s.execute("photo.rate", &json!({"rating": 5})).unwrap(); assert!(!tally.update(&s.catalog), "more photos than are followed one by one"); - assert_eq!(shown(&tally), fresh(&s)); + assert_eq!(shown(&tally), before, "not followed: left as they were, to be counted again"); + assert_eq!(shown(&AlbumTally::of(&s.catalog)), fresh(&s)); } } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 93fe551847f..db718c265c3 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -8,6 +8,31 @@ pub struct LibraryCounts { pub deleted: usize, } +/// The albums' counts as the sidebar shows them ([`Caches::album_counts`]). +pub(crate) struct AlbumCounts { + /// The library they are of ([`lightcraft_engine::Session::library_generation`]). + library: u64, + /// The minute they are of while a smart album asks about "the last N days" (else empty). + minute: String, + /// What follows edits to a photo or a few. + tally: lightcraft_catalog::tally::AlbumTally, + /// The counts as the panels take them. + shown: std::sync::Arc>, +} + +/// A count of every photo on a worker thread ([`Caches::album_counts`]). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) struct AlbumRecount { + /// The library, minute and catalog revision it counts. + library: u64, + minute: String, + revision: u64, + /// The count, sent before the repaint is asked for, so the frame it wakes finds it. + done: std::sync::mpsc::Receiver>, + /// The thread, until it has let go of its copy of the catalog. + worker: std::thread::JoinHandle<()>, +} + /// The values the filter bar's pickers offer. #[derive(Clone, Debug, Default)] pub struct FilterValues { @@ -42,6 +67,9 @@ const READS_FILE: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRE const READS_META: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::META); +/// The keyword tree: the keywords photos carry, and the keyword list's own. +const READS_KEYWORDS: lightcraft_catalog::Aspects = READS_META.with(lightcraft_catalog::Aspects::KEYWORD_LIST); + const READS_PEOPLE: lightcraft_catalog::Aspects = READS_META.with(lightcraft_catalog::Aspects::ANALYSIS); const READS_CAPTURED: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::CAPTURED); @@ -62,7 +90,7 @@ impl Caches { } /// The library's keyword tree. pub fn keyword_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - let kept = self.keyword_tree.take().filter(|(r, _)| still_right(cat, *r, READS_META)).map(|(_, t)| t); + let kept = self.keyword_tree.take().filter(|(r, _)| still_right(cat, *r, READS_KEYWORDS)).map(|(_, t)| t); let t = kept.unwrap_or_else(|| std::sync::Arc::new(cat.keyword_tree())); self.keyword_tree = Some((cat.revision, t.clone())); t @@ -327,22 +355,31 @@ impl Caches { v } + /// How many photos each album of the library `library` ([`lightcraft_engine::Session::library_generation`]) + /// shows, `now` being the session clock ("in the last…" rules count back from it). + /// + /// An edit to a photo or a few is followed at once: a smart album asks only those photos again (a keyword + /// created and given to them too: the keyword list itself counts in no album). Anything more (an album's rules + /// or photos changed, a stack, an edit to many photos such as a keyword renamed across them, a new minute while + /// a smart album asks about "the last N days", another library) counts every photo again, seconds in a large + /// library. That count runs on a worker thread (natively) while the counts shown before stay (none the first + /// time, and none of another library); `ctx` repaints when it is done, and edits made meanwhile are followed + /// from it. pub fn album_counts( &mut self, cat: &lightcraft_catalog::Catalog, + library: u64, now: &str, + ctx: &egui::Context, ) -> std::sync::Arc> { - let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); - let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; - // the counts of this minute, if there are any: an edit to a photo or a few is followed from them, a smart - // album asking only those photos again; anything more, or a new minute, is counted from every photo - let kept = self.album_counts.take().filter(|(of, _, _)| of == minute); - if let Some((_, tally, shown)) = &kept - && tally.revision() == cat.revision - { - let shown = shown.clone(); - self.album_counts = kept; - return shown; + let (relative, minute) = Self::album_clock(cat, now); + self.collect_album_recount(library); + // (album ids start again in every library: another one's counts would be shown on this one's albums) + if self.album_counts.as_ref().is_some_and(|c| c.library != library) { + self.album_counts = None; + } + if let Some(counts) = self.album_counts.as_ref().filter(|c| c.minute == minute && c.tally.revision() == cat.revision) { + return counts.shown.clone(); } if relative { // "in the last N days" counts back from the session clock, as in the grid. (Within a minute an edit asks @@ -350,21 +387,119 @@ impl Caches { // far out as the counts already were between edits, and the next minute counts them all again.) lightcraft_catalog::rules::set_now(Some(now.to_string())); } - let tally = match kept { - Some((_, mut tally, _)) => { - if !tally.update(cat) { - self.album_count_scans += 1; + if let Some(counts) = self.album_counts.as_mut().filter(|c| c.minute == minute) + && counts.tally.update(cat) + { + counts.shown = std::sync::Arc::new(counts.tally.counts().clone()); + return counts.shown.clone(); + } + self.recount_albums(cat, library, minute, now, relative, ctx); + self.album_counts.as_ref().map(|c| c.shown.clone()).unwrap_or_default() + } + + /// Whether a smart album asks about "the last N days", and the minute the counts are of then (else empty). + fn album_clock<'a>(cat: &lightcraft_catalog::Catalog, now: &'a str) -> (bool, &'a str) { + let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); + (relative, if relative { now.get(..16).unwrap_or(now) } else { "" }) + } + + /// [`Caches::album_counts`] for the `albums.list` command, with how far they are from the catalog and the clock as + /// they are now: the command answers at once from them (marking the albums that are behind), and never counts a + /// photo on the UI thread. + pub fn album_counts_for_list( + &mut self, + cat: &lightcraft_catalog::Catalog, + library: u64, + now: &str, + ctx: &egui::Context, + ) -> (std::sync::Arc>, lightcraft_engine::CountsAge) { + use lightcraft_engine::CountsAge; + let counts = self.album_counts(cat, library, now, ctx); + let (_, minute) = Self::album_clock(cat, now); + let age = match self.album_counts.as_ref() { + Some(c) if c.library == library && c.tally.revision() == cat.revision => { + if c.minute == minute { + CountsAge::Current + } else { + CountsAge::ClockBehind } - tally } - None => { - self.album_count_scans += 1; - lightcraft_catalog::tally::AlbumTally::of(cat) + _ => CountsAge::Behind, + }; + (counts, age) + } + + /// A count of every photo is running ([`Caches::album_counts`]). + pub fn album_recount_running(&self) -> bool { + self.album_recount.as_ref().is_some_and(|job| !job.worker.is_finished()) + } + + /// Count every photo for [`Caches::album_counts`]: on a worker thread when one can be started, else here. + fn recount_albums(&mut self, cat: &lightcraft_catalog::Catalog, library: u64, minute: &str, now: &str, relative: bool, ctx: &egui::Context) { + // one at a time: what it finds is followed up to the catalog as it is by then, or counted again + let failed = self.album_recount_failed.as_ref().is_some_and(|(l, r, m)| *l == library && *r == cat.revision && m == minute); + if self.album_recount.is_some() || failed { + return; + } + self.album_count_scans += 1; + #[cfg(not(target_arch = "wasm32"))] + { + // (cheap: the copy shares the photos) + let (copy, ctx, now) = (cat.clone(), ctx.clone(), relative.then(|| now.to_string())); + let (tx, done) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new().name("lc-album-counts".into()).spawn(move || { + let counted = lightcraft_engine::guard::catch("Counting the albums' photos", || { + lightcraft_catalog::rules::set_now(now); + lightcraft_catalog::tally::AlbumTally::of(©) + }); + let _ = tx.send(counted); + ctx.request_repaint(); + }); + match spawned { + Ok(worker) => { + self.album_recount = Some(AlbumRecount { library, minute: minute.to_string(), revision: cat.revision, done, worker }); + return; + } + Err(e) => log::warn!("album counts: can't start a thread ({e}); counting them here"), + } + } + #[cfg(target_arch = "wasm32")] + let _ = (now, relative, ctx); + // (`album_counts` has set the clock on this thread) + let counted = lightcraft_engine::guard::catch("Counting the albums' photos", || lightcraft_catalog::tally::AlbumTally::of(cat)); + self.finish_album_recount(library, cat.revision, minute.to_string(), counted); + } + + /// Take the worker's count once it is done; a count of another library is let go (its thread ends on its own). + fn collect_album_recount(&mut self, library: u64) { + let Some(job) = &self.album_recount else { return }; + if job.library != library { + self.album_recount = None; + return; + } + let counted = match job.done.try_recv() { + Ok(counted) => counted, + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + log::error!("album counts: the count stopped without an answer"); + Err("stopped without an answer".to_string()) } }; - let shown = std::sync::Arc::new(tally.counts().clone()); - self.album_counts = Some((minute.to_string(), tally, shown.clone())); - shown + let Some(job) = self.album_recount.take() else { return }; + self.finish_album_recount(job.library, job.revision, job.minute, counted); + } + + /// The counts a count of every photo made are the ones shown. One that failed (already logged) leaves those + /// shown before, and isn't tried again for the same library, catalog and minute. + fn finish_album_recount(&mut self, library: u64, revision: u64, minute: String, counted: Result) { + match counted { + Ok(tally) => { + self.album_recount_failed = None; + let shown = std::sync::Arc::new(tally.counts().clone()); + self.album_counts = Some(AlbumCounts { library, minute, tally, shown }); + } + Err(_) => self.album_recount_failed = Some((library, revision, minute)), + } } } @@ -386,6 +521,27 @@ mod cache_tests { Op::AddAlbum { album: a } } + type Counts = std::sync::Arc>; + + /// [`super::Caches::album_counts`] of library `library` once a count of every photo it started is done and + /// taken. + fn counted_in(c: &mut super::Caches, cat: &Catalog, library: u64, now: &str) -> Counts { + let ctx = egui::Context::default(); + let t0 = std::time::Instant::now(); + loop { + let shown = c.album_counts(cat, library, now, &ctx); + if c.album_recount.is_none() { + return shown; + } + assert!(t0.elapsed() < std::time::Duration::from_secs(30), "the count is done"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + + fn counted(c: &mut super::Caches, cat: &Catalog, now: &str) -> Counts { + counted_in(c, cat, 0, now) + } + /// Smart-album counts: unchanged frames reuse them; metadata and rule changes and (for /// "in the last…" rules) the clock crossing into a new minute recompute them. #[test] @@ -398,23 +554,23 @@ mod cache_tests { cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); cat.apply(smart(11, serde_json::json!({"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}))).unwrap(); let now = "2026-09-30T12:00:00"; - let n = c.album_counts(&cat, now); + let n = counted(&mut c, &cat, now); assert_eq!((n[&AlbumId(10)], n[&AlbumId(11)]), (1, 1)); assert_eq!(c.album_count_scans, 1); for _ in 0..10 { - c.album_counts(&cat, "2026-09-30T12:00:40"); + counted(&mut c, &cat, "2026-09-30T12:00:40"); } assert_eq!(c.album_count_scans, 1, "unchanged frames in the same minute don't rescan"); // a photo rated: followed from that photo, not counted from every one cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); - assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 2); + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 2); assert_eq!(c.album_count_scans, 1); // rule change let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 5}]})).unwrap(); cat.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); - assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 1); + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 1); // an hour later the 11:59:30 photo has left "in the last hour", with no catalog change - assert_eq!(c.album_counts(&cat, "2026-09-30T13:00:10")[&AlbumId(11)], 0); + assert_eq!(counted(&mut c, &cat, "2026-09-30T13:00:10")[&AlbumId(11)], 0); assert_eq!(c.album_count_scans, 3, "new rules and a new minute are counted from every photo; the rating was not"); lightcraft_catalog::rules::set_now(None); } @@ -462,8 +618,69 @@ mod cache_tests { let mut c = super::Caches::default(); cat.apply(photo(1, "2026-09-30T11:59:30", 5)).unwrap(); cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); - c.album_counts(&cat, "2026-09-30T12:00:00"); - c.album_counts(&cat, "2027-01-01T00:00:00"); + counted(&mut c, &cat, "2026-09-30T12:00:00"); + counted(&mut c, &cat, "2027-01-01T00:00:00"); assert_eq!(c.album_count_scans, 1); } + + /// Counting every photo again (an album's rules changed, an edit to many photos) takes seconds in a large + /// library: it runs off the UI thread, and the sidebar keeps the counts it showed until the new ones are ready. + #[test] + fn a_count_of_every_photo_runs_in_the_background_and_the_counts_shown_stay_meanwhile() { + let mut cat = Catalog::default(); + let mut c = super::Caches::default(); + for i in 0..3u64 { + cat.apply(photo(i + 1, "2026-09-30T11:00:00", if i == 0 { 5 } else { 1 })).unwrap(); + } + cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); + let now = "2026-09-30T12:00:00"; + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 1); + // new rules: every photo is asked again + let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})).unwrap(); + cat.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); + let ctx = egui::Context::default(); + assert_eq!(c.album_counts(&cat, 0, now, &ctx)[&AlbumId(10)], 1, "the frame after the change shows the counts it had"); + assert!(c.album_recount.is_some(), "and every photo is counted elsewhere"); + // done counting is said whether or not a frame has taken the count yet (a folded Albums section takes none) + let t0 = std::time::Instant::now(); + while c.album_recount_running() { + assert!(t0.elapsed() < std::time::Duration::from_secs(30), "the count ends"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + // a photo rated meanwhile: followed from what the count finds + cat.apply(Op::SetRating { id: PhotoId(3), rating: 0 }).unwrap(); + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 2, "three photos rated at least 1, then one not"); + assert_eq!(c.album_count_scans, 2, "counted whole once for the new rules; the rating was followed"); + // the first time there is nothing to show yet: no count, rather than a wrong one + let mut fresh = super::Caches::default(); + assert!(fresh.album_counts(&cat, 0, now, &ctx).get(&AlbumId(10)).is_none()); + assert_eq!(counted(&mut fresh, &cat, now)[&AlbumId(10)], 2); + } + + /// Album ids start again in every library: once another library is open, the albums of the one before never + /// lend it their counts, nor does a count of that library still running when it closed. + #[test] + fn another_library_never_shows_the_counts_of_the_one_before() { + let library = |rated: &[u8]| { + let mut cat = Catalog::default(); + for (i, r) in rated.iter().enumerate() { + cat.apply(photo(i as u64 + 1, "2026-09-30T11:00:00", *r)).unwrap(); + } + cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); + cat + }; + let (mut first, second) = (library(&[5, 1, 1]), library(&[5, 5, 1])); + let (mut c, ctx, now) = (super::Caches::default(), egui::Context::default(), "2026-09-30T12:00:00"); + assert_eq!(counted_in(&mut c, &first, 1, now)[&AlbumId(10)], 1); + assert!(c.album_counts(&second, 2, now, &ctx).get(&AlbumId(10)).is_none(), "nothing until its own are counted"); + assert_eq!(counted_in(&mut c, &second, 2, now)[&AlbumId(10)], 2); + // a count of the first library under way when the second opens is let go + let mut c = super::Caches::default(); + assert_eq!(counted_in(&mut c, &first, 1, now)[&AlbumId(10)], 1); + let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})).unwrap(); + first.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); + assert_eq!(c.album_counts(&first, 1, now, &ctx)[&AlbumId(10)], 1); + assert!(c.album_recount.is_some(), "the first library is being counted"); + assert_eq!(counted_in(&mut c, &second, 2, now)[&AlbumId(10)], 2, "the second library's own count"); + } } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index caacbc59088..449e6c42e9e 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -318,6 +318,22 @@ pub(crate) fn widget_target_visible(ctx: &egui::Context, hit: Option Result { + if id != "albums.list" { + return app.run(id, params); + } + let now = (app.session.clock)(); + let (counts, age) = app.caches.album_counts_for_list(&app.session.catalog, app.session.library_generation(), &now, ctx); + app.session.offer_album_counts(counts, age); + let r = app.run(id, params); + app.session.withdraw_album_counts(); + r +} + /// Dispatch one control request: run engine commands, list menus/widgets, inspect state, queue /// file drops and synthetic input, capture screenshots, or return an error for an unknown or /// invalid request. Requests that need fresh widget geometry are queued as `Outcome` values. @@ -329,7 +345,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest "engine.execute" | "ui.menu.invoke" | "command" => { let Some(id) = s("command").or(s("id")) else { return err("missing `command`") }; let params = p.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({})); - let r = app.run(id, params); + let r = run_command(app, ctx, id, params); ctx.request_repaint(); wrap(r) } diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index ab49563cbb8..3e122129b14 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -388,11 +388,12 @@ impl Headless { } } - /// Is anything still in progress (renders, file-system checks the sidebar waits for, queued - /// input)? + /// Is anything still in progress (renders, file-system checks the sidebar waits for, the albums' counts, + /// queued input)? pub fn busy(&self) -> bool { self.app.renderer.in_flight() > 0 || crate::panels::left::fs_cached_running(&self.view.ctx) > 0 + || self.app.caches.album_recount_running() || self.app.merge.busy() || self.app.scan.is_some() || self.app.sync.is_some() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9db7035c1d0..8a5528f332a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -78,6 +78,7 @@ mod services; #[cfg(test)] use app::{import_tick_allowed, sam_download_ended, shot_ready}; pub(crate) use caches::key_of; +use caches::{AlbumCounts, AlbumRecount}; pub use caches::{FilterValues, LibraryCounts, RulesView}; use clock::AppClock; pub use clock::{monotonic_ms, now_ms}; @@ -570,10 +571,12 @@ pub struct Caches { counts: Option<(u64, LibraryCounts)>, date_groups: Option<(u64, std::sync::Arc>)>, filter_values: Option<(u64, std::sync::Arc)>, - /// The albums' counts: the minute they are of (while a smart album asks about "the last N days"), the tally - /// that follows edits, and the counts as the panels take them. - album_counts: - Option<(String, lightcraft_catalog::tally::AlbumTally, std::sync::Arc>)>, + /// The albums' counts as the sidebar shows them, with the tally that follows edits. + album_counts: Option, + /// A count of every photo running off the UI thread; the counts above are shown until it is done. + album_recount: Option, + /// The library, catalog revision and minute a count of every photo failed at: not tried again until one changes. + album_recount_failed: Option<(u64, u64, String)>, /// How often the album counts were made from every photo (tests check that unchanged frames, and edits to a /// photo or a few, don't). pub album_count_scans: usize, diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index 92498eb0233..99a1f115368 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -34,8 +34,14 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare open = true; set_tree_open(ui, open_id, true); } - let resp = Row::new(&format!("folder:{}", a.id.0), Icon::Folder, &a.name).indent(indent).sense(Sense::click_and_drag()).show(app, ui); - // a folder is no source, so its row folds it too; the triangle is the same click, aimed + // a folder is a source: the photos of the albums inside it, each once (no count shown on its row, for a + // number the albums already give; `albums.list` counts it from theirs, kept with theirs) + let sel = app.session.source == LibrarySource::Album(a.id); + let resp = Row::new(&format!("folder:{}", a.id.0), Icon::Folder, &a.name) + .selected(sel) + .indent(indent) + .sense(Sense::click_and_drag()) + .show(app, ui); let has_children = all.get(&Some(a.id)).is_some_and(|v| !v.is_empty()); if resp.drag_started() { app.ui.dragging_album = Some(a.id.0); @@ -45,16 +51,15 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare } // what this frame draws; a click shows from the next one let draw_open = open; - let mut toggled = false; if has_children { + // only the triangle folds it; it sits on the row and takes its clicks, so the + // menu opens from it too let tri = tree_toggle(ui, &resp, indent, open_id, &mut open, format!("albumToggle:{}", a.id.0)); - toggled = tri.clicked(); - // the triangle sits on the row and takes its clicks: the menu opens from it too folder_menu(app, &tri, a); } - // one click, one toggle: the triangle's is not the row's as well - if resp.clicked() && !toggled { - set_tree_open(ui, open_id, !open); + // the row itself is the source: the photos of the albums inside the folder + if resp.clicked() { + let _ = app.run("library.source", json!({"kind": "album", "id": a.id.0})); } folder_menu(app, &resp, a); if draw_open { @@ -63,9 +68,9 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare } else { let sel = app.session.source == LibrarySource::Album(a.id); let icon = if a.is_smart() { Icon::SmartAlbum } else { Icon::Album }; - // cached: a smart album's count scans the catalog + // cached: a smart album's count scans the catalog (in the background: no number until it is known) let now = (app.session.clock)(); - let n = app.caches.album_counts(&app.session.catalog, &now).get(&a.id).copied().unwrap_or(0); + let n = app.caches.album_counts(&app.session.catalog, app.session.library_generation(), &now, ui.ctx()).get(&a.id).copied(); // the album B adds to is marked "+" let target = app.session.target_album.filter(|t| app.session.catalog.album(*t).is_some()).or_else(|| app.session.catalog.quick_collection()); @@ -74,7 +79,7 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare let problems = app.caches.smart_album_problems(&app.session.catalog).get(&a.id).cloned().unwrap_or_default(); let label = if problems.is_empty() { label } else { format!("⚠ {label}") }; let mut resp = Row::new(&format!("album:{}", a.id.0), icon, &label) - .count(Some(n)) + .count(n) .selected(sel) .indent(indent) .sense(Sense::click_and_drag()) @@ -179,12 +184,19 @@ pub(super) const MARK_W: f32 = 12.0; const HOVER_OPEN_SECS: f64 = 0.6; /// Whether the album `dragged` may be dropped into the folder `target` (`None`: the top level): -/// a folder other than where it already is, and not itself or something inside it. +/// a folder other than where it already is, not itself or something inside it, and not one a +/// smart album that moves with it shows (it would include itself). fn can_drop_album(app: &LightcraftApp, dragged: AlbumId, target: Option) -> bool { - let Some(d) = app.session.catalog.album(dragged) else { return false }; + let cat = &app.session.catalog; + let Some(d) = cat.album(dragged) else { return false }; match target { None => d.parent.is_some(), - Some(t) => app.session.catalog.album(t).is_some_and(|f| f.folder) && d.parent != Some(t) && !is_within(app, t, dragged), + Some(t) => { + cat.album(t).is_some_and(|f| f.folder) + && d.parent != Some(t) + && !is_within(app, t, dragged) + && cat.album_move_would_loop(dragged, t).is_none() + } } } diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index 20c1bbce130..a58cabaa637 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -223,9 +223,14 @@ pub(super) fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Al }); ui.separator(); } - // move into another folder (not into itself or one of its own subfolders) - let mut folders: Vec<(u64, String)> = - app.session.catalog.albums().filter(|f| f.folder && !is_within(app, f.id, a.id)).map(|f| (f.id.0, f.name.clone())).collect(); + // move into another folder (not into itself or one of its own subfolders, nor into one + // a smart album that moves with it shows) + let cat = &app.session.catalog; + let mut folders: Vec<(u64, String)> = cat + .albums() + .filter(|f| f.folder && !is_within(app, f.id, a.id) && cat.album_move_would_loop(a.id, f.id).is_none()) + .map(|f| (f.id.0, f.name.clone())) + .collect(); folders.sort_by_key(|(_, n)| n.to_lowercase()); crate::widgets::menu_button(ui, crate::i18n::tr("Move to"), |ui| { if ui.add_enabled(a.parent.is_some(), egui::Button::new(crate::i18n::tr("Top Level"))).clicked() { @@ -233,7 +238,10 @@ pub(super) fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Al } for (fid, name) in &folders { if ui.add_enabled(a.parent.map(|p| p.0) != Some(*fid), egui::Button::new(name)).clicked() { - let _ = app.run("album.move", json!({"id": a.id.0, "parent": fid})); + // refused for a smart album that would then include itself: say so + if let Err(e) = app.run("album.move", json!({"id": a.id.0, "parent": fid})) { + app.toast(ui.ctx(), e); + } } } }); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 3a102a29a90..b4be41656c3 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -1,4 +1,5 @@ mod activity; +mod album_list; mod album_picker; mod album_remove; mod appearance; diff --git a/crates/ui-egui/src/tests/album_list.rs b/crates/ui-egui/src/tests/album_list.rs new file mode 100644 index 00000000000..c47e7d43110 --- /dev/null +++ b/crates/ui-egui/src/tests/album_list.rs @@ -0,0 +1,258 @@ +//! `albums.list` answers at once from the counts the sidebar keeps: it never counts a smart album's photos on the UI +//! thread (in a large library that is seconds in which the window doesn't answer). A count that isn't of the catalog +//! as it is now is listed as pending (`countPending`), and the ones the sidebar follows through small edits are current +//! at once. + +use std::time::{Duration, Instant}; + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::control::{ControlRequest, Outcome}; +use crate::{LightcraftApp, Services}; + +/// A library of `photos` photos rated 0 to 5 in turn, and no frame drawn: nothing has counted its albums yet. +fn app(photos: u64) -> LightcraftApp { + let mut session = lightcraft_engine::Session::new(); + for i in 1..=photos { + let mut p = Photo::new(PhotoId(i), Source::Demo { scene: 0 }, &format!("p{i}.jpg"), "JPEG", 60, 40, "2026-01-01T00:00:00"); + p.rating = (i % 6) as u8; + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + LightcraftApp::new(session, Services { png: None, ..Default::default() }) +} + +/// `albums.list` as the control channel runs it. +fn list(app: &mut LightcraftApp, ctx: &egui::Context) -> Vec { + let (req, _) = ControlRequest::new("engine.execute", json!({"command": "albums.list"})); + let Outcome::Done(reply) = crate::control::handle(app, ctx, &req) else { panic!("expected a reply") }; + assert_eq!(reply["ok"], true, "{reply}"); + reply["result"].as_array().unwrap().clone() +} + +fn run(app: &mut LightcraftApp, command: &str, params: Value) -> Value { + app.run(command, params).unwrap_or_else(|e| panic!("{command}: {e}")) +} + +fn album(listed: &[Value], id: u64) -> &Value { + listed.iter().find(|a| a["id"] == id).unwrap_or_else(|| panic!("no album {id} in {listed:?}")) +} + +/// Ask again until the smart album `id` is no longer pending (its count of every photo is done and taken). +fn settled(app: &mut LightcraftApp, ctx: &egui::Context, id: u64) -> Vec { + let t0 = Instant::now(); + loop { + let listed = list(app, ctx); + if album(&listed, id)["countPending"] == false { + return listed; + } + assert!(t0.elapsed() < Duration::from_secs(60), "the count of every photo ends"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +fn smart(app: &mut LightcraftApp, name: &str, rules: Value) -> u64 { + run(app, "album.createSmart", json!({"name": name, "rules": rules}))["id"].as_u64().unwrap() +} + +fn count_of(app: &LightcraftApp, id: u64) -> u64 { + app.session.catalog.album_count(AlbumId(id)) as u64 +} + +/// The first answer lists every album without counting the smart albums' photos (they are pending, and counted on a +/// worker); an album of chosen photos is exact at once; the next answers are current, and no photo is counted again. +#[test] +fn the_albums_are_listed_at_once_with_the_smart_albums_counts_pending_until_counted() { + let mut app = app(3000); + let ctx = egui::Context::default(); + let four = smart(&mut app, "Four stars or more", json!({"rating": 4})); + let five = smart(&mut app, "Five stars", json!({"rating": 5})); + let picked = run(&mut app, "album.create", json!({"name": "Picked", "addSelected": false}))["id"].as_u64().unwrap(); + run(&mut app, "library.select", json!({"ids": [1, 2, 3]})); + run(&mut app, "album.addPhotos", json!({"id": picked, "ids": [1, 2, 3]})); + assert_eq!(app.caches.album_count_scans, 0, "nothing counted yet"); + + let first = list(&mut app, &ctx); + for id in [four, five] { + assert_eq!(album(&first, id)["countPending"], true, "a smart album's count isn't known at the first answer: {first:?}"); + assert_eq!(album(&first, id)["count"], 0, "no count of an earlier catalog to show"); + } + assert_eq!(album(&first, picked)["count"], 3, "an album of chosen photos is counted from its list"); + assert!(album(&first, picked).get("countPending").is_none(), "it has nothing to wait for"); + assert_eq!(app.caches.album_count_scans, 1, "every photo is being counted, once, elsewhere"); + + let settled = settled(&mut app, &ctx, four); + assert_eq!(album(&settled, four)["count"], count_of(&app, four)); + assert_eq!(album(&settled, five)["count"], count_of(&app, five)); + assert_eq!(album(&settled, five)["countPending"], false); + assert_eq!(app.caches.album_count_scans, 1, "the answers since counted nothing"); +} + +/// An edit to a photo is followed from the counts kept, so the answer is current at once; new rules count every photo +/// again on the worker, and until that is done the answer lists the count it had, pending. +#[test] +fn an_edit_to_a_photo_is_followed_and_new_rules_leave_the_old_count_pending() { + let mut app = app(3000); + let ctx = egui::Context::default(); + let four = smart(&mut app, "Four stars or more", json!({"rating": 4})); + list(&mut app, &ctx); + let before = album(&settled(&mut app, &ctx, four), four)["count"].as_u64().unwrap(); + assert_eq!(before, count_of(&app, four)); + + // a photo rated 5: one more + run(&mut app, "library.select", json!({"ids": [2]})); + run(&mut app, "photo.rate", json!({"ids": [2], "rating": 5})); + let after = list(&mut app, &ctx); + assert_eq!(album(&after, four)["countPending"], false, "a small edit is followed at once"); + assert_eq!(album(&after, four)["count"].as_u64().unwrap(), before + 1); + assert_eq!(app.caches.album_count_scans, 1, "without counting every photo again"); + + // new rules: the count shown stays the one before until the new one is made + run(&mut app, "album.setRules", json!({"id": four, "rules": {"rating": 5}})); + let changed = list(&mut app, &ctx); + assert_eq!(album(&changed, four)["countPending"], true, "{changed:?}"); + assert_eq!(album(&changed, four)["count"].as_u64().unwrap(), before + 1, "the count of the rules before"); + let done = settled(&mut app, &ctx, four); + assert_eq!(album(&done, four)["count"], count_of(&app, four)); + assert_eq!(app.caches.album_count_scans, 2, "every photo was counted again, for the new rules only"); +} + +/// A new minute puts only the albums whose rules ask about "the last N days" behind (the catalog didn't change, so the +/// other counts are exact), and they are counted again on the worker like any other count behind. +#[test] +fn a_new_minute_leaves_only_the_albums_asking_about_the_last_hour_pending() { + let mut app = app(300); + let ctx = egui::Context::default(); + let clock_at = |app: &mut LightcraftApp, now: &'static str| app.session.clock = Box::new(move || now.to_string()); + clock_at(&mut app, "2026-09-30T12:00:00"); + let four = smart(&mut app, "Four stars or more", json!({"rating": 4})); + let rules = json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}}); + let recent = smart(&mut app, "Recent", rules); + list(&mut app, &ctx); + let first = settled(&mut app, &ctx, recent); + assert_eq!((album(&first, four)["countPending"].as_bool(), album(&first, recent)["countPending"].as_bool()), (Some(false), Some(false))); + assert_eq!(app.caches.album_count_scans, 1); + + clock_at(&mut app, "2026-09-30T12:01:10"); + let later = list(&mut app, &ctx); + assert_eq!(album(&later, four)["countPending"], false, "no rule of it asks about the clock: {later:?}"); + assert_eq!(album(&later, recent)["countPending"], true, "its count is of the minute before: {later:?}"); + let done = settled(&mut app, &ctx, recent); + assert_eq!(album(&done, recent)["count"], count_of(&app, recent)); + assert_eq!(app.caches.album_count_scans, 2, "every photo was counted again for the new minute"); + lightcraft_catalog::rules::set_now(None); +} + +/// In a large library with many smart albums the answer comes in a fraction of the time it takes to count the albums +/// once (what it did, on the UI thread, before). +#[test] +fn listing_the_albums_of_a_large_library_takes_a_fraction_of_counting_them() { + let mut app = app(60_000); + let ctx = egui::Context::default(); + for i in 0..12 { + smart(&mut app, &format!("Rated {i}"), json!({"rating": i % 5 + 1})); + } + let counted = Instant::now(); + let tally = lightcraft_catalog::tally::AlbumTally::of(&app.session.catalog); + let counting = counted.elapsed(); + assert_eq!(tally.counts().len(), 12); + + let listed = Instant::now(); + let first = list(&mut app, &ctx); + let listing = listed.elapsed(); + assert!(first.iter().all(|a| a["countPending"] == true), "{first:?}"); + assert!(listing < counting / 2, "listing took {listing:?}, counting every album once takes {counting:?}"); +} + +fn folder(app: &mut LightcraftApp, name: &str, parent: Option) -> u64 { + run(app, "album.create", json!({"name": name, "folder": true, "parent": parent}))["id"].as_u64().unwrap() +} + +fn smart_in(app: &mut LightcraftApp, name: &str, rules: Value, parent: u64) -> u64 { + run(app, "album.createSmart", json!({"name": name, "rules": rules, "parent": parent}))["id"].as_u64().unwrap() +} + +/// A folder of albums holds the photos of the albums inside it, which would be a pass over the library of its own to +/// count: its count is made with the others on the worker (from theirs), listed pending until then, and followed +/// through an edit to a photo at once. +#[test] +fn a_folders_count_comes_from_the_counts_kept_and_is_pending_with_them() { + let mut app = app(3000); + let ctx = egui::Context::default(); + let trips = folder(&mut app, "Trips", None); + let rome = folder(&mut app, "Rome", Some(trips)); + let four = smart_in(&mut app, "Four stars or more", json!({"rating": 4}), trips); + let five = smart_in(&mut app, "Five stars", json!({"rating": 5}), rome); + run(&mut app, "library.select", json!({"ids": [1, 2, 3]})); + let picked = run(&mut app, "album.create", json!({"name": "Picked", "addSelected": true, "parent": rome}))["id"].as_u64().unwrap(); + let empty = folder(&mut app, "Nothing", None); + assert_eq!(app.caches.album_count_scans, 0, "nothing counted yet"); + + let first = list(&mut app, &ctx); + for id in [trips, empty] { + assert_eq!(album(&first, id)["countPending"], true, "a folder's count waits for the others': {first:?}"); + assert_eq!(album(&first, id)["count"], 0, "no count of an earlier catalog to show"); + } + assert_eq!(app.caches.album_count_scans, 1, "every photo is being counted, once, elsewhere"); + + let done = settled(&mut app, &ctx, trips); + for id in [trips, rome, four, five, picked, empty] { + let found = find_anywhere(&done, id); + assert_eq!(found["count"], count_of(&app, id), "album {id}: {found}"); + } + assert!(count_of(&app, trips) > count_of(&app, four), "the folder holds more than one album of it"); + assert_eq!(count_of(&app, empty), 0); + assert_eq!(app.caches.album_count_scans, 1); + + // a photo outside "Picked" rated 5: it enters the smart albums, so the folders around them are followed from that + // photo, with no pass over the library + let before = count_of(&app, trips); + run(&mut app, "library.select", json!({"ids": [6]})); + run(&mut app, "photo.rate", json!({"ids": [6], "rating": 5})); + assert_eq!(count_of(&app, trips), before + 1, "the photo is in the folder now"); + let after = list(&mut app, &ctx); + for id in [trips, rome, four, five] { + let found = find_anywhere(&after, id); + assert_eq!(found["count"], count_of(&app, id), "album {id} after the edit"); + } + assert_eq!(find_anywhere(&after, trips)["countPending"], false); + assert_eq!(app.caches.album_count_scans, 1); +} + +/// The album with `id`, in the tree `listed` however deep. +fn find_anywhere(listed: &[Value], id: u64) -> Value { + for a in listed { + if a["id"] == id { + return a.clone(); + } + let kids = a["children"].as_array().cloned().unwrap_or_default(); + let inside = find_anywhere(&kids, id); + if !inside.is_null() { + return inside; + } + } + Value::Null +} + +/// Folders in a large library cost no pass over it each: listed in a fraction of the time one count of every album takes. +#[test] +fn listing_the_folders_of_a_large_library_takes_a_fraction_of_counting_them() { + let mut app = app(60_000); + let ctx = egui::Context::default(); + for f in 0..6 { + let parent = folder(&mut app, &format!("Folder {f}"), None); + for i in 0..2 { + smart_in(&mut app, &format!("Rated {f}.{i}"), json!({"rating": (f + i) % 5 + 1}), parent); + } + } + let counted = Instant::now(); + let tally = lightcraft_catalog::tally::AlbumTally::of(&app.session.catalog); + let counting = counted.elapsed(); + assert_eq!(tally.counts().len(), 18); + + let listed = Instant::now(); + let first = list(&mut app, &ctx); + let listing = listed.elapsed(); + assert!(first.iter().all(|a| a["countPending"] == true), "{first:?}"); + assert!(listing < counting / 2, "listing took {listing:?}, counting every album once takes {counting:?}"); +} diff --git a/crates/ui-egui/src/tests/panels.rs b/crates/ui-egui/src/tests/panels.rs index 5208de9b76b..64976139139 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -999,6 +999,63 @@ fn section_chevrons_line_up_with_row_triangles() { } } +/// A folder of albums is a source (a collection set in Lightroom Classic): given a folder whose +/// albums share a photo, when its row is clicked, then the grid shows their photos once each +/// under the folder's name, and the row stays open; only the triangle folds it. A folder with +/// nothing in it can be shown too, and shows nothing. +#[test] +fn clicking_an_album_folder_shows_the_photos_of_its_albums() { + use lightcraft_catalog::AlbumId; + use lightcraft_engine::LibrarySource; + let mut h = demo([1400.0, 900.0], json!({"view": "photoGrid", "leftPanel": true})); + let ids: Vec = h.app.session.visible_cloned().iter().take(4).map(|p| p.0).collect(); + let all = h.app.session.visible_cloned().len(); + let make = |h: &mut Headless, params: serde_json::Value| h.app.session.execute("album.create", ¶ms).unwrap()["id"].as_u64().unwrap(); + let trips = make(&mut h, json!({"name": "Trips", "folder": true})); + let rome = make(&mut h, json!({"name": "Rome", "parent": trips})); + let paris = make(&mut h, json!({"name": "Paris", "parent": trips})); + let empty = make(&mut h, json!({"name": "Empty", "folder": true})); + h.app.session.selection.ids = ids.iter().map(|i| lightcraft_catalog::PhotoId(*i)).collect(); + h.app.session.execute("album.addPhotos", &json!({"id": rome, "ids": [ids[0], ids[1]]})).unwrap(); + h.app.session.execute("album.addPhotos", &json!({"id": paris, "ids": [ids[1], ids[2]]})).unwrap(); + h.step(); + h.step(); + assert!(all > 3, "the demo library holds more than the folder will"); + // the triangle only folds: the grid still shows All Photos + click(&mut h, &format!("albumToggle:{trips}")); + assert!(!has(&h, &format!("source:album:{rome}")), "folded"); + assert_eq!(h.app.session.source, LibrarySource::All); + click(&mut h, &format!("albumToggle:{trips}")); + assert_eq!(h.app.session.source, LibrarySource::All); + // the row is the source; what is inside stays listed + click(&mut h, &format!("source:folder:{trips}")); + assert_eq!(h.app.session.source, LibrarySource::Album(AlbumId(trips))); + let mut shown: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + shown.sort_unstable(); + let mut want = ids[..3].to_vec(); + want.sort_unstable(); + assert_eq!(shown, want, "the shared photo once, the fourth photo not at all"); + assert_eq!(crate::i18n::source_title(&h.app.session), "Trips"); + assert!(has(&h, &format!("source:album:{rome}")) && has(&h, &format!("source:album:{paris}")), "a click doesn't fold it"); + // folded, it is still what the grid shows + click(&mut h, &format!("albumToggle:{trips}")); + assert!(!has(&h, &format!("source:album:{rome}")), "folded"); + assert_eq!(h.app.session.source, LibrarySource::Album(AlbumId(trips))); + assert_eq!(h.app.session.visible_cloned().len(), 3); + click(&mut h, &format!("albumToggle:{trips}")); + // an album inside is still its own source + click(&mut h, &format!("source:album:{rome}")); + assert_eq!(h.app.session.source, LibrarySource::Album(AlbumId(rome))); + assert_eq!(h.app.session.visible_cloned().len(), 2); + // a folder with nothing in it: no triangle, and nothing to show + click(&mut h, &format!("source:folder:{empty}")); + assert_eq!(h.app.session.source, LibrarySource::Album(AlbumId(empty))); + assert!(h.app.session.visible_cloned().is_empty()); + // and back + click(&mut h, &format!("source:folder:{trips}")); + assert_eq!(h.app.session.visible_cloned().len(), 3); +} + /// Albums nest in folders like the other sidebar trees: a folder row has a disclosure triangle /// (`albumToggle:`), plain albums have none, and folding a folder hides what is inside it. #[test] @@ -1221,6 +1278,28 @@ impl AlbumTree { } } +/// Given a smart album that shows a folder (its view, saved), when it is dragged onto that folder +/// or one inside it, then nothing happens (it would include itself, so the folder is no place to +/// drop it: no outline, no refusal to read); another folder takes it. +#[test] +fn a_smart_album_cant_be_dropped_on_the_folder_it_shows() { + let mut t = album_tree(); + t.h.app.session.execute("library.source", &json!({"kind": "album", "id": t.trips})).unwrap(); + let view = t.h.app.session.execute("album.createSmart", &json!({"name": "Trips view"})).unwrap()["id"].as_u64().unwrap(); + t.h.step(); + t.h.step(); + let steps = t.h.app.session.undo.len(); + for folder in [t.trips, t.sub] { + t.drag_row(view, folder); + assert_eq!(t.parent(view), None); + assert!(t.h.app.ui.toast.is_none(), "not a drop at all: {:?}", t.h.app.ui.toast); + assert!(t.h.app.ui.dragging_album.is_none(), "the drag ended"); + } + assert_eq!(t.h.app.session.undo.len(), steps); + t.drag_row(view, t.archive); + assert_eq!(t.parent(view), Some(t.archive)); +} + /// Given albums and folders in the sidebar, when an album or folder is dragged onto a folder, /// then it moves into it (as Move to does); onto a plain album, itself or something inside it, it /// stays where it was. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 36294c78756..2de991d3d38 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -98,6 +98,7 @@ filmstrip is visible. | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | | `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | | `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | +| `engine.execute {command: "albums.list"}` | — | The albums as a tree: `[{id, name, folder, count, cover, children}]`, a smart album also with `smart`, `rules`, `rulesText` and `problems`, and a smart album or a folder with `countPending`. It answers at once and counts no photo on the UI thread: an album of chosen photos is counted from its list, and the `count` of a smart album, or of a folder (the photos of the albums inside it, put together from their counts: no pass over the library of its own), is the one the sidebar keeps (counted on a worker thread, followed through edits to a photo or a few). `countPending: true` says that count isn't of the library as it is now yet: it is the count made before (0 when there is none) while the app counts every photo again (after new rules, an edit to many photos, or a library just opened; and, for an album whose rules ask about "the last N days" (its own, or those of an album it tests), or a folder with such an album inside, each time the clock moves into a new minute — the other albums stay exact then). Ask again a moment later: the album's `countPending` is `false` once its count is done. While a library has such an album and counting every photo takes longer than a minute, that album stays pending, and so does every smart album and folder after an edit made during the count; a count that failed (it is logged) stays pending until the library changes. The app answers this way (also to `lightcraft-cli snapshot --script`, where `ui.settle` first waits for the count); `lightcraft-cli run` without `--connect` and the headless MCP server have no window to keep up: they count every photo once, keep the counts and follow edits, so their answers are never pending | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | | `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes | | `engine.execute {command: "slideshow.overlays"}` | `{identityPlate?: {enabled?, text?, image?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, behind?}, ratingStars?: {enabled?, color?, size?, anchor?, …}, texts?: [{text?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, shadow?, shadowOpacity?, shadowOffset?, shadowRadius?, shadowAngle?}], addText?, removeText?, showWatermark?, watermark?}` (see `engine.commands`) | The overlays drawn on every slide, saved with the library: sizes and offsets are fractions of the slide's shorter side, anchors `topLeft`…`bottomRight` of the `slide` or the `photo`; text overlays expand tokens (`{caption}`, `{exposure}`, `{date}`, the file-naming tokens…; unknown tags show as typed); `watermark` takes the export watermark's keys. Replies with the settings and `warnings` | diff --git a/docs/mcp.md b/docs/mcp.md index 2c155e72c07..a5e3fcf378c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -232,6 +232,13 @@ sequence in a folder, or an AV1 video (no audio). It runs in the background and `cmd_slideshow_exportStatus` gives the result (`pages`, `files`, or `frames` / `samples` / `seconds` for video) or the error. With `wait: true` the call blocks and replies with the result. +`cmd_albums_list` lists the albums with their photo counts. Connected to the desktop app it answers at once from the +counts the sidebar keeps (a folder's count is made from the albums inside it), and a smart album or folder whose count +isn't of the library as it is now yet (it is being counted again after new rules, an edit to many photos or a library +just opened, or, for an album asking about "the last N days" itself or through an album it tests, or a folder with +one inside, a new minute) has `countPending: true` with the count made before (0 if none): ask again a moment later. +Headless, the counts are made on the first call, kept, and never pending. + ### Preview-only raws after an update A raw LightCraft couldn't decode when it was imported is shown from its embedded preview diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f60..9833aca0573 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-LIB-FOLDER: a folder's count in `albums.list` is put together from the counts of the albums inside it, kept with the sidebar's; LR-LIB-SMARTALBUM: `albums.list` answers at once from the counts the sidebar keeps and marks a smart album's count pending while every photo is counted again; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -95,8 +95,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-RECENT-ADDED | Recently added | P1 | ✅ | `cmd:library.source` (`recentlyAdded`), `crates/engine/src/view.rs` (`RECENT_DAYS`) | photos imported in the 30 days up to the latest import, newest import first, grouped by import day | | LR-LIB-BYDATE | Browse by date | P1 | ✅ | `cmd:library.filter` (`date`), `crates/ui-egui/src/panels/left.rs` (`date_row`), `crates/catalog/src/query.rs` (`date_groups`) | year → month → day tree with library-wide counts; a row filters the current source by that date. Active filters show as removable chips under the grid header (`crates/ui-egui/src/panels/chips.rs`, with “+N more” and Clear all), the header counts “N of M photos” (matching of the source's total), a badge on the top-bar filter icon counts them, and an empty result says no photos match the active filters | | LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests/albums_local.rs`, `crates/ui-egui/src/tests/panels.rs` | photos dragged from the grid onto an album row are added to it (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder) | -| LR-LIB-FOLDER | Folders of albums | P0 | ✅ | `cmd:album.create` (`folder`, `parent`), `cmd:album.move`, `cmd:album.reorder`, `cmd:album.sort`, `cmd:dialog.newAlbum` / `cmd:dialog.newFolder` / `cmd:dialog.smartAlbum` / `cmd:dialog.newSmartAlbum` (`parent`), `crates/ui-egui/src/panels/left.rs` (`albums_tree`, `folder_menu`, `disclosure_triangle`), `crates/ui-egui/src/tests/panels.rs` | Delete removes a folder and its nested albums as one undoable edit, keeps photos in the library and returns a deleted album view to All Photos (issue #501); folders nest and fold with the same disclosure triangle as Local / By Date / Folders / Keywords (`albumToggle:`; the row folds them too; open by default); right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder… creates inside it (the `dialog.new*` commands take `parent`), opening the folders down to the new row; creating is only allowed inside folders; moving: drag an album or folder row onto a folder (outlined when allowed; a closed folder opens after 0.6 s under the pointer; the "Albums" header takes an item that sits in a folder back to the top level while it is dragged), the Move to menu or `album.move` — one undo step each; not onto a plain album, itself or something inside it; drop on the top / bottom half of an album or the edge of a folder to place it there by hand (`cmd:album.reorder`, a line shows the place; ordered per folder, folders stay first, new albums go after the ordered ones; right-click ▸ Sort Contents A–Z or + ▸ Sort Albums A–Z = `cmd:album.sort`) | -| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | +| LR-LIB-FOLDER | Folders of albums | P0 | ✅ | `cmd:album.create` (`folder`, `parent`), `cmd:album.move`, `cmd:album.reorder`, `cmd:album.sort`, `cmd:dialog.newAlbum` / `cmd:dialog.newFolder` / `cmd:dialog.smartAlbum` / `cmd:dialog.newSmartAlbum` (`parent`), `cmd:library.source` (`album` with a folder's id), `crates/ui-egui/src/panels/left.rs` (`albums_tree`, `folder_menu`, `disclosure_triangle`), `crates/ui-egui/src/tests/panels.rs`, `crates/engine/src/tests/album_folder_source.rs`, `crates/catalog/src/tests_album_folder_photos.rs` | A folder is a source, as a collection set is in Lightroom Classic: clicking its row shows the photos of every album and smart album inside it, at any depth, each photo once, under the folder's name, with the sort and the filter bar on top (no count on the row; `albums.list` gives it to agents; Remove from Album and Set as Album Cover stay with the albums; a folder's view can be saved as a smart album, which follows the folder; inside that folder it would include itself, so `album.createSmart`, `album.move` and `album.reorder` refuse it there and say so, and the folder is no drop target for it; `album.setRules` with `replace` keeps the album or folder a saved view is limited to unless given `album: null`). Delete removes a folder and its nested albums as one undoable edit, keeps photos in the library and returns a deleted album view to All Photos (issue #501); folders nest and fold with the same disclosure triangle as Local / By Date / Folders / Keywords (`albumToggle:`; only the triangle folds them; open by default); right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder… creates inside it (the `dialog.new*` commands take `parent`), opening the folders down to the new row; creating is only allowed inside folders; moving: drag an album or folder row onto a folder (outlined when allowed; a closed folder opens after 0.6 s under the pointer; the "Albums" header takes an item that sits in a folder back to the top level while it is dragged), the Move to menu or `album.move` — one undo step each; not onto a plain album, itself or something inside it; drop on the top / bottom half of an album or the edge of a folder to place it there by hand (`cmd:album.reorder`, a line shows the place; ordered per folder, folders stay first, new albums go after the ordered ones; right-click ▸ Sort Contents A–Z or + ▸ Sort Albums A–Z = `cmd:album.sort`) | +| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; an edit to a few photos is followed photo by photo (a keyword created in the keyword list too: no rule reads the list), and a count of every photo (an album's rules or photos changed, a stack, an edit to more than 256 photos) runs on a worker thread while the sidebar keeps the counts it showed (none before the first count), so the window doesn't freeze; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | | LR-LIB-SHARED-ALBUM | Shared albums | P2 | ⬜ | | needs a sharing service | | LR-LIB-OFFLINE | Keep album offline | P2 | 🚫 | | not applicable: local-first library | | LR-LIB-TARGET | Target album | P2 | ✅ | `cmd:album.setTarget`, `cmd:album.toggleTarget` | see LRC-LIB-COLLECTIONS | @@ -959,3 +959,5 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-23 | patch | LR-BEHAV-ACCESS: the name field of New Album, New Smart Album, Rename and the other one-field dialogs takes the keyboard focus once when the dialog opens instead of every frame, so Tab and Shift+Tab reach the check box, Cancel and OK; status unchanged (🟡) | | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 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-30 | patch | LR-LIB-SMARTALBUM: `albums.list` answers at once from the counts the sidebar keeps (counted on a worker thread) instead of counting every smart album's photos on the UI thread, and marks a smart album's count `countPending` while every photo is counted again; a session with no window (the CLI, the headless MCP server) counts once, keeps the counts and follows edits; status unchanged (✅) | +| 2026-10-30 | patch | LR-LIB-FOLDER: a folder's count in `albums.list` (the photos of the albums inside it) is put together from the counts of those albums, kept with the sidebar's (`AlbumTally` counts folders, and follows edits to a few photos in them), instead of a pass over the library for each folder on the UI thread; it carries `countPending` like a smart album's; status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..912587b86da 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,19 @@ # What's new in LightCraft +## 2026-10-30 + +### `albums.list` no longer freezes the window in a large library +- The `albums.list` command (also reached as `cmd_albums_list` through MCP when connected to the app) used to count every + smart album's photos on the window's thread before it answered: with many smart albums in a large library, seconds + in which the window did not respond. It now answers at once from the counts the Albums list in the sidebar keeps. + A smart album or folder whose count is not of the library as it is now yet (new rules, an edit to many photos, a + library just opened, or a new minute for an album asking about “the last N days”, itself or through an album it + tests, or a folder with one inside) has `countPending: true`, with the count made before (0 if there is none); ask + again a moment later. A folder's count (the photos of the albums inside it) is put together from their counts, with + no pass over the library of its own, and followed through edits to a few photos like theirs. A script or MCP client + with no window (`lightcraft-cli run`, the headless MCP server) gets the counts counted once and kept, followed + through edits to a few photos instead of counted again with every call. + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock @@ -915,6 +929,17 @@ the other editor (Edit in Other Editor, now ⌥⌘E), and where PhotoCraft is if you use a portable copy. - Export can write PSD too (flat, 8- or 16-bit). +### Folders of albums +- Clicking a folder in the sidebar's Albums section shows the photos of every album and smart album inside it, + folders inside it included, each photo once, as a collection set does in Lightroom Classic. The grid is titled with + the folder's name and follows the sort and the filter bar. The triangle beside the folder opens and closes it; a + click on the row no longer does. +- A folder's view can be saved as a smart album that follows the folder, also after its rules are edited (editing + the rules of a saved album view used to drop the album). It can't be made in, or moved into, the folder it shows + (it would include itself): that folder is no drop target and isn't offered under Move to, and commands say why. +- Agents show a folder with `library.source {"kind": "album", "id": }`; `albums.list` reports a folder's + `count`. + ### Faster GPU exports - Exports with noise reduction, Texture, Clarity, Dehaze or Highlights and Shadows can be much faster on the GPU, depending on the graphics card. On a Windows laptop with an AMD Radeon 780M, a full-size export of a 24 MP raw