From 9ca0d4d5e9310cc2b87fe105b00b69696d08c54b Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 09:05:02 -0400 Subject: [PATCH 01/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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] {