From 9ca0d4d5e9310cc2b87fe105b00b69696d08c54b Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:05:02 -0400 Subject: [PATCH 01/24] LR-LIB-FOLDER: a folder of albums holds the photos of the albums inside it Catalog::album_contains / album_photos / album_count answer for a folder: the photos of the albums and smart albums inside it at any depth, each once, deleted ones left out. Catalog::album_members names those albums. A query over a folder gathers its photos once (FolderPhotos), not per photo and album. album_reaches follows folders, so a smart album limited to the folder it is in is reported as a loop; evaluation was already guarded. albums_of still names albums only. Parents that form a ring in a damaged library end the search. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 84 +++++++- .../catalog/src/tests_album_folder_photos.rs | 204 ++++++++++++++++++ 2 files changed, 280 insertions(+), 8 deletions(-) create mode 100644 crates/catalog/src/tests_album_folder_photos.rs diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a6972..8dd86341346 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -432,17 +432,19 @@ 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) { Some(Album { smart: Some(rules), .. }) => self.smart_album_has(id, rules, &rules.prepare_one(), p), + // one photo: no list of members is built for it (a whole view asks `folder_photos`) + Some(a) if a.folder => self.albums.values().any(|m| !m.folder && self.album_is_within(m, id) && self.album_contains(m.id, p)), Some(a) => self.album_lists(a.id, p.id), None => false, } @@ -454,9 +456,47 @@ 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. 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) => parent = self.albums.get(&p).and_then(|a| a.parent), + None => return false, + } + } + false + } + + /// What folder `id` shows, gathered once for a question about many photos; `None` when `id` + /// is not a folder. + pub(crate) fn folder_photos(&self, id: AlbumId) -> Option { + self.albums.get(&id).filter(|a| a.folder)?; + 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()), + } + } + Some(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 { let mut seen: std::collections::HashSet = std::collections::HashSet::new(); let mut next = vec![from]; @@ -464,7 +504,12 @@ impl Catalog { 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(); + // a folder leads to the albums inside it: testing it tests each of them + let tested = 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(), + }; if tested.contains(&to) { return true; } @@ -498,8 +543,12 @@ 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 { + if let Some(folder) = self.folder_photos(id) { + return self.photos.values().filter(|p| !p.deleted && folder.holds(self, p)).map(|p| p.id).collect(); + } match self.albums.get(&id) { Some(Album { smart: Some(rules), .. }) => { let prepared = rules.prepare(); @@ -512,6 +561,9 @@ impl Catalog { /// Number of photos shown for an album in the sources list (excludes deleted photos). pub fn album_count(&self, id: AlbumId) -> usize { + if let Some(folder) = self.folder_photos(id) { + return self.photos.values().filter(|p| !p.deleted && folder.holds(self, p)).count(); + } match self.albums.get(&id) { // counted in place: no id list is built just for its length Some(Album { smart: Some(rules), .. }) => { @@ -1186,9 +1238,25 @@ 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)] +pub(crate) struct FolderPhotos { + listed: std::collections::HashSet, + smart: Vec, +} + +impl FolderPhotos { + pub(crate) 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)] 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/tests_album_folder_photos.rs b/crates/catalog/src/tests_album_folder_photos.rs new file mode 100644 index 00000000000..3d7cd0d5412 --- /dev/null +++ b/crates/catalog/src/tests_album_folder_photos.rs @@ -0,0 +1,204 @@ +//! 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 costs a pass over the photos, not one +//! per album. + +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()); +} + +/// 100 albums of 2,000 photos each in one folder: testing every photo against every album's list +/// would be a billion comparisons. The folder's photos are gathered once per question. +#[test] +fn a_folder_of_big_albums_is_shown_in_one_pass() { + let mut c = Catalog::new(); + let photos: Vec = (0..4000).map(|i| photo(&mut c, &format!("p{i}.jpg"))).collect(); + let big = folder(&mut c, "Big", None); + for k in 0..100usize { + let list: Vec = photos.iter().copied().skip(k).step_by(2).collect(); + album(&mut c, &format!("A{k}"), Some(big), &list); + } + let start = std::time::Instant::now(); + assert_eq!(shown(&c, big).len(), 4000); + assert_eq!(c.album_count(big), 4000); + assert_eq!(c.album_photos(big).len(), 4000); + assert!(start.elapsed() < std::time::Duration::from_secs(2), "took {:?}", start.elapsed()); +} From fb1e00b3872e68048ab1ba6e93fc97ac2518a151 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:09:11 -0400 Subject: [PATCH 02/24] LR-LIB-FOLDER: library.source shows a folder of albums library.source {kind: album, id} takes a folder too: the grid shows the photos of every album and smart album inside it, each once, under the folder's name, following the sort and the filter. A folder has no order by hand, so the album's own-order pass leaves it alone (it would have turned newest-first round). album.removePhotos refuses a folder instead of recording an empty step. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/library/specs.rs | 7 +- crates/engine/src/lib.rs | 2 + crates/engine/src/tests.rs | 1 + .../engine/src/tests/album_folder_source.rs | 217 ++++++++++++++++++ 4 files changed, 224 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/tests/album_folder_source.rs diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 2e7c1311d0c..a19fa7ab08d 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -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 @@ -1229,7 +1230,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(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index acaa1807009..6bb0b55384a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1154,7 +1154,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..aa16ec01049 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2,6 +2,7 @@ use serde_json::{Value, json}; use crate::{Selection, Session, command_specs}; +mod album_folder_source; mod album_order; mod album_remove; mod albums_local; 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..91ede943155 --- /dev/null +++ b/crates/engine/src/tests/album_folder_source.rs @@ -0,0 +1,217 @@ +//! 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 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. +//! - A folder still holds no photos of its own: adding to it or removing from it is refused, +//! and nothing is recorded to undo. +//! - 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_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 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"] { + 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_eq!(shown(&mut s), [3, 2, 1]); +} + +#[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() { + let dir = std::env::temp_dir().join(format!("lc-album-folder-source-{}", std::process::id())); + 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); + drop(back); + let _ = std::fs::remove_dir_all(&dir); +} From e1f64d655505ead75e99599f157b82ec6f1542b5 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:13:34 -0400 Subject: [PATCH 03/24] LR-LIB-FOLDER: clicking a folder of albums shows its photos The folder row in the sidebar's Albums section is a source, as a collection set is in Lightroom Classic: a click fills the grid with the photos of the albums inside it and marks the row; folding is the triangle's alone. Folder rows carry no count, and the sidebar's count cache skips them. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/tally.rs | 7 ++-- crates/ui-egui/src/panels/left/albums.rs | 21 ++++++---- crates/ui-egui/src/tests/panels.rs | 50 ++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 11 deletions(-) diff --git a/crates/catalog/src/tally.rs b/crates/catalog/src/tally.rs index e8fdc61979b..0f2f14e82b4 100644 --- a/crates/catalog/src/tally.rs +++ b/crates/catalog/src/tally.rs @@ -104,7 +104,8 @@ impl Members { } } -/// [`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. Folders of albums are not counted: +/// the sidebar shows them no count, and theirs would cost a pass each. #[derive(Clone, Debug)] pub struct AlbumTally { revision: u64, @@ -152,7 +153,7 @@ 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)); } AlbumTally { revision: cat.revision, counts, members } @@ -202,7 +203,7 @@ impl AlbumTally { 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)); } } diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index 92498eb0233..7eef8078254 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: it + // would be a pass over the library per folder, for a number the albums already give) + 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 { diff --git a/crates/ui-egui/src/tests/panels.rs b/crates/ui-egui/src/tests/panels.rs index 5208de9b76b..1f224cbe692 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -999,6 +999,56 @@ 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 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"); + // the triangle folds it and leaves the source alone + click(&mut h, &format!("albumToggle:{trips}")); + assert!(!has(&h, &format!("source:album:{rome}")), "folded"); + assert_eq!(h.app.session.source, LibrarySource::Album(AlbumId(trips))); + 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] From a45d1887ae078359356f651fd450c4abe9f6caa9 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:14:28 -0400 Subject: [PATCH 04/24] LR-LIB-FOLDER: docs for folders of albums as a source Parity row and What's new: a folder shows the photos of the albums inside it; only the triangle folds it. Co-Authored-By: Claude Opus 5.5 --- docs/parity-checklist.md | 2 +- docs/whats-new.md | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f60..40671ac7a30 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -95,7 +95,7 @@ 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-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 smart album limited to the folder it is in is reported as a loop). 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; 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 | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..67c129aa34e 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -915,6 +915,14 @@ 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. +- 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 From bcf18f5dfe352423c2650c7ec93d83678a114cb9 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:29:46 -0400 Subject: [PATCH 05/24] LR-LIB-FOLDER: review fixes in the catalog: one gathering per pass, one answer for damaged folders A pass over the library (query, people_in, album_count, album_photos) gathers each folder of albums it asks about once, so a smart album limited to a folder costs what the folder does (it asked every album's list for every photo). Replaces the query-only Prepared. smart_album_would_loop_in: whether rules lead to the folder an album is about to go in. A folder that also has rules is a folder to every question, and an album inside a plain album is not in the folder around them (damaged files). The speed test now measures against asking one photo at a time, with photos in no album, rather than against the clock. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 115 +++++++++++++----- crates/catalog/src/query.rs | 37 +++--- crates/catalog/src/tally.rs | 5 + .../catalog/src/tests_album_folder_photos.rs | 99 +++++++++++++-- 4 files changed, 200 insertions(+), 56 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 8dd86341346..5e604bfc64d 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -442,9 +442,14 @@ impl Catalog { /// 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(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), - // one photo: no list of members is built for it (a whole view asks `folder_photos`) - Some(a) if a.folder => self.albums.values().any(|m| !m.folder && self.album_is_within(m, id) && self.album_contains(m.id, p)), Some(a) => self.album_lists(a.id, p.id), None => false, } @@ -466,24 +471,26 @@ impl Catalog { } } - /// Whether `album` sits inside `folder`, directly or through the folders between them. Parents - /// that lead round in a ring (a damaged library) end the search after one pass round it. + /// 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) => parent = self.albums.get(&p).and_then(|a| a.parent), + 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 once for a question about many photos; `None` when `id` - /// is not a folder. - pub(crate) fn folder_photos(&self, id: AlbumId) -> Option { - self.albums.get(&id).filter(|a| a.folder)?; + /// What folder `id` shows, gathered for a question about many photos. + fn folder_photos(&self, id: AlbumId) -> FolderPhotos { let mut shown = FolderPhotos::default(); for member in self.album_members(id).iter().filter_map(|m| self.albums.get(m)) { match member.smart { @@ -491,29 +498,48 @@ impl Catalog { None => shown.listed.extend(member.photos.iter().copied()), } } - Some(shown) + 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 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; } - // a folder leads to the albums inside it: testing it tests each of them - let tested = 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(), - }; - if tested.contains(&to) { + if found(a) { return true; } - next.extend(tested); + next.extend(self.album_leads_to(a)); } false } @@ -546,13 +572,11 @@ impl Catalog { /// 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 { - if let Some(folder) = self.folder_photos(id) { - return self.photos.values().filter(|p| !p.deleted && folder.holds(self, p)).map(|p| p.id).collect(); - } 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(), @@ -561,14 +585,12 @@ impl Catalog { /// Number of photos shown for an album in the sources list (excludes deleted photos). pub fn album_count(&self, id: AlbumId) -> usize { - if let Some(folder) = self.folder_photos(id) { - return self.photos.values().filter(|p| !p.deleted && folder.holds(self, p)).count(); - } 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, @@ -1241,17 +1263,52 @@ fn album_order_key(a: &Album) -> (bool, bool, u32, String, AlbumId) { /// 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)] -pub(crate) struct FolderPhotos { +struct FolderPhotos { listed: std::collections::HashSet, smart: Vec, } impl FolderPhotos { - pub(crate) fn holds(&self, cat: &Catalog, p: &Photo) -> bool { + fn holds(&self, cat: &Catalog, p: &Photo) -> bool { self.listed.contains(&p.id) || self.smart.iter().any(|s| cat.album_contains(*s, p)) } } +thread_local! { + /// The folders asked about during a pass over the library ([`gathering`]): `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`'s photos during a pass ([`gathering`]), made by `gather` the first time; `None` +/// outside one. +fn gathered(id: AlbumId, gather: impl FnOnce() -> FolderPhotos) -> Option> { + if let Some(known) = GATHERED.with_borrow(|g| g.as_ref().map(|folders| folders.get(&id).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(id, folder.clone()))); + Some(folder) +} + #[cfg(test)] mod tests; #[cfg(test)] 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 0f2f14e82b4..d5f37e77e2d 100644 --- a/crates/catalog/src/tally.rs +++ b/crates/catalog/src/tally.rs @@ -123,6 +123,11 @@ 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(); diff --git a/crates/catalog/src/tests_album_folder_photos.rs b/crates/catalog/src/tests_album_folder_photos.rs index 3d7cd0d5412..36c7796612e 100644 --- a/crates/catalog/src/tests_album_folder_photos.rs +++ b/crates/catalog/src/tests_album_folder_photos.rs @@ -13,8 +13,12 @@ //! - 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 costs a pass over the photos, not one -//! per album. +//! - 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 crate::*; @@ -185,20 +189,91 @@ fn folders_containing_each_other_still_answer() { assert!(c.album_members(other).is_empty() && shown(&c, other).is_empty()); } -/// 100 albums of 2,000 photos each in one folder: testing every photo against every album's list -/// would be a billion comparisons. The folder's photos are gathered once per question. +/// 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. Measured against the slow way rather than the clock. #[test] fn a_folder_of_big_albums_is_shown_in_one_pass() { let mut c = Catalog::new(); - let photos: Vec = (0..4000).map(|i| photo(&mut c, &format!("p{i}.jpg"))).collect(); + 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..100usize { - let list: Vec = photos.iter().copied().skip(k).step_by(2).collect(); + 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 start = std::time::Instant::now(); - assert_eq!(shown(&c, big).len(), 4000); - assert_eq!(c.album_count(big), 4000); - assert_eq!(c.album_photos(big).len(), 4000); - assert!(start.elapsed() < std::time::Duration::from_secs(2), "took {:?}", start.elapsed()); + let limited = smart(&mut c, "In Big", None, Filter { album: Some(big), ..Default::default() }); + let timed = |f: &dyn Fn() -> usize| { + let start = std::time::Instant::now(); + (f(), start.elapsed()) + }; + // one photo at a time: nothing is gathered + let (n, slow) = timed(&|| c.photos().filter(|p| c.album_contains(big, p)).count()); + assert_eq!(n, 4000); + 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 (n, fast) = timed(f); + assert_eq!(n, 4000, "{what}"); + assert!(fast * 10 < slow, "{what} took {fast:?}; one photo at a time took {slow:?}"); + } +} + +/// 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"); +} + +/// 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)); +} + +/// 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]); } From bc89f5906e9e4c36fdd4fa6406213bde83fac90a Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:30:01 -0400 Subject: [PATCH 06/24] LR-LIB-FOLDER: moving an album into folders that contain each other ends Op::MoveAlbum's walk up the parents for the no-cycle check never ended when the parents already formed a ring (a damaged library file). Bounded by the number of albums; regression test moves an album into such a ring. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/tests_album_folder_photos.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/catalog/src/tests_album_folder_photos.rs b/crates/catalog/src/tests_album_folder_photos.rs index 36c7796612e..bd641ad7312 100644 --- a/crates/catalog/src/tests_album_folder_photos.rs +++ b/crates/catalog/src/tests_album_folder_photos.rs @@ -277,3 +277,20 @@ fn an_album_inside_a_plain_album_is_not_in_the_folder() { 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"); +} From 52fd3f9db1c34da93227746602f4b2b2e451247d Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:33:08 -0400 Subject: [PATCH 07/24] LR-LIB-FOLDER: a smart album can't be made in or moved into the folder it shows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fix. Showing a folder made its own New ▸ Create Smart Album from Filter… save a view limited to that folder inside it: an album that includes itself, reported only afterwards. album.createSmart, album.move and album.reorder now refuse that (also for a smart album inside a folder being moved) and say where it can go. album.setCover refuses a folder. The reopen test's scratch folder goes away however the test ends. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/library/filters.rs | 18 +++++ crates/engine/src/cmd/library/specs.rs | 13 ++- .../engine/src/tests/album_folder_source.rs | 79 +++++++++++++++++-- 3 files changed, 103 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/library/filters.rs b/crates/engine/src/cmd/library/filters.rs index f0a3a504f34..81759dcd22d 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 moved = cat.album_members(id); + moved.iter().filter_map(|m| cat.album(*m)).find_map(|m| smart_loop_in(cat, &m.name, m.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 a19fa7ab08d..0a684cd6063 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::{ @@ -819,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 })?; @@ -946,6 +950,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() }), @@ -979,6 +984,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 }); @@ -1244,6 +1252,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/tests/album_folder_source.rs b/crates/engine/src/tests/album_folder_source.rs index 91ede943155..3e2d3f1a552 100644 --- a/crates/engine/src/tests/album_folder_source.rs +++ b/crates/engine/src/tests/album_folder_source.rs @@ -12,8 +12,11 @@ //! - 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. -//! - A folder still holds no photos of its own: adding to it or removing from it is refused, -//! and nothing is recorded to undo. +//! - 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. @@ -169,14 +172,72 @@ fn a_folder_holds_no_photos_of_its_own() { s.selection.ids = vec![PhotoId(1)]; s.selection.active = Some(PhotoId(1)); let steps = s.undo.len(); - for cmd in ["album.addPhotos", "album.removePhotos"] { + 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(); @@ -199,7 +260,15 @@ fn agents_see_a_folders_count() { #[test] fn a_folder_is_still_the_source_after_reopening() { - let dir = std::env::temp_dir().join(format!("lc-album-folder-source-{}", std::process::id())); + /// 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(); @@ -212,6 +281,4 @@ fn a_folder_is_still_the_source_after_reopening() { back.open_library(&dir, false).unwrap(); assert_eq!(back.source, LibrarySource::Album(AlbumId(trips))); assert_eq!(shown(&mut back), want); - drop(back); - let _ = std::fs::remove_dir_all(&dir); } From ea722997f108319e925bbee76f7d28f34f25b39d Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:33:08 -0400 Subject: [PATCH 08/24] LR-LIB-FOLDER: the Move to menu says why a move was refused; the sidebar test proves the triangle alone folds Review fix. The test clicked the triangle only while the folder was already shown, so it couldn't tell a fold from a click on the row. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/left/folders.rs | 5 ++++- crates/ui-egui/src/tests/panels.rs | 9 ++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index 20c1bbce130..bf380b4e2c1 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -233,7 +233,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/panels.rs b/crates/ui-egui/src/tests/panels.rs index 1f224cbe692..de1c250e00e 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -1021,6 +1021,12 @@ fn clicking_an_album_folder_shows_the_photos_of_its_albums() { 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))); @@ -1031,10 +1037,11 @@ fn clicking_an_album_folder_shows_the_photos_of_its_albums() { 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"); - // the triangle folds it and leaves the source alone + // 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}")); From e3ee999f21f673945dec9c8cf7495c6082fa9ce1 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:33:09 -0400 Subject: [PATCH 09/24] LR-LIB-FOLDER: docs for smart albums and the folder they show Co-Authored-By: Claude Opus 5.5 --- docs/parity-checklist.md | 2 +- docs/whats-new.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 40671ac7a30..8dbf6435888 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -95,7 +95,7 @@ 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`), `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 smart album limited to the folder it is in is reported as a loop). 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-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). 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; 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 | diff --git a/docs/whats-new.md b/docs/whats-new.md index 67c129aa34e..42694dcafd8 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -920,6 +920,8 @@ 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. It can't be made in, or moved into, the + folder it shows (it would include itself): LightCraft says so instead of leaving a ⚠ album. - Agents show a folder with `library.source {"kind": "album", "id": }`; `albums.list` reports a folder's `count`. From 0f7c678a8f8180371098155fc28bc7465ba0cb30 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:50:32 -0400 Subject: [PATCH 10/24] LR-LIB-FOLDER: second review fixes in the catalog album_move_would_loop names the smart album a move would make include itself (one question for the engine and the sidebar). A pass keeps the folders it gathered apart by catalog as well as id. The speed test takes the best of five runs against a 5x margin: one run against 10x failed 2 times in 40 on a machine with 30 busy loops. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 28 ++++++++--- .../catalog/src/tests_album_folder_photos.rs | 49 +++++++++++++++++-- 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 5e604bfc64d..86cb5917011 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -445,7 +445,7 @@ impl Catalog { // 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(id, || self.folder_photos(id)) { + 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)), }, @@ -517,6 +517,16 @@ impl Catalog { }) } + /// 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 { @@ -1275,8 +1285,9 @@ impl FolderPhotos { } thread_local! { - /// The folders asked about during a pass over the library ([`gathering`]): `None` outside one. - static GATHERED: std::cell::RefCell>>> = + /// 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) }; } @@ -1297,15 +1308,16 @@ pub(crate) fn gathering(pass: impl FnOnce() -> T) -> T { pass() } -/// Folder `id`'s photos during a pass ([`gathering`]), made by `gather` the first time; `None` -/// outside one. -fn gathered(id: AlbumId, gather: impl FnOnce() -> FolderPhotos) -> Option> { - if let Some(known) = GATHERED.with_borrow(|g| g.as_ref().map(|folders| folders.get(&id).cloned()))? { +/// 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(id, folder.clone()))); + GATHERED.with_borrow_mut(|g| g.as_mut().map(|folders| folders.insert(key, folder.clone()))); Some(folder) } diff --git a/crates/catalog/src/tests_album_folder_photos.rs b/crates/catalog/src/tests_album_folder_photos.rs index bd641ad7312..4d894ebdb82 100644 --- a/crates/catalog/src/tests_album_folder_photos.rs +++ b/crates/catalog/src/tests_album_folder_photos.rs @@ -203,12 +203,18 @@ fn a_folder_of_big_albums_is_shown_in_one_pass() { album(&mut c, &format!("A{k}"), Some(big), &list); } let limited = smart(&mut c, "In Big", None, Filter { album: Some(big), ..Default::default() }); + // the best of a few runs: a busy machine can hold one up, not all of them let timed = |f: &dyn Fn() -> usize| { - let start = std::time::Instant::now(); - (f(), start.elapsed()) + let once = || { + let start = std::time::Instant::now(); + (f(), start.elapsed()) + }; + (0..5).map(|_| once()).min_by_key(|(_, took)| *took).unwrap() }; - // one photo at a time: nothing is gathered - let (n, slow) = timed(&|| c.photos().filter(|p| c.album_contains(big, p)).count()); + // one photo at a time: nothing is gathered (once: it is the slow one) + let start = std::time::Instant::now(); + let n = c.photos().filter(|p| c.album_contains(big, p)).count(); + let slow = start.elapsed(); assert_eq!(n, 4000); for (what, f) in [ ("query", &(|| shown(&c, big).len()) as &dyn Fn() -> usize), @@ -219,7 +225,7 @@ fn a_folder_of_big_albums_is_shown_in_one_pass() { ] { let (n, fast) = timed(f); assert_eq!(n, 4000, "{what}"); - assert!(fast * 10 < slow, "{what} took {fast:?}; one photo at a time took {slow:?}"); + assert!(fast * 5 < slow, "{what} took {fast:?}; one photo at a time took {slow:?}"); } } @@ -246,6 +252,39 @@ fn rules_that_lead_to_a_folder_cant_go_in_it() { 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] From eb8a53d287ff4e8781632224257a5eab4c04ffeb Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:50:32 -0400 Subject: [PATCH 11/24] LR-LIB-FOLDER: editing a saved view's rules keeps the album or folder it shows album.setRules with replace (what the rules dialog sends) started from an empty filter and kept only the library folder, so a folder's view saved as a smart album matched the whole library after OK. It keeps the album field too, unless the call gives album: null. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/library/filters.rs | 4 ++-- crates/engine/src/cmd/library/specs.rs | 7 +++++- .../engine/src/tests/album_folder_source.rs | 24 +++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/library/filters.rs b/crates/engine/src/cmd/library/filters.rs index 81759dcd22d..8f7dfc8acc9 100644 --- a/crates/engine/src/cmd/library/filters.rs +++ b/crates/engine/src/cmd/library/filters.rs @@ -52,8 +52,8 @@ pub(super) fn smart_loop_in(cat: &lightcraft_catalog::Catalog, name: &str, rules /// 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 moved = cat.album_members(id); - moved.iter().filter_map(|m| cat.album(*m)).find_map(|m| smart_loop_in(cat, &m.name, m.smart.as_deref()?, 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 diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 0a684cd6063..5d64bd29903 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -882,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 @@ -890,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) }; diff --git a/crates/engine/src/tests/album_folder_source.rs b/crates/engine/src/tests/album_folder_source.rs index 3e2d3f1a552..9ea497f8d33 100644 --- a/crates/engine/src/tests/album_folder_source.rs +++ b/crates/engine/src/tests/album_folder_source.rs @@ -12,6 +12,9 @@ //! - 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 @@ -164,6 +167,27 @@ fn a_folder_view_saves_as_a_smart_album() { 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(); From 0670a248698c9dd727ecc0519f58f7f326bc3e57 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:50:32 -0400 Subject: [PATCH 12/24] LR-LIB-FOLDER: a folder is no drop target or Move to choice for a smart album that shows it The folder was outlined as a place to drop, then the drop was refused. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/left/albums.rs | 13 ++++++++++--- crates/ui-egui/src/panels/left/folders.rs | 11 ++++++++--- crates/ui-egui/src/tests/panels.rs | 22 ++++++++++++++++++++++ 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index 7eef8078254..d2dd835ce89 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -184,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 bf380b4e2c1..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() { diff --git a/crates/ui-egui/src/tests/panels.rs b/crates/ui-egui/src/tests/panels.rs index de1c250e00e..64976139139 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -1278,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. From 0cbb24d3584616e1650ae669d7646bdbbc0f8ece Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:50:32 -0400 Subject: [PATCH 13/24] LR-LIB-FOLDER: docs for the second review's fixes Co-Authored-By: Claude Opus 5.5 --- docs/parity-checklist.md | 2 +- docs/whats-new.md | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 8dbf6435888..a55e689771b 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -95,7 +95,7 @@ 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`), `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). 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-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; 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 | diff --git a/docs/whats-new.md b/docs/whats-new.md index 42694dcafd8..9f6a0f4d7c5 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -920,8 +920,9 @@ 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. It can't be made in, or moved into, the - folder it shows (it would include itself): LightCraft says so instead of leaving a ⚠ album. +- 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`. From 02cb82e392f536130a56464df8a93baaab3aa652 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 19 Oct 2026 08:27:26 -0400 Subject: [PATCH 14/24] LR-LIB-FOLDER: a folder view follows edits, and the one-pass test counts gathers Review fixes: - a folder of albums has no order of its own, so it no longer counts as an album in its own order: a small edit is followed photo by photo instead of the view being worked out whole - the test that a folder of big albums is gathered in one pass counts the gathers instead of comparing wall-clock timings Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 8 +++++++ .../catalog/src/tests_album_folder_photos.rs | 24 +++++++------------ crates/engine/src/lib.rs | 2 +- .../engine/src/tests/album_folder_source.rs | 19 +++++++++++++++ 4 files changed, 36 insertions(+), 17 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 86cb5917011..c03e8c58d32 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -491,6 +491,8 @@ impl Catalog { /// 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 { @@ -1284,6 +1286,12 @@ impl FolderPhotos { } } +#[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. diff --git a/crates/catalog/src/tests_album_folder_photos.rs b/crates/catalog/src/tests_album_folder_photos.rs index 4d894ebdb82..2a1ff4b88cf 100644 --- a/crates/catalog/src/tests_album_folder_photos.rs +++ b/crates/catalog/src/tests_album_folder_photos.rs @@ -192,7 +192,7 @@ fn folders_containing_each_other_still_answer() { /// 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. Measured against the slow way rather than the clock. +/// 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(); @@ -203,19 +203,11 @@ fn a_folder_of_big_albums_is_shown_in_one_pass() { album(&mut c, &format!("A{k}"), Some(big), &list); } let limited = smart(&mut c, "In Big", None, Filter { album: Some(big), ..Default::default() }); - // the best of a few runs: a busy machine can hold one up, not all of them - let timed = |f: &dyn Fn() -> usize| { - let once = || { - let start = std::time::Instant::now(); - (f(), start.elapsed()) - }; - (0..5).map(|_| once()).min_by_key(|(_, took)| *took).unwrap() - }; - // one photo at a time: nothing is gathered (once: it is the slow one) - let start = std::time::Instant::now(); + // 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(); - let slow = start.elapsed(); - assert_eq!(n, 4000); + 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)), @@ -223,9 +215,9 @@ fn a_folder_of_big_albums_is_shown_in_one_pass() { ("smart album's count", &|| c.album_count(limited)), ("smart album's query", &|| shown(&c, limited).len()), ] { - let (n, fast) = timed(f); - assert_eq!(n, 4000, "{what}"); - assert!(fast * 5 < slow, "{what} took {fast:?}; one photo at a time took {slow:?}"); + let before = gathers(); + assert_eq!(f(), 4000, "{what}"); + assert_eq!(gathers() - before, 1, "{what} gathered the folder's photos once for the whole pass"); } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6bb0b55384a..c62cae14127 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1114,7 +1114,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. diff --git a/crates/engine/src/tests/album_folder_source.rs b/crates/engine/src/tests/album_folder_source.rs index 9ea497f8d33..2f1cb52bc38 100644 --- a/crates/engine/src/tests/album_folder_source.rs +++ b/crates/engine/src/tests/album_folder_source.rs @@ -8,6 +8,8 @@ //! - 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 @@ -126,6 +128,23 @@ fn a_folder_follows_the_sort() { 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(); From 0035a8da0fcd2f86ae459f6da9693226d6103ed7 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 14:22:59 -0400 Subject: [PATCH 15/24] LR-LIB-FOLDER: the whole count follows loops through a folder and leaves out a folder that has rules After the rebase onto the tally of #2422: a folder that a library file also gives rules was counted again and took part in the chain heights, and a loop through a folder (a smart album limited to it, one inside it that tests the first) was missed, so the whole count gave one of them a different number than counting it alone. The folder's number for agents (albums.list) is counted on its own, as the whole count leaves folders out. --- crates/catalog/src/tally.rs | 9 ++++--- .../catalog/src/tests_album_folder_photos.rs | 26 +++++++++++++++++++ crates/catalog/src/tests_tally.rs | 5 ++-- crates/engine/src/cmd/query.rs | 6 +++-- 4 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/catalog/src/tally.rs b/crates/catalog/src/tally.rs index d5f37e77e2d..d7d7dcbbfee 100644 --- a/crates/catalog/src/tally.rs +++ b/crates/catalog/src/tally.rs @@ -10,7 +10,7 @@ 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; @@ -130,7 +130,7 @@ impl AlbumTally { 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(); @@ -228,12 +228,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; } diff --git a/crates/catalog/src/tests_album_folder_photos.rs b/crates/catalog/src/tests_album_folder_photos.rs index 2a1ff4b88cf..f6fb5d97411 100644 --- a/crates/catalog/src/tests_album_folder_photos.rs +++ b/crates/catalog/src/tests_album_folder_photos.rs @@ -20,6 +20,8 @@ //! - 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 { @@ -290,6 +292,30 @@ fn a_folder_with_rules_is_still_a_folder() { 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 leaves it out, as it does every folder + assert!(!crate::tally::AlbumTally::of(&c).counts().contains_key(&f)); +} + +/// 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 diff --git a/crates/catalog/src/tests_tally.rs b/crates/catalog/src/tests_tally.rs index 4953a8bd1ec..ad975bc8824 100644 --- a/crates/catalog/src/tests_tally.rs +++ b/crates/catalog/src/tests_tally.rs @@ -47,9 +47,10 @@ 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 are +/// left out, as the whole count leaves them out. fn counted_alone(c: &Catalog) -> Vec<(AlbumId, usize)> { - let mut v: Vec<_> = c.albums().map(|a| (a.id, c.album_count(a.id))).collect(); + let mut v: Vec<_> = c.albums().filter(|a| !a.folder).map(|a| (a.id, c.album_count(a.id))).collect(); v.sort_unstable(); v } diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs index a3926bc5144..328247a9364 100644 --- a/crates/engine/src/cmd/query.rs +++ b/crates/engine/src/cmd/query.rs @@ -48,7 +48,8 @@ fn album_json(a: &Album, all: &[Album], counts: &HashMap, cat: & "id": a.id.0, "name": a.name, "folder": a.folder, - "count": counts.get(&a.id).copied().unwrap_or(0), + // (the whole count leaves folders out: the sidebar shows them none; an agent is told their photos' number) + "count": counts.get(&a.id).copied().unwrap_or_else(|| if a.folder { cat.album_count(a.id) } else { 0 }), "cover": a.cover.map(|c| c.0), "children": children, }); @@ -154,7 +155,8 @@ pub fn specs() -> Vec { }), cmd!(query "albums.list", "List Albums", [], None, "{}", 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 + // every album but the folders counted in one pass, so a smart album tested by others is worked out once + // (a folder's photos are counted on their own, as the whole count leaves folders out) 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())) }), From c12dec194b67c3ff7d62ef42f94b21ca6e7de6ef Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 15:11:54 -0400 Subject: [PATCH 16/24] LR-LIB-FOLDER: a folder shown as the source follows the clock of the smart albums inside it A folder of albums that holds a smart album with an in-the-last-days rule shows different photos once the minute passes, but the view and the count only noticed the rules of the albums a source tests, not those of a folder's members, so they stayed stale until an edit. The check now goes through the folder's albums at any depth. --- crates/engine/src/lib.rs | 10 ++++++++-- crates/engine/src/tests/view_follow.rs | 27 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c62cae14127..5820e3ab072 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -200,7 +200,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 +212,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; } diff --git a/crates/engine/src/tests/view_follow.rs b/crates/engine/src/tests/view_follow.rs index bc47d94c94b..b7b7b0ccaf5 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] { From b7f77a3d13a72abf6807ed0c4e54bfca487aa6fb Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 10:16:26 -0400 Subject: [PATCH 17/24] LR-LIB-FOLDER: the catalog keeps smart albums off loops, and a loop has one meaning Catalog::apply_new is apply for a new edit: one that would put a smart album on a loop (it would include itself through the albums it tests or the folder it is in) is refused and nothing changes, whichever caller makes it. apply, replay and snapshots stay as they were, so undo, redo and libraries that already hold a loop work. A smart album on a loop now holds nothing (albums_on_a_loop). Before, the evaluation guard cut the loop wherever the question happened to enter it, so what an album held depended on which album was asked first, and the cut answers were worked out again each time: 40 looping albums in a folder of 200 photos took 222 ms to count against 3.7 ms for 10. The check is made once per album in a pass over the library; albums_of is such a pass too. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 108 ++++++- .../catalog/src/tests_album_folder_photos.rs | 2 +- crates/catalog/src/tests_album_loops.rs | 294 ++++++++++++++++++ 3 files changed, 389 insertions(+), 15 deletions(-) create mode 100644 crates/catalog/src/tests_album_loops.rs diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index c03e8c58d32..f4f5d5ef94e 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -435,7 +435,8 @@ impl Catalog { /// 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| !a.folder && self.album_contains(a.id, p)).map(|a| a.id).collect() + // a pass over the albums: what they lead to is worked out once + gathering(|| 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 @@ -449,7 +450,9 @@ impl Catalog { 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), + // one on a loop (it would include itself) holds nothing, whoever asks; the others + // are guarded all the same, against chains too deep to follow + Some(Album { smart: Some(rules), .. }) => !self.album_is_on_a_loop(id, rules) && self.smart_album_has(id, rules, &rules.prepare_one(), p), Some(a) => self.album_lists(a.id, p.id), None => false, } @@ -461,6 +464,20 @@ impl Catalog { !p.deleted && rules::smart_album_holds(id, p.id, || rules.matches_in(p, self, prepared)) } + /// Whether smart album `id` (with `rules`) would include itself: its rules lead back to it + /// ([`Self::album_reaches`]). Worked out once per album in a pass over the library. + fn album_is_on_a_loop(&self, id: AlbumId, rules: &Filter) -> bool { + on_a_loop(self, id, || !rules.albums_tested().is_empty() && self.album_reaches(id, id)) + } + + /// The smart albums that would include themselves, through the albums they test and the + /// folders those are in. New edits can't make one ([`Self::apply_new`]); a library from before + /// that rule, or a damaged one, may hold some, and each holds nothing. + pub fn albums_on_a_loop(&self) -> std::collections::BTreeSet { + let tests_albums = |a: &&Album| a.smart.as_deref().is_some_and(|rules| !rules.albums_tested().is_empty()); + self.albums.values().filter(tests_albums).filter(|a| self.album_reaches(a.id, a.id)).map(|a| a.id).collect() + } + /// 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 { @@ -586,6 +603,8 @@ impl Catalog { 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()), + // one on a loop holds nothing + Some(Album { smart: Some(rules), .. }) if self.album_is_on_a_loop(id, rules) => Vec::new(), Some(Album { smart: Some(rules), .. }) => { let prepared = rules.prepare(); gathering(|| self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).map(|p| p.id).collect()) @@ -599,6 +618,7 @@ impl Catalog { 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()), + Some(Album { smart: Some(rules), .. }) if self.album_is_on_a_loop(id, rules) => 0, // counted in place: no id list is built just for its length Some(Album { smart: Some(rules), .. }) => { let prepared = rules.prepare(); @@ -738,6 +758,27 @@ impl Catalog { Ok(inv) } + /// [`Self::apply`] for a new edit (not an undo, a redo or the replay of a saved log, which + /// bring back what was): refused when it would make a smart album include itself, through the + /// albums it tests or the folder it is in ([`Self::albums_on_a_loop`]), and nothing changes. + /// THE place that rule is kept, whichever command, importer or task makes the edit. Albums + /// already on a loop can still be edited, also in ways that leave them on it. + pub fn apply_new(&mut self, op: Op) -> Result { + if !may_make_a_loop(&op) { + return self.apply(op); + } + let before = self.albums_on_a_loop(); + let undo = self.apply(op)?; + let Some(looping) = self.albums_on_a_loop().into_iter().find(|a| !before.contains(a)) else { return Ok(undo) }; + // named as it is once the edit is taken back, or as the edit would have made it + let made = self.albums.get(&looping).map(|a| a.name.clone()).unwrap_or_default(); + self.apply(undo)?; + let name = self.albums.get(&looping).map_or(made.as_str(), |a| a.name.as_str()); + Err(CatalogError::Invalid(format!( + "smart album “{name}” would include itself: its rules lead back to it through the albums they test or the folder it is in" + ))) + } + 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 @@ -1292,48 +1333,87 @@ thread_local! { static FOLDER_GATHERS: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// What a pass over the library ([`gathering`]) works out once: by catalog (where it is, which +/// holds for the pass: it is borrowed throughout) and album. +#[derive(Default)] +struct Pass { + /// The photos of the folders asked about. + folders: std::collections::HashMap<(usize, AlbumId), std::rc::Rc>, + /// Whether each smart album asked about is on a loop ([`Catalog::albums_on_a_loop`]). + loops: std::collections::HashMap<(usize, AlbumId), bool>, +} + 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) }; + /// The pass over the library under way on this thread: `None` outside one. + static PASS: 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. +/// Run `pass`, a question put to many photos (or many albums) 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, and each smart album is checked +/// for a loop once. 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); + PASS.with_borrow_mut(|p| *p = None); } } } - let outermost = GATHERED.with_borrow_mut(|g| g.is_none().then(|| *g = Some(Default::default())).is_some()); + let outermost = PASS.with_borrow_mut(|p| p.is_none().then(|| *p = Some(Pass::default())).is_some()); let _forget = Forget(outermost); pass() } +fn pass_key(cat: &Catalog, id: AlbumId) -> (usize, AlbumId) { + (std::ptr::from_ref(cat) as usize, id) +} + /// 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()))? { + let key = pass_key(cat, id); + if let Some(known) = PASS.with_borrow(|p| p.as_ref().map(|pass| pass.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()))); + PASS.with_borrow_mut(|p| p.as_mut().map(|pass| pass.folders.insert(key, folder.clone()))); Some(folder) } +/// Whether smart album `id` of `cat` is on a loop, by `search`: asked once per pass +/// ([`gathering`]), and every time outside one. +fn on_a_loop(cat: &Catalog, id: AlbumId, search: impl FnOnce() -> bool) -> bool { + let key = pass_key(cat, id); + if let Some(known) = PASS.with_borrow(|p| p.as_ref().and_then(|pass| pass.loops.get(&key).copied())) { + return known; + } + // searched with nothing borrowed, then kept + let looping = search(); + PASS.with_borrow_mut(|p| p.as_mut().map(|pass| pass.loops.insert(key, looping))); + looping +} + +/// Whether `op` can put a smart album on a loop: it adds one, moves an album or folder, or +/// changes rules (alone or in a batch). +fn may_make_a_loop(op: &Op) -> bool { + match op { + Op::AddAlbum { album } => album.smart.is_some(), + Op::MoveAlbum { .. } | Op::SetAlbumRules { .. } => true, + Op::Batch { ops } => ops.iter().any(may_make_a_loop), + _ => false, + } +} + #[cfg(test)] mod tests; #[cfg(test)] mod tests_album_folder_photos; #[cfg(test)] +mod tests_album_loops; +#[cfg(test)] mod tests_album_order; #[cfg(test)] mod tests_background; diff --git a/crates/catalog/src/tests_album_folder_photos.rs b/crates/catalog/src/tests_album_folder_photos.rs index f6fb5d97411..44f70952742 100644 --- a/crates/catalog/src/tests_album_folder_photos.rs +++ b/crates/catalog/src/tests_album_folder_photos.rs @@ -158,7 +158,7 @@ fn a_smart_album_testing_its_own_folder_is_a_loop_that_ends() { // 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"); + assert!(shown(&c, by_filter).is_empty(), "on a loop: it holds nothing"); // 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()); diff --git a/crates/catalog/src/tests_album_loops.rs b/crates/catalog/src/tests_album_loops.rs new file mode 100644 index 00000000000..85de27494fd --- /dev/null +++ b/crates/catalog/src/tests_album_loops.rs @@ -0,0 +1,294 @@ +//! Smart albums that would include themselves: through the albums they test, the smart albums +//! those test, and the folders any of them are in. +//! +//! The rule is the catalog's: a new edit that would put a smart album on such a loop is refused +//! (`Catalog::apply_new`), whoever makes it. Libraries saved before the rule, or damaged, may +//! still hold loops and must open (`Catalog::apply`, `replay` and snapshots take them); there a +//! loop has one meaning: every smart album on it holds nothing. +//! +//! Scenarios: +//! - Given smart albums on a loop, then each holds nothing, whichever album is asked first, one +//! photo at a time or in a pass; albums that only test them see them as empty. +//! - Given any library, loops or not, then what an album holds doesn't depend on the order the +//! albums are asked in. +//! - Given many smart albums each limited to the folder they are in, then showing the folder +//! costs in proportion to their number. +//! - When a new edit (adding a smart album, moving an album or folder, changing rules, alone or +//! in a batch) would put a smart album on a loop, then it is refused, names the album, and +//! nothing changed. +//! - Given a library that already holds a loop, then it opens, the albums on the loop can still +//! be edited and the loop undone, and edits elsewhere go through. + +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 +} + +/// A smart album as a library saved before the rule could hold it (no check). +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 +} + +fn limited_to(album: AlbumId) -> Filter { + Filter { album: Some(album), ..Default::default() } +} + +/// Rules of Album rules: `(op, album)` joined by `all`. +fn tests(rules: &[(&str, AlbumId)]) -> Filter { + let rules: Vec = rules.iter().map(|(op, a)| serde_json::json!({"field": "album", "op": op, "value": a.0})).collect(); + serde_json::from_value(serde_json::json!({"ruleSet": {"match": "all", "rules": rules}})).unwrap() +} + +fn holds(c: &Catalog, a: AlbumId, p: PhotoId) -> bool { + c.album_contains(a, c.photo(p).unwrap()) +} + +/// Two folders whose smart albums are limited to each other's folder, an album with a photo, and +/// albums outside that test them. +#[test] +fn albums_on_a_loop_hold_nothing_whoever_asks_first() { + let mut c = Catalog::new(); + let p = photo(&mut c, "p.jpg"); + let (g, ff) = (folder(&mut c, "G", None), folder(&mut c, "FF", None)); + let s = smart(&mut c, "S", Some(ff), limited_to(g)); + let t = smart(&mut c, "T", Some(g), limited_to(ff)); + album(&mut c, "R", Some(g), &[p]); + let both = smart(&mut c, "S and T", None, tests(&[("is", s), ("is", t)])); + let not_s = smart(&mut c, "Not S", None, tests(&[("isNot", s)])); + let of_g = smart(&mut c, "Of G", None, limited_to(g)); + assert_eq!(c.albums_on_a_loop(), [s, t].into_iter().collect()); + let ask = |order: &[AlbumId]| -> Vec<(AlbumId, bool)> { + let mut answers: Vec<(AlbumId, bool)> = order.iter().map(|a| (*a, holds(&c, *a, p))).collect(); + answers.sort(); + answers + }; + let all = [s, t, both, not_s, of_g, g, ff]; + let forwards = ask(&all); + let mut reversed = all; + reversed.reverse(); + assert_eq!(forwards, ask(&reversed)); + let answer = |a: AlbumId| forwards.iter().find(|(x, _)| *x == a).unwrap().1; + assert!(!answer(s) && !answer(t), "on the loop: nothing"); + assert!(!answer(both), "tests two albums that hold nothing"); + assert!(answer(not_s), "S holds nothing, so p isn't in it"); + assert!(answer(of_g) && answer(g), "the folder still shows the album in it"); + assert!(!answer(ff), "only S is in FF"); + // the same in a pass over the library + for a in all { + assert_eq!(c.album_count(a), usize::from(answer(a)), "album {a:?}"); + assert_eq!(c.album_photos(a).len(), usize::from(answer(a)), "album {a:?}"); + } + // and each is reported + for a in [s, t] { + assert!(c.smart_album_problems(a).iter().any(|p| p.issue == crate::rules::Issue::AlbumLoop)); + } +} + +/// A small generator: the same sequence every run. +struct Rng(u64); +impl Rng { + fn next(&mut self, n: u64) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 33) % n + } +} + +/// Random libraries of folders, albums and smart albums that test each other at random (many end +/// up with loops): what each album holds is the same asked forwards, backwards, alone or in a pass. +#[test] +fn what_an_album_holds_never_depends_on_who_asks_first() { + let mut rng = Rng(7); + let mut with_loops = 0; + for _ in 0..300 { + let mut c = Catalog::new(); + let photos: Vec = (0..4).map(|i| photo(&mut c, &format!("p{i}.jpg"))).collect(); + let n = 3 + rng.next(8); + let mut ids: Vec = Vec::new(); + let mut folders: Vec = Vec::new(); + for i in 0..n { + let parent = (!folders.is_empty() && rng.next(2) == 0).then(|| folders[rng.next(folders.len() as u64) as usize]); + let id = match rng.next(4) { + 0 => { + let f = folder(&mut c, &format!("F{i}"), parent); + folders.push(f); + f + } + 1 => { + let held: Vec = photos.iter().copied().filter(|_| rng.next(2) == 0).collect(); + album(&mut c, &format!("A{i}"), parent, &held) + } + // rules are set once every album exists, so they can name later ones + _ => smart(&mut c, &format!("S{i}"), parent, Filter::default()), + }; + ids.push(id); + } + for id in ids.clone() { + if c.album(id).is_some_and(|a| a.smart.is_some()) { + let pick = |rng: &mut Rng| ids[rng.next(ids.len() as u64) as usize]; + let rules = match rng.next(3) { + 0 => limited_to(pick(&mut rng)), + 1 => tests(&[(if rng.next(2) == 0 { "is" } else { "isNot" }, pick(&mut rng))]), + _ => tests(&[("is", pick(&mut rng)), ("isNot", pick(&mut rng))]), + }; + // unchecked, as an old library could hold them (a filter naming a smart album + // directly is the one thing `apply` itself refuses) + let _ = c.apply(Op::SetAlbumRules { id, rules: Box::new(rules) }); + } + } + with_loops += usize::from(!c.albums_on_a_loop().is_empty()); + let table = |order: &[AlbumId]| -> Vec<(AlbumId, PhotoId, bool)> { + let mut t: Vec<(AlbumId, PhotoId, bool)> = Vec::new(); + for a in order { + for p in &photos { + t.push((*a, *p, holds(&c, *a, *p))); + } + } + t.sort(); + t + }; + let forwards = table(&ids); + let mut reversed = ids.clone(); + reversed.reverse(); + assert_eq!(forwards, table(&reversed), "{}", c.to_snapshot()); + let in_a_pass = crate::gathering(|| table(&reversed)); + assert_eq!(forwards, in_a_pass, "{}", c.to_snapshot()); + for a in &ids { + let want: Vec = forwards.iter().filter(|(x, _, yes)| x == a && *yes).map(|(_, p, _)| *p).collect(); + assert_eq!(c.album_photos(*a).into_iter().filter(|p| !c.photo(*p).unwrap().deleted).collect::>(), want, "{}", c.to_snapshot()); + } + for a in c.albums_on_a_loop() { + assert!(photos.iter().all(|p| !holds(&c, a, *p)), "on a loop, so empty: {}", c.to_snapshot()); + } + } + assert!(with_loops > 50, "the generator makes loops: {with_loops} of 300"); +} + +/// `k` smart albums each limited to the folder they are all in, 200 photos: showing the folder +/// asked each of them about all the others (cubic in `k`). Four times the albums now costs a few +/// times more, not sixty. +#[test] +fn a_folder_of_looping_albums_costs_in_proportion() { + let build = |k: usize| { + let mut c = Catalog::new(); + let photos: Vec = (0..200).map(|i| photo(&mut c, &format!("p{i}.jpg"))).collect(); + let f = folder(&mut c, "F", None); + album(&mut c, "Plain", Some(f), &photos[..100]); + for i in 0..k { + smart(&mut c, &format!("S{i}"), Some(f), limited_to(f)); + } + (c, f) + }; + let timed = |c: &Catalog, f: AlbumId| { + (0..5) + .map(|_| { + let start = std::time::Instant::now(); + assert_eq!(c.album_count(f), 100); + start.elapsed() + }) + .min() + .unwrap() + }; + let (small, f_small) = build(10); + let (big, f_big) = build(40); + let (t10, t40) = (timed(&small, f_small), timed(&big, f_big)); + assert!(t40 < t10 * 20 + std::time::Duration::from_millis(2), "10 albums: {t10:?}; 40 albums: {t40:?}"); +} + +fn album_names(c: &Catalog) -> Vec<(AlbumId, Option, String)> { + c.albums().map(|a| (a.id, a.parent, serde_json::to_string(&a.smart).unwrap())).collect() +} + +#[test] +fn a_new_edit_that_would_make_a_loop_is_refused() { + let mut c = Catalog::new(); + let trips = folder(&mut c, "Trips", None); + let europe = folder(&mut c, "Europe", Some(trips)); + let view = smart(&mut c, "Trips view", None, limited_to(trips)); + let plain_rules = smart(&mut c, "Rated", Some(trips), Filter { rating: 3, ..Default::default() }); + let before = album_names(&c); + let next = AlbumId(99); + let new_smart = |parent, rules| Op::AddAlbum { album: Album { parent, smart: Some(Box::new(rules)), ..Album::new(next, "New one") } }; + let refused: Vec<(&str, Op, &str)> = vec![ + ("made in the folder it shows", new_smart(Some(trips), limited_to(trips)), "New one"), + ("made in a folder inside it", new_smart(Some(europe), limited_to(trips)), "New one"), + ("moved into it", Op::MoveAlbum { id: view, parent: Some(europe) }, "Trips view"), + ("rules changed to show its own folder", Op::SetAlbumRules { id: plain_rules, rules: Box::new(limited_to(trips)) }, "Rated"), + ("rules changed to test an album that tests it", Op::SetAlbumRules { id: view, rules: Box::new(tests(&[("is", view)])) }, "Trips view"), + ( + "in a batch", + Op::Batch { ops: vec![Op::RenameAlbum { id: view, name: "Renamed".into() }, Op::MoveAlbum { id: view, parent: Some(trips) }] }, + "Trips view", + ), + ]; + for (what, op, name) in refused { + let e = c.apply_new(op).unwrap_err().to_string(); + assert!(e.contains(name) && e.contains("include itself"), "{what}: {e}"); + assert_eq!(album_names(&c), before, "{what}: nothing changed"); + assert_eq!(c.album(view).unwrap().name, "Trips view", "{what}"); + assert!(c.albums_on_a_loop().is_empty(), "{what}"); + } + // what makes no loop goes through, and is undone by what it returns + let allowed = vec![ + new_smart(None, limited_to(trips)), + new_smart(Some(trips), limited_to(europe)), + Op::MoveAlbum { id: plain_rules, parent: Some(europe) }, + Op::SetAlbumRules { id: view, rules: Box::new(tests(&[("isNot", plain_rules)])) }, + ]; + for op in allowed { + let undo = c.apply_new(op.clone()).unwrap_or_else(|e| panic!("{op:?}: {e}")); + assert!(c.albums_on_a_loop().is_empty()); + c.apply(undo).unwrap(); + assert_eq!(album_names(&c), before); + } +} + +#[test] +fn a_library_that_already_holds_a_loop_opens_and_can_be_mended() { + // as written by a version without the rule: the op log makes a loop + let mut old = Catalog::new(); + let mut log = String::new(); + let mut record = |c: &mut Catalog, op: Op| { + log.push_str(&Catalog::op_to_log_line(&op)); + c.apply(op).unwrap(); + }; + let trips = AlbumId(1); + let (inside, other) = (AlbumId(2), AlbumId(3)); + record(&mut old, Op::AddAlbum { album: Album { folder: true, ..Album::new(trips, "Trips") } }); + record(&mut old, Op::AddAlbum { album: Album { parent: Some(trips), smart: Some(Box::new(limited_to(trips))), ..Album::new(inside, "Inside") } }); + record(&mut old, Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(other, "Other") } }); + let mut c = Catalog::new(); + assert_eq!(c.replay(&log).unwrap(), 3, "the log replays"); + assert_eq!(c.albums_on_a_loop(), [inside].into_iter().collect()); + let from_snapshot = Catalog::from_snapshot(&c.to_snapshot()).unwrap(); + assert_eq!(from_snapshot.albums_on_a_loop(), [inside].into_iter().collect()); + // edits elsewhere, and edits to the album on the loop that leave it there, go through + c.apply_new(Op::RenameAlbum { id: inside, name: "Still inside".into() }).unwrap(); + c.apply_new(Op::SetAlbumRules { id: other, rules: Box::new(Filter { rating: 2, ..Default::default() }) }).unwrap(); + c.apply_new(Op::SetAlbumRules { id: inside, rules: Box::new(Filter { rating: 4, album: Some(trips), ..Default::default() }) }).unwrap(); + // but it doesn't get to take another album onto a loop + let e = c.apply_new(Op::MoveAlbum { id: other, parent: Some(trips) }).map(|_| ()); + assert!(e.is_ok(), "Other tests no album: moving it in makes no loop"); + let e = c.apply_new(Op::SetAlbumRules { id: other, rules: Box::new(limited_to(trips)) }).unwrap_err().to_string(); + assert!(e.contains("Other"), "{e}"); + // mended by moving it out + c.apply_new(Op::MoveAlbum { id: inside, parent: None }).unwrap(); + assert!(c.albums_on_a_loop().is_empty()); +} From 189eafa3889b06f9ba64302abab4565bc07b67e3 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 10:16:26 -0400 Subject: [PATCH 18/24] LR-LIB-FOLDER: every session edit keeps the catalog's loop rule Session::commit applies through Catalog::apply_new, so a command, importer or task that forgets the check can't make a smart album include itself. Undo, redo and opening a library are not new edits: a library saved with a loop opens, and undoing its mending brings the loop back. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lib.rs | 38 +++++++--- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/album_loops.rs | 99 ++++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/tests/album_loops.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5820e3ab072..aeb6a53e1c8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -634,10 +634,13 @@ impl Session { // ---------------------------------------------------------------- ops, undo - /// Apply an op as one undoable step. + /// Apply an op as one undoable step. A new edit: one that would make a smart album include + /// itself is refused here, whichever command asked ([`Catalog::apply_new`]); undo, redo and + /// opening a library bring back what was and are not held to that. pub fn commit(&mut self, label: &str, op: Op) -> Result<()> { let fwd = op.clone(); - let inv = self.apply_catalog(op)?; + let inv = self.catalog.apply_new(op)?; + self.forget_media_of(&fwd); self.pending_log.push(fwd); self.undo.push(UndoEntry { label: label.to_string(), op: inv, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }); self.commits = self.commits.wrapping_add(1); @@ -651,13 +654,29 @@ impl Session { Ok(()) } + /// [`Catalog::apply`] for what brings back what was (an undo, a redo, a repair): not held to + /// the loop rule a new edit is ([`Session::commit`]). fn apply_catalog(&mut self, op: Op) -> Result { // Retain only cache IDs while the catalog consumes the operation. Cloning an import // batch here also cloned every photo, although commit already keeps the journal copy. - let mut invalidated = Vec::new(); - // photos whose file was replaced: the faces made from the old pixels go too (issue #1524) - let mut replaced = Vec::new(); - let mut pending = vec![&op]; + let media = Self::media_of(&op); + let inv = self.catalog.apply(op)?; + self.forget_media(media); + Ok(inv) + } + + /// Drops what is cached of the files of the photos `op` (just applied) gave another file or + /// content, added or removed. + fn forget_media_of(&mut self, op: &Op) { + let media = Self::media_of(op); + self.forget_media(media); + } + + /// The photos `op` gives another file or content, adds or removes, and of those the ones + /// whose file was replaced (their faces were made from the old pixels, issue #1524). + fn media_of(op: &Op) -> (Vec, Vec) { + let (mut invalidated, mut replaced) = (Vec::new(), Vec::new()); + let mut pending = vec![op]; while let Some(op) = pending.pop() { match op { Op::SetContent { id, .. } => { @@ -670,7 +689,11 @@ impl Session { _ => {} } } - let inv = self.catalog.apply(op)?; + (invalidated, replaced) + } + + /// Forgets what [`Session::media_of`] found, once the op is applied. + fn forget_media(&mut self, (invalidated, replaced): (Vec, Vec)) { for id in invalidated { self.media.forget(id); } @@ -680,7 +703,6 @@ impl Session { } #[cfg(target_arch = "wasm32")] let _ = replaced; - Ok(inv) } /// [`Session::commit`] for an op that goes with a folder already renamed on disk; the undo diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index aa16ec01049..4aa59cc647e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use crate::{Selection, Session, command_specs}; mod album_folder_source; +mod album_loops; mod album_order; mod album_remove; mod albums_local; diff --git a/crates/engine/src/tests/album_loops.rs b/crates/engine/src/tests/album_loops.rs new file mode 100644 index 00000000000..10380325ce2 --- /dev/null +++ b/crates/engine/src/tests/album_loops.rs @@ -0,0 +1,99 @@ +//! A smart album never comes to include itself by a new edit, whatever makes the edit +//! (`Session::commit` keeps the catalog's rule, `Catalog::apply_new`); a library that already +//! holds such a loop opens, works and can be mended, and undo and redo move across it freely. +//! +//! Scenarios: +//! - When an edit that no command checked would put a smart album on a loop, then it is +//! refused, and there is nothing to undo. +//! - Given a library saved with a loop in it, when it is opened, then the album on the loop is +//! reported and empty, the folder it is in shows its other albums, and moving the album out +//! mends it; undoing that brings the loop back (it was there), and redoing mends it again. + +use lightcraft_catalog::{Album, AlbumId, Filter, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::Session; + +fn limited_to(album: u64) -> Filter { + Filter { album: Some(AlbumId(album)), ..Default::default() } +} + +fn make(s: &mut Session, params: serde_json::Value) -> u64 { + s.execute("album.create", ¶ms).unwrap()["id"].as_u64().unwrap() +} + +#[test] +fn an_edit_no_command_checked_cant_make_a_loop() { + let mut s = Session::new(); + let trips = make(&mut s, json!({"name": "Trips", "folder": true})); + let view = s.execute("album.createSmart", &json!({"name": "Trips view", "rules": {"album": trips}})).unwrap()["id"].as_u64().unwrap(); + let (steps, before) = (s.undo.len(), s.catalog.to_snapshot()); + let next = s.catalog.alloc_album_id(); + for op in [ + Op::MoveAlbum { id: AlbumId(view), parent: Some(AlbumId(trips)) }, + Op::AddAlbum { album: Album { parent: Some(AlbumId(trips)), smart: Some(Box::new(limited_to(trips))), ..Album::new(next, "Inside") } }, + Op::Batch { ops: vec![Op::MoveAlbum { id: AlbumId(view), parent: Some(AlbumId(trips)) }] }, + ] { + let e = s.commit("Edit", op).unwrap_err().to_string(); + assert!(e.contains("include itself"), "{e}"); + assert_eq!(s.undo.len(), steps, "nothing to undo"); + assert!(s.catalog.albums_on_a_loop().is_empty()); + } + assert_eq!( + serde_json::from_str::(&s.catalog.to_snapshot()).unwrap()["albums"], + serde_json::from_str::(&before).unwrap()["albums"] + ); +} + +#[test] +fn a_library_saved_with_a_loop_opens_and_is_mended_by_moving_the_album_out() { + /// 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-loops-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&scratch.0); + let mut s = Session::new(); + s.open_library(&scratch.0, false).unwrap(); + let id = s.catalog.alloc_photo_id(); + s.commit( + "Add Photo", + Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 1 }, "p.jpg", "JPEG", 60, 40, "2026-02-01T10:00:00")) }, + ) + .unwrap(); + let trips = make(&mut s, json!({"name": "Trips", "folder": true})); + let rome = make(&mut s, json!({"name": "Rome", "parent": trips})); + s.selection.ids = vec![PhotoId(id.0)]; + s.execute("album.addPhotos", &json!({"id": rome, "ids": [id.0]})).unwrap(); + let view = s.execute("album.createSmart", &json!({"name": "Trips view", "rules": {"album": trips}})).unwrap()["id"].as_u64().unwrap(); + // as a version without the rule recorded it: the view moved into the folder it shows + let old_edit = Op::MoveAlbum { id: AlbumId(view), parent: Some(AlbumId(trips)) }; + s.catalog.apply(old_edit.clone()).unwrap(); + s.pending_log.push(old_edit); + s.execute("album.rename", &json!({"id": rome, "name": "Roma"})).unwrap(); + drop(s); + + let mut s = Session::new(); + s.open_library(&scratch.0, false).unwrap(); + let on_a_loop = |s: &Session| s.catalog.albums_on_a_loop().into_iter().map(|a| a.0).collect::>(); + assert_eq!(on_a_loop(&s), [view], "it opened, loop and all"); + assert!(!s.catalog.smart_album_problems(AlbumId(view)).is_empty(), "and says so"); + let shown = |s: &mut Session, album: u64| { + s.execute("library.source", &json!({"kind": "album", "id": album})).unwrap(); + s.visible_cloned().len() + }; + assert_eq!((shown(&mut s, view), shown(&mut s, trips)), (0, 1), "the album on the loop is empty; its folder shows Roma's photo"); + // other edits go on + s.execute("album.rename", &json!({"id": view, "name": "Still looping"})).unwrap(); + // mended by moving it out; undo brings back what was, redo mends again + s.execute("album.move", &json!({"id": view, "parent": null})).unwrap(); + assert!(on_a_loop(&s).is_empty()); + assert_eq!(shown(&mut s, view), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(on_a_loop(&s), [view], "undo is no new edit: it brings back the library as it was"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(on_a_loop(&s).is_empty()); +} From 5857328acecf9f733e0267e4016eeec4b68c97fc Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 10:16:26 -0400 Subject: [PATCH 19/24] LR-LIB-FOLDER: docs for the loop rule living in the catalog Co-Authored-By: Claude Opus 5.5 --- docs/parity-checklist.md | 2 +- docs/whats-new.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a55e689771b..955cdd34777 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -95,7 +95,7 @@ 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`), `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-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; the catalog keeps the rule for every new edit (`Catalog::apply_new`), and a smart album already on a loop in an older library holds nothing, whichever is asked first; `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; 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 | diff --git a/docs/whats-new.md b/docs/whats-new.md index 9f6a0f4d7c5..ddd07fc4cc9 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -923,6 +923,10 @@ - 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. +- No edit can make a smart album include itself any more, whichever command, importer or task makes it: the library + itself refuses it and names the album. A library that already holds such a loop still opens; each album on the loop + is marked ⚠ and holds nothing (it used to hold different photos depending on which album was looked at first, and + many of them in one folder made the folder slow to show), and moving it out or changing its rules mends it. - Agents show a folder with `library.source {"kind": "album", "id": }`; `albums.list` reports a folder's `count`. From 6d009ea1d56e4ac0d0136eceab26158566ff5277 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 10:50:44 -0400 Subject: [PATCH 20/24] LR-LIB-FOLDER: the loop rule looks ahead instead of applying and taking back Review fixes. apply_new applied the edit, looked for new loops and applied the inverse. The inverse of a rules change is checked like any rules change, so for an album whose saved rules no longer pass that check the taking back failed and the loop stayed, in memory only. It also moved the next album id and the revision on a refusal. Now the albums are outlined as the edit would leave them (who is in what, what tests what) and the loops looked for there: a refused edit never touched the library. Which albums are on a loop is worked out on a graph made in one look at the albums (AlbumGraph), not by scanning every album per folder per smart album: 300 folders each holding a smart album limited to the next took over a second per edit. Adding or removing any album is checked too (a folder taking in an orphaned smart album), the refusal names the album the edit was about, and a folder that carries rules has no loop mark, as it is on none. The random-library test now checks every answer against the definition written out a second time: asking in another order could never differ, so the old assertions passed without the rule. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 152 ++++++++++-- crates/catalog/src/model.rs | 15 ++ crates/catalog/src/tests_album_loops.rs | 302 ++++++++++++++++++++---- 3 files changed, 401 insertions(+), 68 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index f4f5d5ef94e..4af77908434 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -470,12 +470,16 @@ impl Catalog { on_a_loop(self, id, || !rules.albums_tested().is_empty() && self.album_reaches(id, id)) } + /// What each album's photos depend on, for questions about many albums at once. + fn album_graph(&self) -> AlbumGraph { + AlbumGraph::of(self.albums.values()) + } + /// The smart albums that would include themselves, through the albums they test and the /// folders those are in. New edits can't make one ([`Self::apply_new`]); a library from before /// that rule, or a damaged one, may hold some, and each holds nothing. pub fn albums_on_a_loop(&self) -> std::collections::BTreeSet { - let tests_albums = |a: &&Album| a.smart.as_deref().is_some_and(|rules| !rules.albums_tested().is_empty()); - self.albums.values().filter(tests_albums).filter(|a| self.album_reaches(a.id, a.id)).map(|a| a.id).collect() + self.album_graph().on_a_loop() } /// The albums and smart albums whose photos `id` shows: those inside a folder, at any depth @@ -577,7 +581,8 @@ impl Catalog { /// `RuleSet::upgrade`): typically a rule testing an album that has since been deleted. Empty /// for a sound smart album, a plain album or no album. pub fn smart_album_problems(&self, id: AlbumId) -> Vec { - let Some(filter) = self.albums.get(&id).and_then(|a| a.smart.as_deref()) else { return Vec::new() }; + // a folder that carries rules (a damaged library) is a folder: its rules are never asked + let Some(filter) = self.albums.get(&id).filter(|a| !a.folder).and_then(|a| a.smart.as_deref()) else { return Vec::new() }; let mut out: Vec = self.album_filter_problem(filter, Some(id)).into_iter().collect(); if let Some(mut rules) = filter.rule_set.clone() { rules.upgrade(); @@ -760,23 +765,36 @@ impl Catalog { /// [`Self::apply`] for a new edit (not an undo, a redo or the replay of a saved log, which /// bring back what was): refused when it would make a smart album include itself, through the - /// albums it tests or the folder it is in ([`Self::albums_on_a_loop`]), and nothing changes. - /// THE place that rule is kept, whichever command, importer or task makes the edit. Albums - /// already on a loop can still be edited, also in ways that leave them on it. + /// albums it tests or the folder it is in ([`Self::albums_on_a_loop`]). THE place that rule is + /// kept, whichever command, importer or task makes the edit. Albums already on a loop can + /// still be edited, also in ways that leave them on it. + /// + /// The check is made on what the edit would do to the albums, before it is done: a refused + /// edit never touched the library, so there is nothing to take back (or to fail taking back). pub fn apply_new(&mut self, op: Op) -> Result { - if !may_make_a_loop(&op) { - return self.apply(op); + if let Some(looping) = self.would_put_on_a_loop(&op) { + return Err(CatalogError::Invalid(format!( + "smart album “{looping}” would include itself: its rules lead back to it through the albums they test or the folder it is in" + ))); + } + self.apply(op) + } + + /// The name of a smart album `op` would newly put on a loop: the album the op is about when + /// that is one of them. `None` when it makes none (or changes no album). + fn would_put_on_a_loop(&self, op: &Op) -> Option { + if !changes_albums(op) { + return None; } - let before = self.albums_on_a_loop(); - let undo = self.apply(op)?; - let Some(looping) = self.albums_on_a_loop().into_iter().find(|a| !before.contains(a)) else { return Ok(undo) }; - // named as it is once the edit is taken back, or as the edit would have made it - let made = self.albums.get(&looping).map(|a| a.name.clone()).unwrap_or_default(); - self.apply(undo)?; - let name = self.albums.get(&looping).map_or(made.as_str(), |a| a.name.as_str()); - Err(CatalogError::Invalid(format!( - "smart album “{name}” would include itself: its rules lead back to it through the albums they test or the folder it is in" - ))) + // the albums as they would be: who is in what, and what tests what; no photo lists + let mut after: BTreeMap = self.albums.values().map(|a| (a.id, a.outline())).collect(); + let mut edited = Vec::new(); + foresee(&mut after, op, &mut edited); + let now = self.albums_on_a_loop(); + let then = AlbumGraph::of(after.values()).on_a_loop(); + let mut new = then.difference(&now); + let looping = edited.iter().find(|e| then.contains(e) && !now.contains(e)).or_else(|| new.next())?; + Some(after.get(looping).map(|a| a.name.clone()).unwrap_or_default()) } fn apply_inner(&mut self, op: Op) -> Result { @@ -1396,17 +1414,103 @@ fn on_a_loop(cat: &Catalog, id: AlbumId, search: impl FnOnce() -> bool) -> bool looping } -/// Whether `op` can put a smart album on a loop: it adds one, moves an album or folder, or -/// changes rules (alone or in a batch). -fn may_make_a_loop(op: &Op) -> bool { +/// Whether `op` changes which album is in what or what tests what: it adds or removes an album, +/// moves one, or changes rules (alone or in a batch). +fn changes_albums(op: &Op) -> bool { match op { - Op::AddAlbum { album } => album.smart.is_some(), - Op::MoveAlbum { .. } | Op::SetAlbumRules { .. } => true, - Op::Batch { ops } => ops.iter().any(may_make_a_loop), + Op::AddAlbum { .. } | Op::RemoveAlbum { .. } | Op::MoveAlbum { .. } | Op::SetAlbumRules { .. } => true, + Op::Batch { ops } => ops.iter().any(changes_albums), _ => false, } } +/// What `op` would do to `albums`, as far as loops go (who is in what, what tests what), without +/// the checks `apply` makes: an op it would refuse is refused there. `edited` gets the albums the +/// op is about. +fn foresee(albums: &mut BTreeMap, op: &Op, edited: &mut Vec) { + match op { + Op::AddAlbum { album } => { + edited.push(album.id); + albums.entry(album.id).or_insert_with(|| album.outline()); + } + Op::RemoveAlbum { id } => { + albums.remove(id); + } + Op::MoveAlbum { id, parent } => { + edited.push(*id); + if let Some(a) = albums.get_mut(id) { + a.parent = *parent; + } + } + Op::SetAlbumRules { id, rules } => { + edited.push(*id); + if let Some(a) = albums.get_mut(id).filter(|a| a.smart.is_some()) { + a.smart = Some(rules.clone()); + } + } + Op::Batch { ops } => ops.iter().for_each(|op| foresee(albums, op, edited)), + _ => {} + } +} + +/// What the photos of each album depend on: a folder on the albums inside it at any depth, a +/// smart album on the albums and folders it tests (as [`Catalog::album_reaches`] follows them one +/// album at a time). Made in one look at the albums, for questions about all of them. +struct AlbumGraph { + leads_to: std::collections::HashMap>, + /// The smart albums that test albums: the only ones that can be on a loop. + testing: Vec, +} + +impl AlbumGraph { + fn of<'a>(albums: impl Iterator + Clone) -> AlbumGraph { + let by_id: std::collections::HashMap = albums.clone().map(|a| (a.id, a)).collect(); + let mut leads_to: std::collections::HashMap> = std::collections::HashMap::new(); + let mut testing = Vec::new(); + for a in albums { + if a.folder { + continue; + } + // into every folder around it, through folders only (as `album_is_within`); folders + // that contain each other (a damaged library) are each gone through once + let mut around: Vec = Vec::new(); + let mut parent = a.parent; + while let Some(folder) = parent.and_then(|p| by_id.get(&p)).filter(|f| f.folder && !around.contains(&f.id)) { + around.push(folder.id); + leads_to.entry(folder.id).or_default().push(a.id); + parent = folder.parent; + } + let tested = a.smart.as_deref().map(Filter::albums_tested).unwrap_or_default(); + if !tested.is_empty() { + testing.push(a.id); + leads_to.insert(a.id, tested); + } + } + AlbumGraph { leads_to, testing } + } + + /// The smart albums that lead back to themselves. + fn on_a_loop(&self) -> std::collections::BTreeSet { + self.testing.iter().copied().filter(|a| self.reaches(*a, *a)).collect() + } + + fn reaches(&self, from: AlbumId, to: AlbumId) -> bool { + let none = Vec::new(); + let leads = |a: AlbumId| self.leads_to.get(&a).unwrap_or(&none); + let mut seen: std::collections::HashSet = std::collections::HashSet::new(); + let mut next: Vec = leads(from).clone(); + while let Some(a) = next.pop() { + if a == to { + return true; + } + if seen.insert(a) { + next.extend(leads(a)); + } + } + false + } +} + #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index b405e1db965..6647413d1ae 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -540,6 +540,21 @@ pub struct Album { } impl Album { + /// The album without its photos: what it is, where it is and what it tests. + pub(crate) fn outline(&self) -> Album { + Album { + id: self.id, + name: self.name.clone(), + parent: self.parent, + folder: self.folder, + photos: Vec::new(), + cover: None, + smart: self.smart.clone(), + quick: self.quick, + order: self.order, + } + } + /// A regular (manual) album. pub fn new(id: AlbumId, name: impl Into) -> Album { Album { id, name: name.into(), parent: None, folder: false, photos: Vec::new(), cover: None, smart: None, quick: false, order: None } diff --git a/crates/catalog/src/tests_album_loops.rs b/crates/catalog/src/tests_album_loops.rs index 85de27494fd..cef28257a42 100644 --- a/crates/catalog/src/tests_album_loops.rs +++ b/crates/catalog/src/tests_album_loops.rs @@ -111,74 +111,184 @@ impl Rng { } } -/// Random libraries of folders, albums and smart albums that test each other at random (many end -/// up with loops): what each album holds is the same asked forwards, backwards, alone or in a pass. +/// What a smart album of the random libraries asks: limited to an album (its `album` field), or +/// Album rules joined by all / any. +#[derive(Clone)] +enum Asks { + Nothing, + Limited(AlbumId), + Rules { any: bool, rules: Vec<(bool, AlbumId)> }, +} + +impl Asks { + fn filter(&self) -> Filter { + match self { + Asks::Nothing => Filter::default(), + Asks::Limited(a) => limited_to(*a), + Asks::Rules { any, rules } => { + let rules: Vec = + rules.iter().map(|(is, a)| serde_json::json!({"field": "album", "op": if *is { "is" } else { "isNot" }, "value": a.0})).collect(); + serde_json::from_value(serde_json::json!({"ruleSet": {"match": if *any { "any" } else { "all" }, "rules": rules}})).unwrap() + } + } + } + fn tested(&self) -> Vec { + match self { + Asks::Nothing => Vec::new(), + Asks::Limited(a) => vec![*a], + Asks::Rules { rules, .. } => rules.iter().map(|(_, a)| *a).collect(), + } + } +} + +/// The random library written down a second time, plainly, to answer by the definition: a +/// folder holds what the albums in it hold; an album holds its list; a smart album that leads +/// back to itself holds nothing, and any other holds what its rules say. +struct Plain { + parent: std::collections::HashMap>, + folders: std::collections::HashSet, + lists: std::collections::HashMap>, + asks: std::collections::HashMap, +} + +impl Plain { + fn inside(&self, folder: AlbumId) -> Vec { + let mut out = Vec::new(); + for (a, parent) in &self.parent { + if *parent == Some(folder) { + if self.folders.contains(a) { out.extend(self.inside(*a)) } else { out.push(*a) } + } + } + out + } + fn leads_to(&self, a: AlbumId) -> Vec { + if self.folders.contains(&a) { self.inside(a) } else { self.asks.get(&a).map(Asks::tested).unwrap_or_default() } + } + fn on_a_loop(&self, a: AlbumId) -> bool { + let (mut seen, mut next) = (std::collections::HashSet::new(), self.leads_to(a)); + while let Some(x) = next.pop() { + if x == a { + return true; + } + if seen.insert(x) { + next.extend(self.leads_to(x)); + } + } + false + } + fn holds(&self, a: AlbumId, p: PhotoId) -> bool { + if self.folders.contains(&a) { + return self.inside(a).into_iter().any(|m| self.holds(m, p)); + } + if let Some(list) = self.lists.get(&a) { + return list.contains(&p); + } + match self.asks.get(&a) { + None => false, + Some(_) if self.on_a_loop(a) => false, + Some(Asks::Nothing) => true, + Some(Asks::Limited(x)) => self.holds(*x, p), + Some(Asks::Rules { any, rules }) => { + let mut answers = rules.iter().map(|(is, x)| self.holds(*x, p) == *is); + if *any { answers.any(|yes| yes) } else { answers.all(|yes| yes) } + } + } + } +} + +/// Random libraries of folders, albums and smart albums that test each other at random (most end +/// up with loops, many through folders): every way of asking what an album holds gives the answer +/// of the definition ([`Plain`]), whatever was asked before, one photo at a time or in a pass. Before, a +/// loop was cut wherever the question entered it, so an album seen from inside another's rules +/// could differ from the same album asked directly. #[test] -fn what_an_album_holds_never_depends_on_who_asks_first() { +fn what_an_album_holds_is_what_the_definition_says() { let mut rng = Rng(7); - let mut with_loops = 0; - for _ in 0..300 { + let (mut with_loops, mut through_folders) = (0, 0); + for _ in 0..400 { let mut c = Catalog::new(); let photos: Vec = (0..4).map(|i| photo(&mut c, &format!("p{i}.jpg"))).collect(); - let n = 3 + rng.next(8); + let mut plain = Plain { parent: Default::default(), folders: Default::default(), lists: Default::default(), asks: Default::default() }; + let n = 3 + rng.next(10); let mut ids: Vec = Vec::new(); let mut folders: Vec = Vec::new(); for i in 0..n { - let parent = (!folders.is_empty() && rng.next(2) == 0).then(|| folders[rng.next(folders.len() as u64) as usize]); + let parent = (!folders.is_empty() && rng.next(3) != 0).then(|| folders[rng.next(folders.len() as u64) as usize]); let id = match rng.next(4) { 0 => { let f = folder(&mut c, &format!("F{i}"), parent); folders.push(f); + plain.folders.insert(f); f } 1 => { let held: Vec = photos.iter().copied().filter(|_| rng.next(2) == 0).collect(); - album(&mut c, &format!("A{i}"), parent, &held) + let a = album(&mut c, &format!("A{i}"), parent, &held); + plain.lists.insert(a, held); + a } // rules are set once every album exists, so they can name later ones - _ => smart(&mut c, &format!("S{i}"), parent, Filter::default()), + _ => { + let s = smart(&mut c, &format!("S{i}"), parent, Filter::default()); + plain.asks.insert(s, Asks::Nothing); + s + } }; + plain.parent.insert(id, parent); ids.push(id); } - for id in ids.clone() { - if c.album(id).is_some_and(|a| a.smart.is_some()) { - let pick = |rng: &mut Rng| ids[rng.next(ids.len() as u64) as usize]; - let rules = match rng.next(3) { - 0 => limited_to(pick(&mut rng)), - 1 => tests(&[(if rng.next(2) == 0 { "is" } else { "isNot" }, pick(&mut rng))]), - _ => tests(&[("is", pick(&mut rng)), ("isNot", pick(&mut rng))]), - }; - // unchecked, as an old library could hold them (a filter naming a smart album - // directly is the one thing `apply` itself refuses) - let _ = c.apply(Op::SetAlbumRules { id, rules: Box::new(rules) }); + let smart_ids: Vec = plain.asks.keys().copied().collect(); + for id in smart_ids { + let pick = |rng: &mut Rng| ids[rng.next(ids.len() as u64) as usize]; + let asks = match rng.next(4) { + 0 => Asks::Limited(pick(&mut rng)), + 1 => Asks::Rules { any: false, rules: vec![(rng.next(2) == 0, pick(&mut rng))] }, + 2 => Asks::Rules { any: false, rules: vec![(true, pick(&mut rng)), (false, pick(&mut rng))] }, + _ => Asks::Rules { any: true, rules: vec![(rng.next(2) == 0, pick(&mut rng)), (true, pick(&mut rng))] }, + }; + // unchecked, as an old library could hold them (a filter naming a smart album + // directly is the one thing `apply` itself refuses: those keep asking nothing) + if c.apply(Op::SetAlbumRules { id, rules: Box::new(asks.filter()) }).is_ok() { + plain.asks.insert(id, asks); } } - with_loops += usize::from(!c.albums_on_a_loop().is_empty()); - let table = |order: &[AlbumId]| -> Vec<(AlbumId, PhotoId, bool)> { - let mut t: Vec<(AlbumId, PhotoId, bool)> = Vec::new(); - for a in order { - for p in &photos { - t.push((*a, *p, holds(&c, *a, *p))); - } + let looping: std::collections::BTreeSet = plain.asks.keys().copied().filter(|a| plain.on_a_loop(*a)).collect(); + assert_eq!(c.albums_on_a_loop(), looping, "{}", c.to_snapshot()); + with_loops += usize::from(!looping.is_empty()); + through_folders += usize::from(looping.iter().any(|a| plain.asks[a].tested().iter().any(|t| plain.folders.contains(t)))); + let mut order = ids.clone(); + for round in 0..3 { + // forwards, backwards, then in a pass + if round == 1 { + order.reverse(); } - t.sort(); - t - }; - let forwards = table(&ids); - let mut reversed = ids.clone(); - reversed.reverse(); - assert_eq!(forwards, table(&reversed), "{}", c.to_snapshot()); - let in_a_pass = crate::gathering(|| table(&reversed)); - assert_eq!(forwards, in_a_pass, "{}", c.to_snapshot()); + let ask = || { + for a in &order { + for p in &photos { + assert_eq!(holds(&c, *a, *p), plain.holds(*a, *p), "album {a:?}, photo {p:?}, round {round}: {}", c.to_snapshot()); + } + } + }; + if round == 2 { crate::gathering(ask) } else { ask() } + } for a in &ids { - let want: Vec = forwards.iter().filter(|(x, _, yes)| x == a && *yes).map(|(_, p, _)| *p).collect(); - assert_eq!(c.album_photos(*a).into_iter().filter(|p| !c.photo(*p).unwrap().deleted).collect::>(), want, "{}", c.to_snapshot()); + let want: Vec = photos.iter().copied().filter(|p| plain.holds(*a, *p)).collect(); + assert_eq!(c.album_photos(*a), want, "{}", c.to_snapshot()); + assert_eq!(c.album_count(*a), want.len(), "{}", c.to_snapshot()); + // the ⚠ in the sidebar is on exactly the albums on a loop + let marked = c.smart_album_problems(*a).iter().any(|p| p.issue == crate::rules::Issue::AlbumLoop); + assert_eq!(marked, looping.contains(a), "album {a:?}: {}", c.to_snapshot()); } - for a in c.albums_on_a_loop() { - assert!(photos.iter().all(|p| !holds(&c, a, *p)), "on a loop, so empty: {}", c.to_snapshot()); + for p in &photos { + let want: Vec = { + let mut v: Vec = ids.iter().copied().filter(|a| !plain.folders.contains(a) && plain.holds(*a, *p)).collect(); + v.sort(); + v + }; + assert_eq!(c.albums_of(*p), want, "{}", c.to_snapshot()); } } - assert!(with_loops > 50, "the generator makes loops: {with_loops} of 300"); + assert!(with_loops > 100 && through_folders > 30, "the generator makes loops: {with_loops} of 400, {through_folders} through folders"); } /// `k` smart albums each limited to the folder they are all in, 200 photos: showing the folder @@ -212,8 +322,9 @@ fn a_folder_of_looping_albums_costs_in_proportion() { assert!(t40 < t10 * 20 + std::time::Duration::from_millis(2), "10 albums: {t10:?}; 40 albums: {t40:?}"); } -fn album_names(c: &Catalog) -> Vec<(AlbumId, Option, String)> { - c.albums().map(|a| (a.id, a.parent, serde_json::to_string(&a.smart).unwrap())).collect() +/// The whole library as saved (ids still to hand out included). +fn album_names(c: &Catalog) -> String { + c.to_snapshot() } #[test] @@ -256,8 +367,111 @@ fn a_new_edit_that_would_make_a_loop_is_refused() { let undo = c.apply_new(op.clone()).unwrap_or_else(|e| panic!("{op:?}: {e}")); assert!(c.albums_on_a_loop().is_empty()); c.apply(undo).unwrap(); - assert_eq!(album_names(&c), before); + // the albums are as they were (an id that was used is not handed out again) + let albums = |snapshot: &str| serde_json::from_str::(snapshot).unwrap()["albums"].clone(); + assert_eq!(albums(&album_names(&c)), albums(&before)); + } +} + +/// A refused edit names the album the edit was about, when that one is among those it would put +/// on a loop (two albums testing each other both end up on it). +#[test] +fn a_refusal_names_the_album_that_was_edited() { + let mut c = Catalog::new(); + let first = smart(&mut c, "First", None, Filter::default()); + let second = smart(&mut c, "Second", None, tests(&[("is", first)])); + let e = c.apply_new(Op::SetAlbumRules { id: first, rules: Box::new(tests(&[("is", second)])) }).unwrap_err().to_string(); + assert!(e.contains("First"), "{e}"); + let third = smart(&mut c, "Third", None, Filter::default()); + let e = c.apply_new(Op::SetAlbumRules { id: third, rules: Box::new(tests(&[("is", third)])) }).unwrap_err().to_string(); + assert!(e.contains("Third"), "{e}"); +} + +/// The check looks at what the edit would do before doing it, so there is nothing to take back: +/// an album whose saved rules `apply` itself would no longer take (limited to what has since +/// become a smart album's id) can't be left half-edited on a loop. +#[test] +fn a_refused_edit_never_touched_the_library() { + let mut c = Catalog::new(); + // T is limited to album 2 before there is one; then a smart album takes that id + let t = smart(&mut c, "T", None, limited_to(AlbumId(2))); + let u = smart(&mut c, "U", None, Filter { rating: 3, ..Default::default() }); + assert_eq!((t, u), (AlbumId(1), AlbumId(2))); + assert!(c.apply(Op::SetAlbumRules { id: t, rules: Box::new(limited_to(u)) }).is_err(), "T's own rules can't be set again"); + let (before, revision) = (c.to_snapshot(), c.revision); + let e = c.apply_new(Op::SetAlbumRules { id: t, rules: Box::new(tests(&[("is", t)])) }).unwrap_err().to_string(); + assert!(e.contains("include itself") && e.contains("“T”"), "{e}"); + assert_eq!(c.to_snapshot(), before); + assert_eq!(c.revision, revision, "not even looked at as changed"); + assert!(c.albums_on_a_loop().is_empty()); + // an album refused with an id of the caller's choosing leaves the ids to hand out alone + let chosen = + Op::AddAlbum { album: Album { parent: None, smart: Some(Box::new(tests(&[("is", AlbumId(500))]))), ..Album::new(AlbumId(500), "Chosen") } }; + assert!(c.apply_new(chosen).is_err()); + assert_eq!(c.to_snapshot(), before); + assert_eq!(c.alloc_album_id(), AlbumId(3)); +} + +/// A damaged library: a smart album whose folder is gone, limited to that folder's id. A folder +/// made with that id would take it in and close the loop. +#[test] +fn a_folder_that_would_adopt_a_looping_album_is_refused() { + let mut c = Catalog::new(); + let s = smart(&mut c, "Orphan", None, limited_to(AlbumId(2))); + c.albums.get_mut(&s).unwrap().parent = Some(AlbumId(2)); + let e = c.apply_new(Op::AddAlbum { album: Album { folder: true, ..Album::new(AlbumId(2), "Back") } }).unwrap_err().to_string(); + assert!(e.contains("Orphan"), "{e}"); + assert!(c.album(AlbumId(2)).is_none()); +} + +/// A damaged library: a folder that also carries rules is a folder, so it is on no loop and +/// carries no ⚠ for one. +#[test] +fn a_folder_with_rules_is_marked_as_it_is_treated() { + let mut c = Catalog::new(); + let f = folder(&mut c, "F", None); + c.albums.get_mut(&f).unwrap().smart = Some(Box::new(limited_to(f))); + assert!(c.albums_on_a_loop().is_empty()); + assert!(c.smart_album_problems(f).is_empty()); +} + +/// 300 folders, the smart album in each limited to the next folder (no loop): every edit of the +/// albums asks which of them are on a loop, and that looked through every album once per folder +/// per smart album (over a second). A drag has to stay a drag. +#[test] +fn asking_for_loops_in_a_long_chain_is_quick() { + let mut c = Catalog::new(); + let folders: Vec = (0..300).map(|i| folder(&mut c, &format!("F{i}"), None)).collect(); + for i in 0..1400 { + album(&mut c, &format!("A{i}"), Some(folders[i % 300]), &[]); } + let mut smarts = Vec::new(); + for i in 0..299 { + smarts.push(smart(&mut c, &format!("S{i}"), Some(folders[i]), limited_to(folders[i + 1]))); + } + let best = |f: &mut dyn FnMut()| { + (0..3) + .map(|_| { + let start = std::time::Instant::now(); + f(); + start.elapsed() + }) + .min() + .unwrap() + }; + let asked = best(&mut || assert!(c.albums_on_a_loop().is_empty())); + assert!(asked < std::time::Duration::from_millis(250), "albums_on_a_loop took {asked:?}"); + let loose = album(&mut c, "Loose", None, &[]); + let mut c2 = c.clone(); + let mut to = 0; + let moved = best(&mut || { + to += 1; + c2.apply_new(Op::MoveAlbum { id: loose, parent: Some(folders[to]) }).unwrap(); + }); + assert!(moved < std::time::Duration::from_millis(250), "a move took {moved:?}"); + // closing the chain is still seen + let e = c2.apply_new(Op::SetAlbumRules { id: smarts[0], rules: Box::new(limited_to(folders[0])) }); + assert!(e.is_err()); } #[test] From 7efa7c3b2379931600eb1561635147af25b1951a Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 10:50:44 -0400 Subject: [PATCH 21/24] LR-LIB-FOLDER: note the 32-deep limit of smart albums testing smart albums Co-Authored-By: Claude Opus 5.5 --- docs/parity-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 955cdd34777..a77d6c1feb6 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -95,7 +95,7 @@ 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`), `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; the catalog keeps the rule for every new edit (`Catalog::apply_new`), and a smart album already on a loop in an older library holds nothing, whichever is asked first; `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-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; the catalog keeps the rule for every new edit (`Catalog::apply_new`), and a smart album already on a loop in an older library holds nothing, whichever is asked first (known limit: smart albums that test each other more than 32 deep, with no loop, still count the deepest as empty); `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; 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 | From ddf5071e62b9becb14dd3c89ccc660d5b153d657 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 11:22:30 -0400 Subject: [PATCH 22/24] LR-LIB-FOLDER: which albums are on a loop is worked out once per change to the albums Second review. Evaluation asked each smart album whether it is on a loop with a search of its own, once per pass; the sidebar counts every album in a pass each, after every edit. With 300 folders whose smart albums are each limited to the next folder (no loop at all) one recount went from 0.12 s to about 15 s in the reviewer's measurement, and the albums of one photo from 41 ms to 3.7 s. The set is now kept by the catalog from the first question until an op changes the albums; the same recount is back under a second, and the loop rule's own check reads the set instead of building it again. A batch that fails part-way is taken back unchecked. Putting back rules is checked like setting them, so in a library whose saved rules the catalog would no longer take, the taking back failed silently and left the batch half applied (and, through that, a loop). Regression test for both. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 93 ++++++++++++------- .../catalog/src/tests_album_folder_photos.rs | 12 +-- crates/catalog/src/tests_album_loops.rs | 65 ++++++++++++- 3 files changed, 128 insertions(+), 42 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 4af77908434..135c8947642 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -294,6 +294,10 @@ pub struct Catalog { /// Lookups derived from the above (never saved), see [`index`]. #[serde(skip)] index: index::Indexes, + /// The smart albums on a loop, worked out when first asked and forgotten when an op changes + /// the albums ([`Self::albums_on_a_loop`]). + #[serde(skip)] + loops: LoopsMemo, } /// What of a photo an op changed: enough to tell which tallies of the library an edit leaves as they were (a @@ -452,7 +456,7 @@ impl Catalog { }, // one on a loop (it would include itself) holds nothing, whoever asks; the others // are guarded all the same, against chains too deep to follow - Some(Album { smart: Some(rules), .. }) => !self.album_is_on_a_loop(id, rules) && self.smart_album_has(id, rules, &rules.prepare_one(), p), + Some(Album { smart: Some(rules), .. }) => !self.album_is_on_a_loop(id) && self.smart_album_has(id, rules, &rules.prepare_one(), p), Some(a) => self.album_lists(a.id, p.id), None => false, } @@ -464,10 +468,25 @@ impl Catalog { !p.deleted && rules::smart_album_holds(id, p.id, || rules.matches_in(p, self, prepared)) } - /// Whether smart album `id` (with `rules`) would include itself: its rules lead back to it - /// ([`Self::album_reaches`]). Worked out once per album in a pass over the library. - fn album_is_on_a_loop(&self, id: AlbumId, rules: &Filter) -> bool { - on_a_loop(self, id, || !rules.albums_tested().is_empty() && self.album_reaches(id, id)) + /// Whether smart album `id` would include itself ([`Self::albums_on_a_loop`]). + fn album_is_on_a_loop(&self, id: AlbumId) -> bool { + self.looping().contains(&id) + } + + /// [`Self::albums_on_a_loop`], worked out once for the albums as they are: every photo of + /// every pass asks, and only an op that changes the albums gives another answer. + fn looping(&self) -> &std::collections::BTreeSet { + self.loops.0.get_or_init(|| self.album_graph().on_a_loop()) + } + + /// A damaged library, for tests: `change` an album as no op would, and forget what was + /// worked out from the albums as an op does. + #[cfg(test)] + pub(crate) fn damage(&mut self, id: AlbumId, change: impl FnOnce(&mut Album)) { + if let Some(album) = self.albums.get_mut(&id) { + change(album); + } + self.loops = LoopsMemo::default(); } /// What each album's photos depend on, for questions about many albums at once. @@ -479,7 +498,7 @@ impl Catalog { /// folders those are in. New edits can't make one ([`Self::apply_new`]); a library from before /// that rule, or a damaged one, may hold some, and each holds nothing. pub fn albums_on_a_loop(&self) -> std::collections::BTreeSet { - self.album_graph().on_a_loop() + self.looping().clone() } /// The albums and smart albums whose photos `id` shows: those inside a folder, at any depth @@ -609,7 +628,7 @@ impl Catalog { 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()), // one on a loop holds nothing - Some(Album { smart: Some(rules), .. }) if self.album_is_on_a_loop(id, rules) => Vec::new(), + Some(Album { smart: Some(_), .. }) if self.album_is_on_a_loop(id) => Vec::new(), Some(Album { smart: Some(rules), .. }) => { let prepared = rules.prepare(); gathering(|| self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).map(|p| p.id).collect()) @@ -623,7 +642,7 @@ impl Catalog { 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()), - Some(Album { smart: Some(rules), .. }) if self.album_is_on_a_loop(id, rules) => 0, + Some(Album { smart: Some(_), .. }) if self.album_is_on_a_loop(id) => 0, // counted in place: no id list is built just for its length Some(Album { smart: Some(rules), .. }) => { let prepared = rules.prepare(); @@ -732,9 +751,13 @@ impl Catalog { // the revision was set from outside: what is remembered is of another past self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() }; } + if changes_albums(&op) { + // also when the op fails: forgetting is always safe + self.loops = LoopsMemo::default(); + } let broad = self.changes.broad; self.changes.torn = false; - let inv = match self.apply_inner(op) { + let inv = match self.apply_inner(op, true) { Ok(inv) => inv, Err(e) => { let made = self.revision.saturating_add(1); @@ -790,14 +813,16 @@ impl Catalog { let mut after: BTreeMap = self.albums.values().map(|a| (a.id, a.outline())).collect(); let mut edited = Vec::new(); foresee(&mut after, op, &mut edited); - let now = self.albums_on_a_loop(); + let now = self.looping(); let then = AlbumGraph::of(after.values()).on_a_loop(); - let mut new = then.difference(&now); + let mut new = then.difference(now); let looping = edited.iter().find(|e| then.contains(e) && !now.contains(e)).or_else(|| new.next())?; Some(after.get(looping).map(|a| a.name.clone()).unwrap_or_default()) } - fn apply_inner(&mut self, op: Op) -> Result { + /// `checked`: rules an op sets are checked ([`Self::validate_rules`]); not when a failed batch + /// is taken back, where the rules put back are the ones that were there, whatever they are. + fn apply_inner(&mut self, op: Op, checked: bool) -> 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. @@ -936,7 +961,9 @@ impl Catalog { if album.folder || !album.photos.is_empty() { return Err(CatalogError::Invalid("a smart album holds rules, not photos".into())); } - self.validate_rules(rules)?; + if checked { + self.validate_rules(rules)?; + } } let id = album.id; self.next_album = self.next_album.max(id.0.saturating_add(1)); @@ -1005,7 +1032,9 @@ impl Catalog { Op::SetAlbumCover { id, cover: std::mem::replace(&mut a.cover, cover) } } Op::SetAlbumRules { id, rules } => { - self.validate_rules(&rules)?; + if checked { + self.validate_rules(&rules)?; + } let a = self.album_mut(id)?; let Some(old) = a.smart.as_mut() else { return Err(CatalogError::Invalid("not a smart album".into())); @@ -1132,12 +1161,12 @@ impl Catalog { Op::Batch { ops } => { let mut inverses = Vec::with_capacity(ops.len()); for op in ops { - match self.apply_inner(op) { + match self.apply_inner(op, checked) { Ok(inv) => inverses.push(inv), Err(e) => { - // roll back what was applied + // roll back what was applied (unchecked: what was there goes back) for inv in inverses.into_iter().rev() { - if self.apply_inner(inv).is_err() { + if self.apply_inner(inv, false).is_err() { self.changes.torn = true; } } @@ -1357,8 +1386,17 @@ thread_local! { struct Pass { /// The photos of the folders asked about. folders: std::collections::HashMap<(usize, AlbumId), std::rc::Rc>, - /// Whether each smart album asked about is on a loop ([`Catalog::albums_on_a_loop`]). - loops: std::collections::HashMap<(usize, AlbumId), bool>, +} + +/// [`Catalog::albums_on_a_loop`] as last worked out. No part of what a catalog is: two catalogs +/// are equal whatever each has worked out, and a copy starts with what its original knew. +#[derive(Clone, Debug, Default)] +struct LoopsMemo(std::sync::OnceLock>); + +impl PartialEq for LoopsMemo { + fn eq(&self, _: &LoopsMemo) -> bool { + true + } } thread_local! { @@ -1368,8 +1406,8 @@ thread_local! { /// Run `pass`, a question put to many photos (or many albums) 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, and each smart album is checked -/// for a loop once. Forgotten when the outermost pass ends, however it ends. +/// 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 { @@ -1401,19 +1439,6 @@ fn gathered(cat: &Catalog, id: AlbumId, gather: impl FnOnce() -> FolderPhotos) - Some(folder) } -/// Whether smart album `id` of `cat` is on a loop, by `search`: asked once per pass -/// ([`gathering`]), and every time outside one. -fn on_a_loop(cat: &Catalog, id: AlbumId, search: impl FnOnce() -> bool) -> bool { - let key = pass_key(cat, id); - if let Some(known) = PASS.with_borrow(|p| p.as_ref().and_then(|pass| pass.loops.get(&key).copied())) { - return known; - } - // searched with nothing borrowed, then kept - let looping = search(); - PASS.with_borrow_mut(|p| p.as_mut().map(|pass| pass.loops.insert(key, looping))); - looping -} - /// Whether `op` changes which album is in what or what tests what: it adds or removes an album, /// moves one, or changes rules (alone or in a batch). fn changes_albums(op: &Op) -> bool { diff --git a/crates/catalog/src/tests_album_folder_photos.rs b/crates/catalog/src/tests_album_folder_photos.rs index 44f70952742..782cafe4a66 100644 --- a/crates/catalog/src/tests_album_folder_photos.rs +++ b/crates/catalog/src/tests_album_folder_photos.rs @@ -177,13 +177,13 @@ fn folders_containing_each_other_still_answer() { 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); + c.damage(x, |a| a.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); + c.damage(x, |a| a.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 @@ -288,7 +288,7 @@ fn a_folder_with_rules_is_still_a_folder() { 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() })); + c.damage(f, |a| a.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)); @@ -327,11 +327,11 @@ fn an_album_inside_a_plain_album_is_not_in_the_folder() { 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); + c.damage(child, |a| a.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)); + c.damage(child, |a| a.parent = Some(AlbumId(999))); assert_eq!(c.album_members(f), [plain]); } @@ -343,7 +343,7 @@ fn moving_into_folders_that_contain_each_other_ends() { 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); + c.damage(x, |a| a.parent = Some(y)); let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { let _ = c.apply(Op::MoveAlbum { id: loose, parent: Some(y) }); diff --git a/crates/catalog/src/tests_album_loops.rs b/crates/catalog/src/tests_album_loops.rs index cef28257a42..8f67cec85d2 100644 --- a/crates/catalog/src/tests_album_loops.rs +++ b/crates/catalog/src/tests_album_loops.rs @@ -16,6 +16,11 @@ //! - When a new edit (adding a smart album, moving an album or folder, changing rules, alone or //! in a batch) would put a smart album on a loop, then it is refused, names the album, and //! nothing changed. +//! - Given a long chain of folders whose smart albums are each limited to the next folder (no +//! loop), then counting every album, as the sidebar does after each edit, takes what it took +//! before the rule: which albums are on a loop is worked out once per change to the albums. +//! - Given a batch of edits that fails part-way in a library whose saved rules the catalog +//! would no longer take, then everything is as it was: no rules half-changed, no loop left. //! - Given a library that already holds a loop, then it opens, the albums on the loop can still //! be edited and the loop undone, and edits elsewhere go through. @@ -418,7 +423,7 @@ fn a_refused_edit_never_touched_the_library() { fn a_folder_that_would_adopt_a_looping_album_is_refused() { let mut c = Catalog::new(); let s = smart(&mut c, "Orphan", None, limited_to(AlbumId(2))); - c.albums.get_mut(&s).unwrap().parent = Some(AlbumId(2)); + c.damage(s, |a| a.parent = Some(AlbumId(2))); let e = c.apply_new(Op::AddAlbum { album: Album { folder: true, ..Album::new(AlbumId(2), "Back") } }).unwrap_err().to_string(); assert!(e.contains("Orphan"), "{e}"); assert!(c.album(AlbumId(2)).is_none()); @@ -430,7 +435,7 @@ fn a_folder_that_would_adopt_a_looping_album_is_refused() { fn a_folder_with_rules_is_marked_as_it_is_treated() { let mut c = Catalog::new(); let f = folder(&mut c, "F", None); - c.albums.get_mut(&f).unwrap().smart = Some(Box::new(limited_to(f))); + c.damage(f, |a| a.smart = Some(Box::new(limited_to(f)))); assert!(c.albums_on_a_loop().is_empty()); assert!(c.smart_album_problems(f).is_empty()); } @@ -474,6 +479,62 @@ fn asking_for_loops_in_a_long_chain_is_quick() { assert!(e.is_err()); } +/// The sidebar counts every album after every edit. With 300 folders whose smart albums are +/// each limited to the next folder, asking each smart album along the way whether it is on a loop +/// made one recount take a quarter of a minute; it takes a fraction of a second. +#[test] +fn counting_every_album_of_a_long_chain_is_quick() { + let mut c = Catalog::new(); + let photos: Vec = (0..200).map(|i| photo(&mut c, &format!("p{i}.jpg"))).collect(); + let folders: Vec = (0..300).map(|i| folder(&mut c, &format!("F{i}"), None)).collect(); + for i in 0..1400 { + album(&mut c, &format!("A{i}"), Some(folders[i % 300]), &photos[i % 200..(i % 200 + 1)]); + } + let smarts: Vec = (0..299).map(|i| smart(&mut c, &format!("S{i}"), Some(folders[i]), limited_to(folders[i + 1]))).collect(); + let start = std::time::Instant::now(); + let total: usize = smarts.iter().map(|s| c.album_count(*s)).sum(); + let counted = start.elapsed(); + assert!(total > 0); + assert!(counted < std::time::Duration::from_secs(3), "one recount took {counted:?}"); + let start = std::time::Instant::now(); + for p in &photos[..5] { + assert!(!c.albums_of(*p).is_empty()); + } + let asked = start.elapsed(); + assert!(asked < std::time::Duration::from_secs(3), "the albums of five photos took {asked:?}"); + // an edit to the albums is seen at once: the chain closed (as an old library could hold it) + assert!(c.albums_on_a_loop().is_empty()); + c.apply(Op::SetAlbumRules { id: smarts[298], rules: Box::new(limited_to(folders[0])) }).unwrap(); + assert_eq!(c.albums_on_a_loop().len(), 299); + assert_eq!(c.album_count(smarts[0]), 0); + // and so is one taken back + c.apply(Op::SetAlbumRules { id: smarts[298], rules: Box::new(Filter::default()) }).unwrap(); + assert!(c.albums_on_a_loop().is_empty()); + assert!(c.album_count(smarts[0]) > 0); +} + +/// A batch that fails part-way is taken back whole, also where the rules it has to put back are +/// rules `apply` would no longer take as a new edit (T limited to what has since become a smart +/// album): taking back is not checked like an edit. Before, T kept its new rules and a loop. +#[test] +fn a_batch_that_fails_is_taken_back_whole() { + let mut c = Catalog::new(); + let t = smart(&mut c, "T", None, limited_to(AlbumId(2))); + let u = smart(&mut c, "U", None, Filter { rating: 3, ..Default::default() }); + let v = smart(&mut c, "V", None, tests(&[("is", t)])); + assert_eq!((t, u, v), (AlbumId(1), AlbumId(2), AlbumId(3))); + let (before, revision) = (c.to_snapshot(), c.revision); + let batch = || Op::Batch { + ops: vec![Op::SetAlbumRules { id: t, rules: Box::new(tests(&[("is", v)])) }, Op::RemoveAlbum { id: AlbumId(999) }, Op::RemoveAlbum { id: v }], + }; + for result in [c.apply_new(batch()), c.apply(batch())] { + assert!(result.unwrap_err().to_string().contains("999")); + assert_eq!(c.to_snapshot(), before); + assert_eq!(c.revision, revision); + assert!(c.albums_on_a_loop().is_empty()); + } +} + #[test] fn a_library_that_already_holds_a_loop_opens_and_can_be_mended() { // as written by a version without the rule: the op log makes a loop From 419aeb8fab2d350dc35666a76750bc2990baaa15 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 12:00:17 -0400 Subject: [PATCH 23/24] LR-LIB-FOLDER: the albums on a loop are found in one walk, not a search per smart album Third review. Every edit of the albums asks which are on a loop, and a search from each smart album grew with the square of a chain of folders: 15 ms per edit at 300 folders, 317 ms at 1,200 in the reviewer's measurement. One walk over the albums (Tarjan's strongly connected parts, with its own stack so a long chain can't overflow) grows with the chain. The random-library test checks the result against the definition written out separately. The failed-batch test is named for what it shows: rules are put back. Other checks a batch's taking back can run into in a damaged library are as before, and apply's comment says so. The wall-clock test counts fewer photos, for a wider margin, and a catalog's Debug no longer depends on what it worked out. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 87 ++++++++++++++++++++----- crates/catalog/src/tests_album_loops.rs | 54 +++++++++++++-- 2 files changed, 118 insertions(+), 23 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 135c8947642..222a59ea00f 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -746,6 +746,8 @@ impl Catalog { /// Apply an op; returns its inverse. On error the catalog is as it was, the revision included, and nothing is /// remembered of the op in what the latest ops touched. The one exception is a batch whose rollback fails: the /// catalog did change, so the revision advances and anything may be taken to have changed. + /// (In a damaged library, what a failed batch already did may not all go back, where putting + /// it back runs into a check other than the one on rules.) pub fn apply(&mut self, op: Op) -> Result { if self.changes.seen != self.revision { // the revision was set from outside: what is remembered is of another past @@ -1390,9 +1392,17 @@ struct Pass { /// [`Catalog::albums_on_a_loop`] as last worked out. No part of what a catalog is: two catalogs /// are equal whatever each has worked out, and a copy starts with what its original knew. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Default)] struct LoopsMemo(std::sync::OnceLock>); +/// Printed the same whether or not anything was worked out: a catalog's `Debug` is of what it +/// holds. +impl std::fmt::Debug for LoopsMemo { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("LoopsMemo") + } +} + impl PartialEq for LoopsMemo { fn eq(&self, _: &LoopsMemo) -> bool { true @@ -1514,25 +1524,70 @@ impl AlbumGraph { AlbumGraph { leads_to, testing } } - /// The smart albums that lead back to themselves. + /// The smart albums that lead back to themselves: those in a ring of albums leading to one + /// another (a strongly connected part of more than one album), or leading straight to + /// themselves. One walk over the albums (Tarjan's, with its own stack rather than recursion: + /// a chain of thousands of folders must not overflow), where a search from each smart album + /// grew with the square of a chain's length. fn on_a_loop(&self) -> std::collections::BTreeSet { - self.testing.iter().copied().filter(|a| self.reaches(*a, *a)).collect() - } - - fn reaches(&self, from: AlbumId, to: AlbumId) -> bool { - let none = Vec::new(); - let leads = |a: AlbumId| self.leads_to.get(&a).unwrap_or(&none); - let mut seen: std::collections::HashSet = std::collections::HashSet::new(); - let mut next: Vec = leads(from).clone(); - while let Some(a) = next.pop() { - if a == to { - return true; + // only what leads somewhere can be on a ring: number those albums + let ids: Vec = self.leads_to.keys().copied().collect(); + let number: std::collections::HashMap = ids.iter().enumerate().map(|(i, a)| (*a, i)).collect(); + let leads: Vec> = + ids.iter().map(|a| self.leads_to.get(a).into_iter().flatten().filter_map(|to| number.get(to).copied()).collect()).collect(); + const UNSEEN: usize = usize::MAX; + let n = ids.len(); + // when each was first reached, the earliest still-open album it leads back to, the open + // ones in the order reached, and whether each ended up on a ring + let (mut reached, mut back) = (vec![UNSEEN; n], vec![0usize; n]); + let (mut open, mut is_open, mut ringed) = (Vec::new(), vec![false; n], vec![false; n]); + let mut clock = 0usize; + for root in 0..n { + if reached[root] != UNSEEN { + continue; } - if seen.insert(a) { - next.extend(leads(a)); + // (album, how many of its leads were followed) + let mut walk: Vec<(usize, usize)> = vec![(root, 0)]; + while let Some(&(v, followed)) = walk.last() { + if followed == 0 && reached[v] == UNSEEN { + reached[v] = clock; + back[v] = clock; + clock += 1; + open.push(v); + is_open[v] = true; + } + if let Some(&w) = leads[v].get(followed) { + if let Some(top) = walk.last_mut() { + top.1 += 1; + } + if reached[w] == UNSEEN { + walk.push((w, 0)); + } else if is_open[w] { + back[v] = back[v].min(reached[w]); + } + continue; + } + // every lead of `v` followed: it closes, and with it the ring it is the first of + walk.pop(); + if let Some(&(parent, _)) = walk.last() { + back[parent] = back[parent].min(back[v]); + } + if back[v] == reached[v] { + let mut ring = Vec::new(); + while let Some(w) = open.pop() { + is_open[w] = false; + ring.push(w); + if w == v { + break; + } + } + if ring.len() > 1 || leads[v].contains(&v) { + ring.into_iter().for_each(|w| ringed[w] = true); + } + } } } - false + self.testing.iter().copied().filter(|a| number.get(a).is_some_and(|i| ringed[*i])).collect() } } diff --git a/crates/catalog/src/tests_album_loops.rs b/crates/catalog/src/tests_album_loops.rs index 8f67cec85d2..ac1fefec886 100644 --- a/crates/catalog/src/tests_album_loops.rs +++ b/crates/catalog/src/tests_album_loops.rs @@ -20,7 +20,9 @@ //! loop), then counting every album, as the sidebar does after each edit, takes what it took //! before the rule: which albums are on a loop is worked out once per change to the albums. //! - Given a batch of edits that fails part-way in a library whose saved rules the catalog -//! would no longer take, then everything is as it was: no rules half-changed, no loop left. +//! would no longer take, then the rules are as they were: none half-changed, no loop left. +//! - Given a chain of folders four times as long, then asking which albums are on a loop takes +//! about four times as long, not sixteen. //! - Given a library that already holds a loop, then it opens, the albums on the loop can still //! be edited and the loop undone, and edits elsewhere go through. @@ -479,16 +481,52 @@ fn asking_for_loops_in_a_long_chain_is_quick() { assert!(e.is_err()); } +/// Every edit of the albums asks which are on a loop. One search per smart album made that grow +/// with the square of a chain's length (four times the chain: sixteen times the wait, a third of +/// a second per drag at 1,200 folders); one walk over the albums grows with the chain. +#[test] +fn asking_for_loops_grows_with_the_chain_not_its_square() { + let chain = |n: usize| { + let mut c = Catalog::new(); + let folders: Vec = (0..n).map(|i| folder(&mut c, &format!("F{i}"), None)).collect(); + for i in 0..n - 1 { + smart(&mut c, &format!("S{i}"), Some(folders[i]), limited_to(folders[i + 1])); + } + c + }; + let asked = |c: &Catalog| { + (0..5) + .map(|_| { + // a copy that has worked nothing out yet + let fresh = Catalog::from_snapshot(&c.to_snapshot()).unwrap(); + let start = std::time::Instant::now(); + assert!(fresh.albums_on_a_loop().is_empty()); + start.elapsed() + }) + .min() + .unwrap() + }; + let (short, long) = (asked(&chain(300)), asked(&chain(1200))); + assert!(long < short * 8 + std::time::Duration::from_millis(2), "300 folders: {short:?}; 1,200 folders: {long:?}"); + // the chain closed is one loop of all of them + let mut c = chain(300); + let last = c.albums().filter(|a| a.folder).map(|a| a.id).max().unwrap(); + let first = c.albums().filter(|a| a.folder).map(|a| a.id).min().unwrap(); + smart(&mut c, "Closing", Some(last), limited_to(first)); + assert_eq!(c.albums_on_a_loop().len(), 300); +} + /// The sidebar counts every album after every edit. With 300 folders whose smart albums are /// each limited to the next folder, asking each smart album along the way whether it is on a loop /// made one recount take a quarter of a minute; it takes a fraction of a second. #[test] fn counting_every_album_of_a_long_chain_is_quick() { let mut c = Catalog::new(); - let photos: Vec = (0..200).map(|i| photo(&mut c, &format!("p{i}.jpg"))).collect(); + // few photos: counting them is not what is measured, and the clock gets a wide margin + let photos: Vec = (0..40).map(|i| photo(&mut c, &format!("p{i}.jpg"))).collect(); let folders: Vec = (0..300).map(|i| folder(&mut c, &format!("F{i}"), None)).collect(); for i in 0..1400 { - album(&mut c, &format!("A{i}"), Some(folders[i % 300]), &photos[i % 200..(i % 200 + 1)]); + album(&mut c, &format!("A{i}"), Some(folders[i % 300]), &photos[i % 40..(i % 40 + 1)]); } let smarts: Vec = (0..299).map(|i| smart(&mut c, &format!("S{i}"), Some(folders[i]), limited_to(folders[i + 1]))).collect(); let start = std::time::Instant::now(); @@ -513,11 +551,13 @@ fn counting_every_album_of_a_long_chain_is_quick() { assert!(c.album_count(smarts[0]) > 0); } -/// A batch that fails part-way is taken back whole, also where the rules it has to put back are -/// rules `apply` would no longer take as a new edit (T limited to what has since become a smart -/// album): taking back is not checked like an edit. Before, T kept its new rules and a loop. +/// A batch that fails part-way puts back the rules it changed, also where those are rules `apply` +/// would no longer take as a new edit (T limited to what has since become a smart album): putting +/// rules back is not checked like setting them. Before, T kept its new rules and a loop. (Other +/// things a batch may have to put back in a damaged library, a rating out of range or an album +/// whose folder is gone, are still checked, and still stay half applied: not this test's.) #[test] -fn a_batch_that_fails_is_taken_back_whole() { +fn a_failed_batch_puts_back_rules_the_catalog_would_no_longer_take() { let mut c = Catalog::new(); let t = smart(&mut c, "T", None, limited_to(AlbumId(2))); let u = smart(&mut c, "U", None, Filter { rating: 3, ..Default::default() }); From afa4a732b7d6160504430c8bd962fb65aabda90a Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 19 Oct 2026 16:35:15 -0400 Subject: [PATCH 24/24] LR-LIB-FOLDER: a loop search reads the album tree once, not once per folder The search lists what is inside each folder from one children index, built when the first folder is reached. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 44 +++++++++++++++--- crates/catalog/src/tests_album_loops.rs | 60 +++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 5 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 222a59ea00f..c6a97b9f995 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -547,7 +547,8 @@ impl Catalog { /// 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) + let contents = std::cell::OnceCell::new(); + self.album_search(self.album_leads_to(from, &contents), |a| a == to) } /// Whether a smart album with `rules` would include itself if it were in folder `parent`: its @@ -569,11 +570,43 @@ impl Catalog { .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))) } + /// What is directly inside each folder, in one pass over the albums: for a search that walks + /// down several folders. + fn folder_contents(&self) -> std::collections::HashMap> { + let mut map: std::collections::HashMap> = std::collections::HashMap::new(); + for a in self.albums.values() { + if let Some(p) = a.parent.filter(|p| self.albums.get(p).is_some_and(|f| f.folder)) { + map.entry(p).or_default().push(a.id); + } + } + map + } + /// 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 { + /// inside a folder. `contents` is [`Self::folder_contents`], worked out when first needed. + fn album_leads_to(&self, a: AlbumId, contents: &std::cell::OnceCell>>) -> Vec { match self.albums.get(&a) { - Some(al) if al.folder => self.album_members(a), + Some(al) if al.folder => { + let contents = contents.get_or_init(|| self.folder_contents()); + // as `album_members`, walking down the folders (each once: a ring ends the walk) + let mut inside = Vec::new(); + let mut seen = std::collections::HashSet::from([a]); + let mut folders = vec![a]; + while let Some(f) = folders.pop() { + for &m in contents.get(&f).map(Vec::as_slice).unwrap_or_default() { + match self.albums.get(&m) { + Some(member) if member.folder => { + if seen.insert(m) { + folders.push(m); + } + } + Some(_) => inside.push(m), + None => {} + } + } + } + inside + } Some(al) => al.smart.as_deref().map(Filter::albums_tested).unwrap_or_default(), None => Vec::new(), } @@ -583,6 +616,7 @@ impl Catalog { /// ([`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 contents = std::cell::OnceCell::new(); let mut next = start; while let Some(a) = next.pop() { if !seen.insert(a) { @@ -591,7 +625,7 @@ impl Catalog { if found(a) { return true; } - next.extend(self.album_leads_to(a)); + next.extend(self.album_leads_to(a, &contents)); } false } diff --git a/crates/catalog/src/tests_album_loops.rs b/crates/catalog/src/tests_album_loops.rs index ac1fefec886..e2d59f6bd2b 100644 --- a/crates/catalog/src/tests_album_loops.rs +++ b/crates/catalog/src/tests_album_loops.rs @@ -442,6 +442,66 @@ fn a_folder_with_rules_is_marked_as_it_is_treated() { assert!(c.smart_album_problems(f).is_empty()); } +/// What a loop search reads inside a folder is what the folder shows: albums at any depth, no +/// folders, nothing under a parent that is no folder or is gone, and a ring of folders ends. +#[test] +fn a_loop_search_walks_folders_as_the_folder_shows() { + let mut c = Catalog::new(); + let (a, b) = (folder(&mut c, "A", None), folder(&mut c, "B", None)); + let (c1, c2) = (folder(&mut c, "C1", Some(b)), folder(&mut c, "C2", Some(b))); + let deep = folder(&mut c, "Deep", Some(c1)); + let (x, y, z) = (album(&mut c, "X", Some(deep), &[]), album(&mut c, "Y", Some(c2), &[]), album(&mut c, "Z", Some(a), &[])); + let plain = album(&mut c, "Plain", None, &[]); + let under_plain = album(&mut c, "Under", None, &[]); + c.damage(under_plain, |al| al.parent = Some(plain)); + let orphan = album(&mut c, "Orphan", None, &[]); + c.damage(orphan, |al| al.parent = Some(AlbumId(999))); + let tested_by_s = smart(&mut c, "S", None, tests(&[("is", x)])); + let reaches = |c: &Catalog| { + let all: Vec = c.albums().map(|al| al.id).collect(); + all.iter().flat_map(|&f| all.iter().map(move |&t| (f, t))).filter(|&(f, t)| c.album_reaches(f, t)).collect::>() + }; + // as the search read it before: through `album_members` + let by_members = |c: &Catalog| { + let all: Vec = c.albums().map(|al| al.id).collect(); + let mut found = Vec::new(); + for &f in &all { + let mut seen = std::collections::HashSet::new(); + let mut next = match c.album(f) { + Some(al) if al.folder => c.album_members(f), + Some(al) => al.smart.as_deref().map(Filter::albums_tested).unwrap_or_default(), + None => Vec::new(), + }; + while let Some(t) = next.pop() { + if !seen.insert(t) { + continue; + } + found.push((f, t)); + match c.album(t) { + Some(al) if al.folder => next.extend(c.album_members(t)), + Some(al) => next.extend(al.smart.as_deref().map(Filter::albums_tested).unwrap_or_default()), + None => {} + } + } + } + found + }; + let sorted = |mut v: Vec<(AlbumId, AlbumId)>| { + v.sort(); + v + }; + assert_eq!(sorted(reaches(&c)), sorted(by_members(&c))); + assert!(c.album_reaches(b, x) && c.album_reaches(b, y) && !c.album_reaches(a, x) && c.album_reaches(a, z)); + assert!(!c.album_reaches(plain, under_plain) && !c.album_reaches(AlbumId(999), x)); + assert!(c.album_reaches(tested_by_s, x) && !c.album_reaches(tested_by_s, y)); + // a ring of folders, and a folder that is its own parent + c.damage(b, |al| al.parent = Some(deep)); + assert_eq!(sorted(reaches(&c)), sorted(by_members(&c))); + c.damage(a, |al| al.parent = Some(a)); + assert_eq!(sorted(reaches(&c)), sorted(by_members(&c))); + assert!(c.album_reaches(b, x) && c.album_reaches(a, z)); +} + /// 300 folders, the smart album in each limited to the next folder (no loop): every edit of the /// albums asks which of them are on a loop, and that looked through every album once per folder /// per smart album (over a second). A drag has to stay a drag.