From 73b9cc3708d822bfe2d09dc1f2b2281453f13bb9 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 13 Oct 2026 19:30:39 -0400 Subject: [PATCH 1/2] LR-LIB-SMARTALBUM: a view can hold its photos until it is refreshed A view is asked again after every edit, so a photo that an edit makes stop matching it leaves the grid at once and every photo after it moves up: a keyword given in a smart album of photos without keywords takes the photo away from under the cursor, and in a random order, with no landmarks, the shift reads as a new shuffle (the seed does not change). View > Hold View Until Refreshed (`library.holdView`, off by default, kept with the library's preferences): a photo the view shows stays in it when an edit makes it stop matching a smart album's rules, Picks or the filter bar. View > Refresh View (`library.refresh`, also in the sort menu while the hold is on), Reshuffle, another source, filter or sort, or new rules for the smart album shown, shows what matches now. - Photos that start matching still appear at once. - A photo that is deleted, or taken out of the album or folder shown, still leaves at once: a held photo has to be where the view looks (`Catalog::query_keeping`, `within`). - A source with no filter over it holds nothing and is queried as before. - A refresh keeps the seed. - The grid's count no longer reads "3 of 2" when a held view shows more than now match its source. Each edit still asks the whole library again; that cost is not addressed here. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/query.rs | 15 +- crates/engine/src/cmd/library.rs | 38 +++++ crates/engine/src/lib.rs | 82 ++++++++-- crates/engine/src/library.rs | 5 + crates/engine/src/tests_hold_view.rs | 200 +++++++++++++++++++++++++ crates/engine/src/tests_library.rs | 24 +++ crates/ui-egui/locales/de.json | 2 + crates/ui-egui/locales/es.json | 2 + crates/ui-egui/locales/fr.json | 2 + crates/ui-egui/locales/ja.json | 2 + crates/ui-egui/locales/pt-br.json | 2 + crates/ui-egui/locales/ru.json | 2 + crates/ui-egui/locales/uk.json | 2 + crates/ui-egui/locales/zh-hans.json | 2 + crates/ui-egui/locales/zh-hant.json | 2 + crates/ui-egui/src/menubar.rs | 14 ++ crates/ui-egui/src/panels/bottombar.rs | 8 + crates/ui-egui/src/panels/chips.rs | 3 +- docs/parity-checklist.md | 5 +- docs/whats-new.md | 9 ++ 20 files changed, 405 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/tests_hold_view.rs diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index a9956703dc5..a9aa66b7fad 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -369,8 +369,21 @@ pub fn cmp_name(a: &str, b: &str) -> std::cmp::Ordering { impl Catalog { /// Photos matching `filter`, in `sort` order (ties broken by file name, then id). pub fn query(&self, filter: &Filter, sort: &Sort) -> Vec { + self.query_keeping(filter, sort, &std::collections::HashSet::new(), filter) + } + + /// [`Catalog::query`], and with them the photos of `keep` that still match `within`, each at its place in `sort` + /// order: a view that holds the photos it showed when an edit makes them stop matching `filter` (a smart + /// album's rules, the filter bar), as long as they are still where the view looks (`within`: in the library, + /// the album, the folder; not deleted). + pub fn query_keeping(&self, filter: &Filter, sort: &Sort, keep: &std::collections::HashSet, within: &Filter) -> Vec { let root = filter.library_root(); - let mut v: Vec<&Photo> = self.photos().map(|p| p.as_ref()).filter(|p| filter.matches_in(p, self, root.as_deref())).collect(); + let within_root = within.library_root(); + let mut v: Vec<&Photo> = self + .photos() + .map(|p| p.as_ref()) + .filter(|p| filter.matches_in(p, self, root.as_deref()) || (keep.contains(&p.id) && within.matches_in(p, self, within_root.as_deref()))) + .collect(); v.sort_by(|a, b| { let o = match sort.key { SortKey::CaptureDate => a.captured.cmp(&b.captured).then_with(|| a.imported.cmp(&b.imported)), diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 3a5575ea81a..910091648a1 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -510,6 +510,44 @@ pub fn specs() -> Vec { ok() } ), + cmd!( + "library.refresh", + "Refresh View", + ["View"], + None, + "{} — show what matches now: a view that holds its photos (`library.holdView`) lets go of the ones that stopped matching a smart album's rules, Picks or the filter bar since it was opened, sorted or last refreshed", + always, + |s, _| { + s.refresh_view(); + ok() + } + ), + cmd!( + "library.holdView", + "Hold View Until Refreshed", + ["View"], + None, + "{on?: bool (toggles when omitted)} → {hold} — when on, an edit that makes a photo stop matching the view (a keyword given in a smart album of photos without keywords, a flag taken off in Picks, a rating under the filter bar's) keeps it in the view until `library.refresh`, Reshuffle, or another source, filter or sort; photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder shown still takes it out of the view. Changing a smart album's rules is another view too. Off (the default): the view follows every edit. Kept with the library's preferences; asking for the state it already has changes nothing", + always, + |s, p| { + let on = match p.get("on") { + None | Some(Value::Null) => !s.hold_view, + Some(Value::Bool(on)) => *on, + Some(_) => return Err(bad("library.holdView", "on must be true or false")), + }; + if on != s.hold_view { + let was = s.hold_view; + s.hold_view = on; + if let Err(e) = s.save_prefs() { + // not kept: not changed either, so asking again does what was asked + s.hold_view = was; + return Err(e); + } + s.refresh_view(); + } + Ok(json!({"hold": s.hold_view})) + } + ), cmd!( "library.shuffle", "Reshuffle", diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7e05fcffd1e..c1f1c093170 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -190,6 +190,13 @@ pub struct Session { /// Shared, so frontends can hold it across frames without copying ([`Session::visible_shared`]). visible: Arc<[PhotoId]>, visible_key: Option<(u64, String)>, + /// A view holds the photos it shows until it is refreshed (`library.holdView`): an edit that makes a photo stop + /// matching a smart album's rules, Picks or the filter bar leaves it where it is. Off: the photo goes at once. + pub hold_view: bool, + /// The view that is held and the photos in it, before stacks are arranged ([`Session::hold_view`]). Another + /// source, filter or sort is another view, and starts from what matches; so does a smart album whose rules + /// were changed. `None` for a view that nothing can stop matching (a source with no filter over it). + held: Option<(String, Vec)>, /// Identifies the current `visible` list: a new value (unique in the process) every time it /// is recomputed, so frontends can key their per-view caches on it instead of hashing the ids. visible_gen: u64, @@ -345,6 +352,8 @@ impl Session { selection: Selection::default(), visible: Vec::new().into(), visible_key: None, + hold_view: false, + held: None, visible_gen: 0, total: None, undo: Vec::new(), @@ -853,6 +862,16 @@ impl Session { pub fn visible(&mut self) -> &[PhotoId] { let mut key = (self.catalog.revision, format!("{:?}|{:?}|{:?}|{:?}|{:?}", self.source, self.filter, self.sort, self.browse, self.library_folder)); + // What a held view is told apart by: what is shown and how, and for a smart album its rules (rules that were + // changed ask something else). Not the checks of Missing Photos below: they fill the view in, they are + // no other view. + let asks = matches!(self.source, LibrarySource::Picks) + || matches!(self.source, LibrarySource::Album(a) if self.catalog.album(a).is_some_and(|al| al.is_smart())); + let rules = match self.source { + LibrarySource::Album(a) if asks => self.catalog.album(a).map(|al| format!("{:?}", al.smart)).unwrap_or_default(), + _ => String::new(), + }; + let view = format!("{}|{rules}", key.1); if self.source == LibrarySource::Missing && self.media.availability.is_background() { // the view fills in as the background checks find files gone key.1.push_str(&format!("|{}", self.media.availability.generation())); @@ -860,18 +879,33 @@ impl Session { if self.visible_key.as_ref() != Some(&key) { // "in the last N days" rules count back from the session's clock lightcraft_catalog::rules::set_now(Some((self.clock)())); - let mut f = self.source.to_filter(&self.filter, &self.catalog); - if self.source == LibrarySource::Folder { - // no folder chosen: nothing (an empty path matches nothing) - let b = self.browse.clone().unwrap_or_default(); - f.folder = Some(b.path); - f.subfolders = b.subfolders; - } - if self.source == LibrarySource::LibraryFolder { - // no folder chosen: nothing (`.` names no folder) - f.library_folder = Some(self.library_folder.clone().unwrap_or_else(|| ".".into())); - } - let mut visible = self.catalog.query(&f, &self.sort); + let f = self.view_filter(self.source, &self.filter); + // A held view keeps the photos it shows that stopped matching what is asked of them (a smart album's + // rules, a flag, the filter bar), as long as they are still where the view looks: in the library for + // a view that is only a question, else in the album or folder shown. Taking a photo out of an album + // or the library takes it out of the view at once, held or not. + // (only a view that asks something can lose a photo to an edit: the others are queried as ever, at no + // cost for the hold) + let holds = self.hold_view && (asks || self.filter != Filter::default()); + let held = self.held.as_ref().filter(|(held, _)| holds && *held == view).map(|(_, ids)| ids); + let mut visible = match held { + Some(ids) => { + let keep: std::collections::HashSet = ids.iter().copied().collect(); + let within = if asks { + self.view_filter(LibrarySource::All, &Filter::default()) + } else if self.source == LibrarySource::RecentlyAdded { + // (how far back it reaches was worked out for `f`: not a second pass over the library) + Filter { imported_from: f.imported_from.clone(), ..Default::default() } + } else { + self.view_filter(self.source, &Filter::default()) + }; + self.catalog.query_keeping(&f, &self.sort, &keep, &within) + } + None => self.catalog.query(&f, &self.sort), + }; + // what the view shows now is what it holds until it is refreshed (taken before stacks are arranged, so + // a photo folded into a stack is held with it) + self.held = holds.then(|| (view, visible.clone())); if visible.is_empty() && self.source == LibrarySource::LibraryFolder && !self.folder_holds_photos() { // the shown folder lost its last photo (deleted, moved, removed): everything, not // an empty grid under the name of a folder that is gone from the sidebar @@ -921,6 +955,28 @@ impl Session { &self.visible } + /// `source` as a filter over `base` (the filter bar's, or none), with the folder it shows. + fn view_filter(&self, source: LibrarySource, base: &Filter) -> Filter { + let mut f = source.to_filter(base, &self.catalog); + if source == LibrarySource::Folder { + // no folder chosen: nothing (an empty path matches nothing) + let b = self.browse.clone().unwrap_or_default(); + f.folder = Some(b.path); + f.subfolders = b.subfolders; + } + if source == LibrarySource::LibraryFolder { + // no folder chosen: nothing (`.` names no folder) + f.library_folder = Some(self.library_folder.clone().unwrap_or_else(|| ".".into())); + } + f + } + + /// Let go of what a held view kept: the view shows what matches now ([`Session::hold_view`]). + pub fn refresh_view(&mut self) { + self.held = None; + self.visible_key = None; + } + /// Whether the library still holds a photo imported from the folder a `LibraryFolder` source /// shows. fn folder_holds_photos(&self) -> bool { @@ -1022,6 +1078,8 @@ mod tests_forget_local; #[cfg(test)] mod tests_history_cursor; #[cfg(test)] +mod tests_hold_view; +#[cfg(test)] mod tests_import; #[cfg(test)] mod tests_import_move; diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 0305623f2a4..be6fab1dd16 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -232,6 +232,8 @@ struct PrefsFile { /// Days after which untouched Local records of unbrowsed folders are forgotten (missing = /// the default, 0 = never). forget_local_days: Option, + /// A view holds the photos it shows until it is refreshed (`library.holdView`). + hold_view: bool, } fn presets_json(s: &Session) -> String { @@ -455,6 +457,8 @@ impl Session { self.import_defaults = prefs.import; self.cache_mb = prefs.cache_mb; self.forget_local_days = prefs.forget_local_days.unwrap_or(lightcraft_catalog::DEFAULT_FORGET_DAYS); + self.hold_view = prefs.hold_view; + self.refresh_view(); self.smart_previews_dir = prefs.smart_previews_dir.filter(|_| on_disk).map(PathBuf::from); if let Some(d) = &self.smart_previews_dir { self.media.smart_dir = Some(d.clone()); @@ -699,6 +703,7 @@ impl Session { cache_mb: self.cache_mb, smart_previews_dir: self.smart_previews_dir.as_ref().map(|d| d.to_string_lossy().to_string()), forget_local_days: Some(self.forget_local_days), + hold_view: self.hold_view, }) .unwrap_or_default(); let Some(lib) = self.library.as_mut() else { return Ok(()) }; diff --git a/crates/engine/src/tests_hold_view.rs b/crates/engine/src/tests_hold_view.rs new file mode 100644 index 00000000000..3bb998b8cf8 --- /dev/null +++ b/crates/engine/src/tests_hold_view.rs @@ -0,0 +1,200 @@ +//! A view holds the photos it shows until it is refreshed (`library.holdView`): an edit that makes a photo stop +//! matching a smart album's rules, Picks or the filter bar leaves it where it is, and the others where they are. + +use lightcraft_catalog::PhotoId; +use serde_json::json; + +use crate::{LibrarySource, Session}; + +/// The demo library with no photo keyworded, showing a smart album of the photos without keywords, at random. +fn unkeyworded() -> Session { + let mut s = Session::with_demo(); + let all: Vec = s.visible_cloned().iter().map(|p| p.0).collect(); + s.execute("photo.setMeta", &json!({"ids": all, "keywords": []})).unwrap(); + let rules = json!({"ruleSet": {"match": "all", "rules": [{"field": "keywordCount", "op": "is", "value": 0}]}}); + let album = s.execute("album.createSmart", &json!({"name": "Unkeyworded", "rules": rules})).unwrap()["id"].as_u64().unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": album})).unwrap(); + s.execute("library.sort", &json!({"key": "random"})).unwrap(); + s +} + +fn hold(s: &mut Session) { + assert_eq!(s.execute("library.holdView", &json!({"on": true})).unwrap()["hold"], true); +} + +fn keyword(s: &mut Session, id: PhotoId) { + s.execute("photo.setMeta", &json!({"ids": [id.0], "addKeywords": ["travel"]})).unwrap(); +} + +#[test] +fn a_keyword_given_in_a_held_view_leaves_the_photo_and_the_order_where_they_are() { + // Given a smart album of the photos without keywords, at random, held + let mut s = unkeyworded(); + hold(&mut s); + let (before, seed) = (s.visible_cloned(), s.sort.seed); + assert!(before.len() > 10); + // When photos in it are given a keyword, one after the other + for at in [3, 7, 0] { + keyword(&mut s, before[at]); + // Then nothing moves: the same photos in the same places, under the same shuffle + assert_eq!(s.visible_cloned(), before, "after a keyword on the photo at {at}"); + assert_eq!(s.sort.seed, seed); + } + // When the view is refreshed, Then they are gone and the others keep their order + s.execute("library.refresh", &json!({})).unwrap(); + let after = s.visible_cloned(); + let expected: Vec = before.iter().copied().filter(|id| ![before[3], before[7], before[0]].contains(id)).collect(); + assert_eq!(after, expected); + assert_eq!(s.sort.seed, seed, "a refresh is not a reshuffle"); +} + +#[test] +fn a_view_that_is_not_held_follows_every_edit_as_before() { + let mut s = unkeyworded(); + assert!(!s.hold_view, "off unless asked for"); + let before = s.visible_cloned(); + keyword(&mut s, before[3]); + let after = s.visible_cloned(); + assert!(!after.contains(&before[3]), "the photo leaves at once"); + assert_eq!(after, before.iter().copied().filter(|id| *id != before[3]).collect::>(), "the others keep their order"); +} + +#[test] +fn a_held_view_still_takes_in_what_starts_matching_and_lets_go_of_what_is_deleted() { + let mut s = unkeyworded(); + let all = s.visible_cloned(); + // one photo has a keyword before the view is held: it is not in it + keyword(&mut s, all[5]); + hold(&mut s); + let before = s.visible_cloned(); + assert!(!before.contains(&all[5])); + // its keyword taken off again: it matches, and comes in at its place in the shuffle + s.execute("photo.setMeta", &json!({"ids": [all[5].0], "keywords": []})).unwrap(); + assert_eq!(s.visible_cloned(), all, "back where the shuffle puts it"); + // a photo that was kept after it stopped matching, then deleted, is not kept in the view + keyword(&mut s, all[2]); + assert!(s.visible_cloned().contains(&all[2])); + s.execute("library.select", &json!({"ids": [all[2].0]})).unwrap(); + s.execute("photo.delete", &json!({})).unwrap(); + assert!(!s.visible_cloned().contains(&all[2]), "Recently Deleted is somewhere else"); +} + +#[test] +fn another_source_filter_sort_or_shuffle_is_another_view() { + let mut s = unkeyworded(); + hold(&mut s); + let before = s.visible_cloned(); + // Reshuffle: a new order of what matches now + keyword(&mut s, before[1]); + assert!(s.visible_cloned().contains(&before[1])); + s.execute("library.shuffle", &json!({})).unwrap(); + assert!(!s.visible_cloned().contains(&before[1]), "a reshuffle refreshes"); + // another sort + let now = s.visible_cloned(); + keyword(&mut s, now[1]); + s.execute("library.sort", &json!({"key": "fileName"})).unwrap(); + assert!(!s.visible_cloned().contains(&now[1]), "another sort refreshes"); + // the filter bar + let now = s.visible_cloned(); + keyword(&mut s, now[1]); + s.execute("library.filter", &json!({"rating": 0, "text": "a"})).unwrap(); + assert!(!s.visible_cloned().contains(&now[1]), "another filter refreshes"); + s.execute("library.filter", &json!({"text": ""})).unwrap(); + // away and back + let now = s.visible_cloned(); + let source = s.source; + keyword(&mut s, now[1]); + s.execute("library.source", &json!({"kind": "all"})).unwrap(); + let _ = s.visible_cloned(); + s.source = source; + assert!(!s.visible_cloned().contains(&now[1]), "coming back to it refreshes"); +} + +#[test] +fn picks_and_the_filter_bar_hold_too_and_an_album_lets_go_of_what_is_taken_out_of_it() { + let mut s = Session::with_demo(); + let all = s.visible_cloned(); + // Picks + s.execute("library.select", &json!({"ids": [all[0].0, all[1].0, all[2].0]})).unwrap(); + s.execute("photo.flag", &json!({"flag": "pick"})).unwrap(); + s.execute("library.source", &json!({"kind": "picks"})).unwrap(); + hold(&mut s); + let picks = s.visible_cloned(); + assert!(picks.len() >= 3, "{picks:?}"); + s.execute("library.select", &json!({"ids": [picks[1].0]})).unwrap(); + s.execute("photo.flag", &json!({"flag": "none"})).unwrap(); + assert_eq!(s.visible_cloned(), picks, "a pick unflagged stays until the view is refreshed"); + s.execute("library.refresh", &json!({})).unwrap(); + assert_eq!(s.visible_cloned(), picks.iter().copied().filter(|id| *id != picks[1]).collect::>()); + // the filter bar over an album: a rating under the filter's stays, a photo taken out of the album goes + let album = s.execute("album.create", &json!({"name": "Trip"})).unwrap()["id"].as_u64().unwrap(); + let ids: Vec = all.iter().take(5).map(|p| p.0).collect(); + s.execute("library.select", &json!({"ids": ids})).unwrap(); + s.execute("photo.rate", &json!({"rating": 4})).unwrap(); + s.execute("album.addPhotos", &json!({"id": album, "ids": ids})).unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": album})).unwrap(); + s.execute("library.filter", &json!({"rating": 3})).unwrap(); + let shown = s.visible_cloned(); + assert_eq!(shown.len(), 5); + s.execute("library.select", &json!({"ids": [shown[0].0]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 1})).unwrap(); + assert_eq!(s.visible_cloned().len(), 5, "rated under the filter: held"); + s.execute("album.removePhotos", &json!({"id": album, "ids": [shown[0].0, shown[1].0]})).unwrap(); + let left = s.visible_cloned(); + assert!(!left.contains(&shown[0]) && !left.contains(&shown[1]), "out of the album is out of the view: {left:?}"); + assert_eq!(left.len(), 3); + assert_eq!(s.source, LibrarySource::Album(lightcraft_catalog::AlbumId(album))); +} + +#[test] +fn turning_the_hold_off_lets_go_at_once() { + let mut s = unkeyworded(); + hold(&mut s); + let before = s.visible_cloned(); + keyword(&mut s, before[4]); + assert!(s.visible_cloned().contains(&before[4])); + assert_eq!(s.execute("library.holdView", &json!({})).unwrap()["hold"], false, "toggles without `on`"); + assert!(!s.visible_cloned().contains(&before[4])); +} + +#[test] +fn changing_the_rules_of_the_smart_album_shown_is_another_view() { + let mut s = unkeyworded(); + hold(&mut s); + let before = s.visible_cloned(); + let LibrarySource::Album(album) = s.source else { panic!("a smart album is shown") }; + // the album now asks for photos with a keyword: none has one, and none is kept from what it asked before + let rules = json!({"ruleSet": {"match": "all", "rules": [{"field": "keywordCount", "op": "gt", "value": 0}]}}); + s.execute("album.setRules", &json!({"id": album.0, "rules": rules})).unwrap(); + assert!(s.visible_cloned().is_empty(), "the old rules' photos are not held under the new ones"); + // and undoing the change brings the first question back, with what matches it + s.undo_step().unwrap(); + assert_eq!(s.visible_cloned(), before); +} + +#[test] +fn a_source_with_no_filter_over_it_holds_nothing() { + // All Photos, an album or a folder with no filter: nothing an edit does can make a photo stop matching, so + // nothing is kept (and nothing is paid for the hold) + let mut s = Session::with_demo(); + hold(&mut s); + let all = s.visible_cloned(); + keyword(&mut s, all[0]); + assert_eq!(s.visible_cloned(), all); + assert!(s.held.is_none()); + s.execute("library.filter", &json!({"rating": 1})).unwrap(); + let _ = s.visible_cloned(); + assert!(s.held.is_some(), "a filter is a question: its view is held"); +} + +#[test] +fn asking_for_the_state_it_has_changes_nothing_and_a_word_is_not_a_bool() { + let mut s = unkeyworded(); + hold(&mut s); + let before = s.visible_cloned(); + keyword(&mut s, before[2]); + hold(&mut s); + assert!(s.visible_cloned().contains(&before[2]), "on, asked for again: the held photos stay"); + assert!(s.execute("library.holdView", &json!({"on": "false"})).is_err()); + assert!(s.hold_view, "a refused call changes nothing"); +} diff --git a/crates/engine/src/tests_library.rs b/crates/engine/src/tests_library.rs index 8a2599e5ca4..131049d13e8 100644 --- a/crates/engine/src/tests_library.rs +++ b/crates/engine/src/tests_library.rs @@ -675,3 +675,27 @@ fn an_album_filter_loop_is_refused() { assert!(r.is_err_and(|e| e.to_string().contains("include itself")), "refused"); assert_eq!(s.catalog.album(lightcraft_catalog::AlbumId(a)).unwrap().smart.as_ref().and_then(|f| f.album), None); } + +#[test] +fn the_hold_of_the_view_is_kept_with_the_library_and_holds_nothing_over_from_another() { + let dir = temp_dir("holdview"); + let mut s = open(&dir, true); + assert!(!s.hold_view, "off in a library that never asked for it"); + s.execute("library.holdView", &json!({"on": true})).unwrap(); + // a filter over the demo photos, and one of them edited out from under it: held + s.execute("library.filter", &json!({"rating": 0, "flag": "none"})).unwrap(); + let shown = s.visible_cloned(); + let id = *shown.first().expect("the seeded library has unflagged photos"); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("photo.flag", &json!({"flag": "pick"})).unwrap(); + assert!(s.visible_cloned().contains(&id)); + s.close_library().unwrap(); + drop(s); + // opened again: the hold is on, and what was held is not (a library opens on what matches) + let mut s = open(&dir, false); + assert!(s.hold_view); + s.execute("library.filter", &json!({"rating": 0, "flag": "none"})).unwrap(); + assert!(!s.visible_cloned().contains(&id)); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 25c411ce0e0..a38116ab2b4 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -581,6 +581,7 @@ "Friday": "Freitag", "Full": "Vollständig", "Full Screen Preview": "Vollbildvorschau", + "Hold View Until Refreshed": "Ansicht bis zum Aktualisieren beibehalten", "Lights Out": "Licht aus", "Full screen mode": "Vollbildmodus", "Full size": "Volle Größe", @@ -1173,6 +1174,7 @@ "Refining the mask's detail…": "Maskendetails werden verfeinert…", "Refresh Source": "Quelle aktualisieren", "Refresh Source (/)": "Quelle aktualisieren (/)", + "Refresh View": "Ansicht aktualisieren", "Reject": "Ablehnen", "Reject below focus": "Unter Schärfegrenzwert ablehnen", "Rejected": "Abgelehnt", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index ba3e1e33165..aee0b24e1a2 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -563,6 +563,7 @@ "Friday": "Viernes", "Full": "Completa", "Full Screen Preview": "Vista previa a pantalla completa", + "Hold View Until Refreshed": "Mantener vista hasta actualizar", "Lights Out": "Luces apagadas", "Full screen mode": "Modo de pantalla completa", "Full size": "Tamaño completo", @@ -1145,6 +1146,7 @@ "Refining the mask's detail…": "Refinando el detalle de la máscara…", "Refresh Source": "Actualizar origen", "Refresh Source (/)": "Actualizar origen (/)", + "Refresh View": "Actualizar vista", "Reject": "Rechazar", "Reject below focus": "Rechazar por debajo del enfoque", "Rejected": "Rechazada", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index b0becb154e4..d9c05f1bfc7 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -545,6 +545,7 @@ "Friday": "Vendredi", "Full": "Complet", "Full Screen Preview": "Aperçu en plein écran", + "Hold View Until Refreshed": "Conserver la vue jusqu’à l’actualisation", "Lights Out": "Lumières éteintes", "Full screen mode": "Mode plein écran", "Full size": "Taille complète", @@ -1119,6 +1120,7 @@ "Refining the mask's detail…": "Affinage du détail du masque…", "Refresh Source": "Actualiser la source", "Refresh Source (/)": "Actualiser la source (/)", + "Refresh View": "Actualiser la vue", "Reject": "Rejeter", "Reject below focus": "Rejeter en dessous de la netteté", "Rejected": "Rejetée", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 7a282e676e4..5ec9e8bdcd3 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -509,6 +509,7 @@ "Has Edits": "編集", "Has GPS": "GPS情報", "High Contrast B&W": "ハイコントラスト白黒", + "Hold View Until Refreshed": "更新するまで表示を保持", "Home": "ホーム", "Horizontal inset (% of short edge)": "水平方向の余白(短辺に対する%)", "Hours": "時間", @@ -684,6 +685,7 @@ "Refine Saturation": "彩度を微調整", "Refining the mask's detail…": "マスクの細部を微調整中…", "Refresh Source": "コピー元を更新", + "Refresh View": "表示を更新", "Reject": "不採用", "Reliability": "信頼性", "Relink Photo": "写真の参照先を再設定", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index f8e4753e5ce..44a4910afdd 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -554,6 +554,7 @@ "Friday": "Sexta-feira", "Full": "Completa", "Full Screen Preview": "Pré-visualização em tela cheia", + "Hold View Until Refreshed": "Manter visualização até atualizar", "Lights Out": "Luzes apagadas", "Full screen mode": "Modo tela cheia", "Full size": "Tamanho completo", @@ -1137,6 +1138,7 @@ "Refining the mask's detail…": "Refinando os detalhes da máscara…", "Refresh Source": "Atualizar origem", "Refresh Source (/)": "Atualizar origem (/)", + "Refresh View": "Atualizar visualização", "Reject": "Rejeitar", "Reject below focus": "Rejeitar abaixo do foco", "Rejected": "Rejeitada", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index c840218a039..2a9f1037938 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -455,6 +455,7 @@ "Friday": "Пятница", "Full": "Полный", "Full Screen Preview": "Полноэкранный просмотр", + "Hold View Until Refreshed": "Удерживать вид до обновления", "Lights Out": "Выключить свет", "Full screen mode": "Полноэкранный режим", "Full size": "Полный размер", @@ -942,6 +943,7 @@ "Refine Mask Edges": "Уточнить края маски", "Refresh Source": "Обновить источник", "Refresh Source (/)": "Обновить источник (/)", + "Refresh View": "Обновить вид", "Reject": "Отклонить", "Reject below focus": "Отклонять при недостаточной резкости", "Rejected": "Отклонено", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 85a83809806..5d79898d5ad 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -96,6 +96,7 @@ "Focal Length": "Фокусна відстань", "Grab bag": "Випадкова добірка", "Group name": "Назва групи", + "Hold View Until Refreshed": "Утримувати вигляд до оновлення", "Home": "Домашня тека", "Horizontal inset (% of short edge)": "Відступ по горизонталі (% короткого краю)", "ISO Speed": "Чутливість ISO", @@ -233,6 +234,7 @@ "Red": "Червоний", "Red Eye": "Червоні очі", "Redo": "Повторити", + "Refresh View": "Оновити вигляд", "Remove": "Видалити", "Rename": "Перейменувати", "Rename…": "Перейменувати…", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ad379f1ef3c..5c0bc09018c 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -515,6 +515,7 @@ "HDR panoramas": "HDR 全景", "Has Edits": "有编辑", "Has GPS": "有 GPS", + "Hold View Until Refreshed": "刷新前保持视图", "Home": "主文件夹", "Horizontal inset (% of short edge)": "水平边距 (占短边 %)", "Hours": "小时", @@ -631,6 +632,7 @@ "Refine Edges": "细化边缘", "Refine Saturation": "细化饱和度", "Refining the mask's detail…": "正在细化蒙版细节…", + "Refresh View": "刷新视图", "Reliability": "可靠性", "Relink Photo": "重新链接照片", "Reload Changed Files": "重新载入已更改的文件", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 647d153d0a7..863d4d3cd9c 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -515,6 +515,7 @@ "HDR panoramas": "HDR 全景", "Has Edits": "有編輯", "Has GPS": "有 GPS", + "Hold View Until Refreshed": "重新整理前保持檢視", "Home": "個人資料夾", "Horizontal inset (% of short edge)": "水平邊距(短邊百分比)", "Hours": "小時", @@ -631,6 +632,7 @@ "Refine Edges": "調整邊緣", "Refine Saturation": "調整飽和度", "Refining the mask's detail…": "正在調整遮色片細節…", + "Refresh View": "重新整理檢視", "Reliability": "可靠度", "Relink Photo": "重新連結照片", "Reload Changed Files": "重新載入已變更的檔案", diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index fe6905cadbc..78996f40921 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -167,6 +167,8 @@ const LAYOUT: &[(&str, &[&str])] = &[ "@Stacks", "view.filterBar", "library.clearFilter", + "library.refresh", + "library.holdView", "---", "compare.swap", "compare.makeSelect", @@ -329,6 +331,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { "view.autoAdvance" => Some(u.auto_advance), "view.filterBar" => Some(u.filter_bar), "view.navigator" => Some(u.navigator), + "library.holdView" => Some(app.session.hold_view), "view.fullScreenPreview" => Some(u.fullscreen), "view.lightsOut" => Some(u.lights_out != crate::state::LightsOut::On), "view.enterFullScreen" => Some(app.window_is_fullscreen), @@ -987,6 +990,17 @@ mod tests { }) } + #[test] + fn view_menu_offers_the_hold_and_the_refresh_and_checks_the_hold_while_it_is_on() { + let mut a = app(); + let view = |a: &LightcraftApp| menu_bar(a).into_iter().find(|(t, _)| t == "View").expect("View menu").1; + let items = view(&a); + assert!(matches!(find(&items, "library.refresh"), Some(MenuNode::Item { enabled: true, .. }))); + assert!(matches!(find(&items, "library.holdView"), Some(MenuNode::Item { checked: Some(false), .. })), "off unless asked for"); + a.session.execute("library.holdView", &json!({"on": true})).expect("hold the view"); + assert!(matches!(find(&view(&a), "library.holdView"), Some(MenuNode::Item { checked: Some(true), .. }))); + } + /// The Sort submenu is expanded by hand: Reshuffle appears once (not again from the registry), /// only while sorting at random, and the direction items are off for a shuffle. #[test] diff --git a/crates/ui-egui/src/panels/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rs index b986b8995e5..4872378da7b 100644 --- a/crates/ui-egui/src/panels/bottombar.rs +++ b/crates/ui-egui/src/panels/bottombar.rs @@ -272,6 +272,14 @@ fn sort_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { if cur.key == Random && ui.button(crate::i18n::tr("Reshuffle")).clicked() { let _ = app.run("library.shuffle", json!({})); } + // a view that holds its photos shows what matches now when asked to + if app.session.hold_view { + let r = ui.button(crate::i18n::tr("Refresh View")); + crate::widgets::register(ui.ctx(), "button:refreshView", r.rect); + if r.clicked() { + let _ = app.run("library.refresh", json!({})); + } + } ui.separator(); // a shuffle has no direction worth choosing ui.add_enabled_ui(cur.key != Random, |ui| { diff --git a/crates/ui-egui/src/panels/chips.rs b/crates/ui-egui/src/panels/chips.rs index d1acd15a591..510931a51db 100644 --- a/crates/ui-egui/src/panels/chips.rs +++ b/crates/ui-egui/src/panels/chips.rs @@ -18,7 +18,8 @@ const TAIL: f32 = 170.0; /// "14 of 120 photos" when a filter narrows the source, else "14 photos". pub fn count_text(matching: usize, total: Option, filtering: bool) -> String { match total { - Some(t) if filtering && t != matching => crate::i18n::tr_format!("{matching} of {t} photos", matching = matching, t = t), + // (a held view can show more than now match its source: no "3 of 2") + Some(t) if filtering && t > matching => crate::i18n::tr_format!("{matching} of {t} photos", matching = matching, t = t), _ => crate::i18n::tr_format!("{matching} photos", matching = matching), } } diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 7bb187811c1..02416ec1a8d 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (integration batch 35: KEYC-SELECTONLYACTIVE, Select Only Active Photo ⌘⇧D; LR-BEHAV-AUTOSAVE, damaged snapshots repaired on open; LR-EDIT-OPTICS-PROFILE, Nikon Z 6II / Z 8 / Z f in-file distortion; LRC-LIB-CATALOG-IMPORT, WAL-only catalogs open; LR-EXP-DIM, enlargements stop at 512 MP; LR-IMP-CAMERA-COVERAGE, Canon EOS RP CR3 verified; model folder retry) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (integration batch 35: KEYC-SELECTONLYACTIVE, Select Only Active Photo ⌘⇧D; LR-BEHAV-AUTOSAVE, damaged snapshots repaired on open; LR-EDIT-OPTICS-PROFILE, Nikon Z 6II / Z 8 / Z f in-file distortion; LRC-LIB-CATALOG-IMPORT, WAL-only catalogs open; LR-EXP-DIM, enlargements stop at 512 MP; LR-IMP-CAMERA-COVERAGE, Canon EOS RP CR3 verified; model folder retry; LR-LIB-SMARTALBUM: a view can hold its photos until refreshed) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -96,7 +96,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-BYDATE | Browse by date | P1 | ✅ | `cmd:library.filter` (`date`), `crates/ui-egui/src/panels/left.rs` (`date_row`), `crates/catalog/src/query.rs` (`date_groups`) | year → month → day tree with library-wide counts; a row filters the current source by that date. Active filters show as removable chips under the grid header (`crates/ui-egui/src/panels/chips.rs`, with “+N more” and Clear all), the header counts “N of M photos” (matching of the source's total), a badge on the top-bar filter icon counts them, and an empty result says no photos match the active filters | | LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests_albums_local.rs`, `crates/ui-egui/src/tests_panels.rs` | photos dragged from the grid onto an album row are added to it (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder) | | LR-LIB-FOLDER | Folders of albums | P0 | ✅ | `cmd:album.create` (`folder`, `parent`), `cmd:album.move`, `cmd:album.reorder`, `cmd:album.sort`, `cmd:dialog.newAlbum` / `cmd:dialog.newFolder` / `cmd:dialog.smartAlbum` / `cmd:dialog.newSmartAlbum` (`parent`), `crates/ui-egui/src/panels/left.rs` (`albums_tree`, `folder_menu`, `disclosure_triangle`), `crates/ui-egui/src/tests_panels.rs` | Delete removes a folder and its nested albums as one undoable edit, keeps photos in the library and returns a deleted album view to All Photos (issue #501); folders nest and fold with the same disclosure triangle as Local / By Date / Folders / Keywords (`albumToggle:`; the row folds them too; open by default); right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder… creates inside it (the `dialog.new*` commands take `parent`), opening the folders down to the new row; creating is only allowed inside folders; moving: drag an album or folder row onto a folder (outlined when allowed; a closed folder opens after 0.6 s under the pointer; the "Albums" header takes an item that sits in a folder back to the top level while it is dragged), the Move to menu or `album.move` — one undo step each; not onto a plain album, itself or something inside it; drop on the top / bottom half of an album or the edge of a folder to place it there by hand (`cmd:album.reorder`, a line shows the place; ordered per folder, folders stay first, new albums go after the ordered ones; right-click ▸ Sort Contents A–Z or + ▸ Sort Albums A–Z = `cmd:album.sort`) | -| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `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; sidebar counts are cached per catalog revision (and per minute while an “in the last…” rule is used), counted without building id lists | +| 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; sidebar counts are cached per catalog revision (and per minute while an “in the last…” rule is used), counted without building id lists; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort | | LR-LIB-SHARED-ALBUM | Shared albums | P2 | ⬜ | | needs a sharing service | | LR-LIB-OFFLINE | Keep album offline | P2 | 🚫 | | not applicable: local-first library | | LR-LIB-TARGET | Target album | P2 | ✅ | `cmd:album.setTarget`, `cmd:album.toggleTarget` | see LRC-LIB-COLLECTIONS | @@ -822,4 +822,5 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-11 | minor | LR-IMP-FORMATS and LR-IMP-CAMERA-COVERAGE: EOS R5 Mark II CR3 decodes from sensor data (57% of its C-RAW files opened as a preview: QP-map escape); status unchanged (🟡) | | 2026-10-10 | patch | LR-BEHAV-UNDO: file/XMP repair retries and merged rename Undo/Redo evidence; status and summary counts unchanged. | | 2026-10-10 | minor | Renamed from `parity.md` (progress-docs standard); Top gaps moved to gaps.md (its duplicated items 1–2 from a bad merge resolved there), shortcut notes moved to ui-parity.md. Rows unchanged; a recount of the rows gives 81.1% of 517 in-scope rows (P0 98.0%, P1 95.1%, P2 46.9%), so the generated summary above is due a `cargo xtask parity --write` | +| 2026-10-13 | minor | LR-LIB-SMARTALBUM: `cmd:library.holdView` and `cmd:library.refresh`: a view can hold the photos it shows until it is refreshed; status unchanged (✅) | | 2026-09-30 – 2026-10-11 | — | Rows added and updated with each feature (see `git log -- docs/parity.md docs/parity-checklist.md`) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 1bf44c3f4ef..a46a67a729d 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -8,6 +8,15 @@ ## 2026-10-13 +### A view can hold its photos until you refresh it +- View ▸ Hold View Until Refreshed (off unless you turn it on; kept with the library). With it on, an edit that makes + a photo stop matching the view keeps it in the view: a keyword given in a smart album of photos without keywords, + a flag taken off in Picks, a rating that falls under the filter bar's. With it off, as before, the photo leaves the + grid at once and every photo after it moves up. View ▸ Refresh View (also in the sort menu while the hold is on), + Reshuffle, another source, filter or sort, or new rules for the smart album shows what matches now. +- Photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder + shown still takes it out of the view. + ### HDR merges keep the lens correction - An HDR made with Photo ▸ Photo Merge ▸ HDR now keeps the lens correction the photos carry (Sony's, Panasonic's and Leica's, and the one some DNGs carry, e.g. from drones): Optics ▸ Enable Lens Corrections straightens it as it From 5f1037a19205b147808ad747004b22f582ffcb91 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 13 Oct 2026 20:24:41 -0400 Subject: [PATCH 2/2] PERF-EDIT: an edit is followed from what it touched, not worked out from every photo Everything derived from the catalog was keyed on its revision, which every op raises. So each edit (a keyword, a rating, every tick of a slider) had the grid's list queried and sorted again from every photo, the source counted by a second full query, and the side panels tally the whole library again. In a library of 67,000 photos the frame after one keyword took about 156 ms with both side panels open (an idle frame: 2 ms). The catalog now remembers which photos its latest ops touched and what of them they changed (`Catalog::touched_since`, `aspects_since`, `Aspects`). It answers "not known" for an op that changes more than photos of its own (an album, a stack, the keyword list), for changes too long ago, and for a revision it did not make itself (a library just loaded). - The view (`Session::visible`): when the same view is asked again after a small edit, the photos the edit touched are taken out of the list it had, asked about again, and put back at their place in the order (`Catalog::follow`). 37 ms -> 0.6 ms. Worked out whole as before: more than 256 photos touched, a change that is not photos' own, an album in its own order, Recently Added, Missing Photos, and a view that asks about "the last N days" (it changes with the clock too). - The source's count: taken from the list when no filter is set, else counted without sorting (`Catalog::count`). 37 ms -> 0. - The side panels (`Caches`): the folder tree, keyword tree, date groups, people's names and library counts are kept through an edit that changed nothing they read. A rating or a slider changes none; a keyword leaves the folders, dates and counts. The frame after a keyword: about 156 ms -> 54 ms with both side panels open, 71 ms -> 2 ms with the grid alone (`tests_view_cost.rs`, a synthetic library, run with --ignored --nocapture). Still paid on each edit: the count beside every album and smart album in the left panel (about 25 ms for a smart album there), and the filter bar's lists. Tests: 1,440 random edits of every photo-local kind across sources, sorts, filters and the hold, each compared with the list worked out whole; 600 random edits comparing every kept tally with a fresh one; the clock; the record itself, with its failure paths. `ui.inspect` -> `perf` reports `viewFollowed` and `viewWorkedOut`. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 155 +++++++++++++++++ crates/catalog/src/query.rs | 66 ++++++-- crates/catalog/src/tests.rs | 78 +++++++++ crates/engine/src/lib.rs | 116 ++++++++++--- crates/engine/src/library.rs | 2 + crates/engine/src/tests_hold_view.rs | 8 +- crates/engine/src/tests_view_follow.rs | 221 +++++++++++++++++++++++++ crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/lib.rs | 70 ++++---- crates/ui-egui/src/tests_tallies.rs | 149 +++++++++++++++++ crates/ui-egui/src/tests_view_cost.rs | 155 +++++++++++++++++ docs/whats-new.md | 14 ++ 12 files changed, 957 insertions(+), 79 deletions(-) create mode 100644 crates/engine/src/tests_view_follow.rs create mode 100644 crates/ui-egui/src/tests_tallies.rs create mode 100644 crates/ui-egui/src/tests_view_cost.rs diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index ed4cb75b410..aa2f5745bf7 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -281,6 +281,71 @@ pub struct Catalog { /// Increments on every applied op. #[serde(skip)] pub revision: u64, + /// Which photos the latest ops touched ([`Catalog::touched_since`]). + #[serde(skip)] + changes: Changes, +} + +/// What of a photo an op changed: enough to tell which tallies of the library an edit leaves as they were (a +/// rating changes no folder's count; a slider changes none at all). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Aspects(u16); + +impl Aspects { + pub const NONE: Aspects = Aspects(0); + pub const RATING: Aspects = Aspects(1); + pub const FLAG: Aspects = Aspects(1 << 1); + pub const LABEL: Aspects = Aspects(1 << 2); + /// Develop settings, versions and history. + pub const DEVELOP: Aspects = Aspects(1 << 3); + /// Title, caption, keywords, people, place and the rest of the metadata. + pub const META: Aspects = Aspects(1 << 4); + pub const CAPTURED: Aspects = Aspects(1 << 5); + /// Where its file is. + pub const FILE: Aspects = Aspects(1 << 6); + pub const ANALYSIS: Aspects = Aspects(1 << 7); + /// Whether it is in the library at all: added, removed, deleted, restored, taken in from Local. + pub const PRESENCE: Aspects = Aspects(1 << 8); + /// Everything: the photo may count differently for any tally. + pub const ALL: Aspects = Aspects(u16::MAX); + + pub const fn with(self, other: Aspects) -> Aspects { + Aspects(self.0 | other.0) + } + + /// Whether any of `other` is among these. + pub const fn any_of(self, other: Aspects) -> bool { + self.0 & other.0 != 0 + } +} + +/// The most photos remembered as touched; older changes are then answered with "anything may have changed". +const MAX_TOUCHED: usize = 8192; + +/// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can +/// follow a small edit without being worked out again from every photo. +#[derive(Clone, Debug, Default)] +struct Changes { + /// The photos ops changed, each with the revision the op made and what of the photo it changed. Oldest first. + touched: std::collections::VecDeque<(u64, PhotoId, Aspects)>, + /// What the op being applied changes of its photo. + now: Aspects, + /// The latest revision made by an op that changed more than photos of its own (an album, a stack, a keyword of + /// the list…): what it changed for which photos is not known. + broad: u64, + /// Changes up to this revision are no longer all in `touched`. + floor: u64, + /// The revision the last op recorded here made. When the catalog's revision is another, it was set from + /// outside (a library just loaded takes a range of its own, so that nothing kept from another library is + /// taken for this one's): nothing is known of how the catalog got to where it is. + seen: u64, +} + +impl PartialEq for Changes { + /// Two catalogs are the same catalog whatever each remembers of how it got there. + fn eq(&self, _: &Self) -> bool { + true + } } impl Catalog { @@ -479,20 +544,110 @@ impl Catalog { // ---- writes fn photo_mut(&mut self, id: PhotoId) -> Result<&mut Photo> { + self.touch(id); self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id)) } + + /// The op being applied changes photo `id` (or adds or removes it). + fn touch(&mut self, id: PhotoId) { + // (the revision the op will make: `apply` counts up once it is done) + self.changes.touched.push_back((self.revision.saturating_add(1), id, self.changes.now)); + while self.changes.touched.len() > MAX_TOUCHED { + if let Some((revision, _, _)) = self.changes.touched.pop_front() { + self.changes.floor = revision; + } + } + } + + /// What of its photos the ops since `revision` changed, taken together ([`Aspects::NONE`] when there were + /// none). `None` when that is not known ([`Catalog::touched_since`]). A tally of the library that reads only + /// other things of a photo is still right. + pub fn aspects_since(&self, revision: u64) -> Option { + if !self.remembers(revision) { + return None; + } + Some(self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a))) + } + + /// Whether every change since the catalog was at `revision` is remembered photo by photo. + fn remembers(&self, revision: u64) -> bool { + self.changes.seen == self.revision && revision <= self.revision && revision >= self.changes.floor && self.changes.broad <= revision + } + + /// The photos changed, added or removed since the catalog was at `revision`, each once. `None` when that is not + /// known: an op since then changed more than photos of its own, or it was too long ago. Then anything may + /// have changed. + pub fn touched_since(&self, revision: u64) -> Option> { + if !self.remembers(revision) { + return None; + } + let mut ids: Vec = self.changes.touched.iter().filter(|(r, _, _)| *r > revision).map(|(_, id, _)| *id).collect(); + ids.sort_unstable(); + ids.dedup(); + Some(ids) + } fn album_mut(&mut self, id: AlbumId) -> Result<&mut Album> { self.albums.get_mut(&id).ok_or(CatalogError::NoAlbum(id)) } /// Apply an op; returns its inverse. On error nothing changes. pub fn apply(&mut self, op: Op) -> Result { + if self.changes.seen != self.revision { + // the revision was set from outside: what is remembered is of another past + self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() }; + } let inv = self.apply_inner(op)?; self.revision += 1; + self.changes.seen = self.revision; Ok(inv) } fn apply_inner(&mut self, op: Op) -> Result { + // An op that changes one photo says which (`photo_mut`, and adding or removing it below). Every other kind + // can change what any photo matches or where it sorts: an album's photos or rules, a stack, a keyword's + // name. Listed kind by kind, so a new one has to be put on one side. + match &op { + // (a photo that comes, goes, or changes what it is to the library counts for every tally; so do the + // rare kinds whose reach nobody has to think about) + Op::AddPhoto { photo } => { + self.changes.now = Aspects::ALL; + self.touch(photo.id); + } + Op::RemovePhoto { id } => { + self.changes.now = Aspects::ALL; + self.touch(*id); + } + Op::SetDeleted { .. } | Op::SetLocal { .. } | Op::SetContent { .. } | Op::SetEmbeddedLens { .. } | Op::SetAsShotWb { .. } => { + self.changes.now = Aspects::ALL + } + Op::SetRating { .. } => self.changes.now = Aspects::RATING, + Op::SetFlag { .. } => self.changes.now = Aspects::FLAG, + Op::SetLabel { .. } => self.changes.now = Aspects::LABEL, + Op::SetMeta { .. } => self.changes.now = Aspects::META, + Op::SetCaptured { .. } => self.changes.now = Aspects::CAPTURED, + Op::SetFile { .. } | Op::Relink { .. } => self.changes.now = Aspects::FILE, + Op::SetAnalysis { .. } => self.changes.now = Aspects::ANALYSIS, + Op::SetDevelop { .. } | Op::SetVersions { .. } | Op::SetHistory { .. } | Op::PushHistory { .. } | Op::SetHistoryCursor { .. } => { + self.changes.now = Aspects::DEVELOP + } + // (its ops say for themselves, one by one) + Op::Batch { .. } => {} + Op::AddAlbum { .. } + | Op::RemoveAlbum { .. } + | Op::RenameAlbum { .. } + | Op::MoveAlbum { .. } + | Op::SetAlbumOrder { .. } + | Op::SetAlbumPhotos { .. } + | Op::SetAlbumCover { .. } + | Op::SetAlbumRules { .. } + | Op::AddStack { .. } + | Op::RemoveStack { .. } + | Op::SetStack { .. } + | Op::SetLabelName { .. } + | Op::SetBrowsed { .. } + | Op::SetKeyword { .. } + | Op::SetFolderRecord { .. } => self.changes.broad = self.revision.saturating_add(1), + } Ok(match op { Op::AddPhoto { photo } => { if self.photos.contains_key(&photo.id) { diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index a9aa66b7fad..eba2a0a7495 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -94,6 +94,27 @@ pub struct Sort { pub seed: u64, } +impl Sort { + /// Which of two photos comes first in this order (never `Equal` for two photos: the id decides last). + pub fn order(&self, a: &Photo, b: &Photo) -> std::cmp::Ordering { + let o = match self.key { + SortKey::CaptureDate => a.captured.cmp(&b.captured).then_with(|| a.imported.cmp(&b.imported)), + SortKey::ImportDate => a.imported.cmp(&b.imported), + SortKey::EditDate => a.edited.cmp(&b.edited), + SortKey::FileName => cmp_name(&a.file_name, &b.file_name), + SortKey::Rating => a.rating.cmp(&b.rating), + SortKey::FileSize => a.file_size.cmp(&b.file_size), + SortKey::Random => shuffle_rank(self.seed, a.id).cmp(&shuffle_rank(self.seed, b.id)), + } + // Ties (one import batch, a burst within a second, equal ratings) sort by file name, the + // order cameras number frames, so the order doesn't depend on how ids were allocated; + // the id only keeps it stable. + .then_with(|| if self.key == SortKey::FileName { Equal } else { cmp_name(&a.file_name, &b.file_name) }) + .then(a.id.cmp(&b.id)); + if self.ascending { o } else { o.reverse() } + } +} + impl Default for Sort { fn default() -> Self { Sort { key: SortKey::CaptureDate, ascending: false, group: crate::GroupBy::Auto, seed: 0 } @@ -384,26 +405,37 @@ impl Catalog { .map(|p| p.as_ref()) .filter(|p| filter.matches_in(p, self, root.as_deref()) || (keep.contains(&p.id) && within.matches_in(p, self, within_root.as_deref()))) .collect(); - v.sort_by(|a, b| { - let o = match sort.key { - SortKey::CaptureDate => a.captured.cmp(&b.captured).then_with(|| a.imported.cmp(&b.imported)), - SortKey::ImportDate => a.imported.cmp(&b.imported), - SortKey::EditDate => a.edited.cmp(&b.edited), - SortKey::FileName => cmp_name(&a.file_name, &b.file_name), - SortKey::Rating => a.rating.cmp(&b.rating), - SortKey::FileSize => a.file_size.cmp(&b.file_size), - SortKey::Random => shuffle_rank(sort.seed, a.id).cmp(&shuffle_rank(sort.seed, b.id)), - } - // Ties (one import batch, a burst within a second, equal ratings) sort by file name, the - // order cameras number frames, so the order doesn't depend on how ids were allocated; - // the id only keeps it stable. - .then_with(|| if sort.key == SortKey::FileName { Equal } else { cmp_name(&a.file_name, &b.file_name) }) - .then(a.id.cmp(&b.id)); - if sort.ascending { o } else { o.reverse() } - }); + v.sort_by(|a, b| sort.order(a, b)); v.into_iter().map(|p| p.id).collect() } + /// The list `was` (a [`Catalog::query`] of `filter` in `sort` order, or a [`Catalog::query_keeping`]), after ops + /// that touched only the photos `touched` (sorted by id, each once: [`Catalog::touched_since`]): those photos + /// taken out, and the ones that match `filter` now put back at their place in the order. With `within`, a + /// touched photo that was in the list and still matches `within` stays, as `query_keeping` would keep it. What + /// the query would give, without asking every photo again. + pub fn follow(&self, was: &[PhotoId], touched: &[PhotoId], filter: &Filter, sort: &Sort, within: Option<&Filter>) -> Vec { + 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 (root, within_root) = (filter.library_root(), within.and_then(Filter::library_root)); + for id in touched { + let Some(p) = self.photo(*id) else { continue }; + let kept = within.is_some_and(|w| listed.contains(id) && w.matches_in(p, self, within_root.as_deref())); + if filter.matches_in(p, self, root.as_deref()) || kept { + // (the list is in order without the touched photos, and stays so as each is put back) + let at = ids.partition_point(|other| self.photo(*other).is_some_and(|o| sort.order(o, p).is_lt())); + ids.insert(at, *id); + } + } + ids + } + + /// How many photos match `filter`: [`Catalog::query`]'s length without its sorting. + pub fn count(&self, filter: &Filter) -> usize { + let root = filter.library_root(); + self.photos().filter(|p| filter.matches_in(p, self, root.as_deref())).count() + } + /// Year → month → day counts for the "By Date" section (newest first). pub fn date_groups(&self) -> Vec { use std::collections::BTreeMap; diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index acfbb1bb19c..518be154acc 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -737,3 +737,81 @@ fn cmp_name_ignores_case_without_allocating() { assert_eq!(cmp_name("DSC_0001", "DSC_0002"), Less); assert_eq!(cmp_name("a", "ab"), Less); } + +/// What the catalog remembers of its latest ops: which photos each changed and what of them, as long as that can be +/// said photo by photo. +#[test] +fn the_catalog_remembers_which_photos_its_latest_ops_changed_and_what_of_them() { + let mut c = Catalog::default(); + let photo = |c: &mut Catalog, name: &str| { + let id = c.alloc_photo_id(); + c.apply(Op::AddPhoto { + photo: Box::new(Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00")), + }) + .unwrap(); + id + }; + let (a, b) = (photo(&mut c, "a.jpg"), photo(&mut c, "b.jpg")); + let start = c.revision; + assert_eq!(c.touched_since(start), Some(vec![])); + assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); + // a rating, then a flag on another photo, as one batch + c.apply(Op::SetRating { id: a, rating: 3 }).unwrap(); + assert_eq!(c.touched_since(start), Some(vec![a])); + assert_eq!(c.aspects_since(start), Some(Aspects::RATING)); + let after_rating = c.revision; + c.apply(Op::Batch { ops: vec![Op::SetFlag { id: b, flag: Flag::Pick }, Op::SetRating { id: a, rating: 4 }] }).unwrap(); + assert_eq!(c.touched_since(start), Some(vec![a, b]), "each once"); + assert_eq!(c.touched_since(after_rating), Some(vec![a, b])); + assert_eq!(c.aspects_since(after_rating), Some(Aspects::FLAG.with(Aspects::RATING))); + assert_eq!(c.touched_since(c.revision), Some(vec![])); + // a photo that goes counts for everything + let before = c.revision; + c.apply(Op::RemovePhoto { id: b }).unwrap(); + assert_eq!(c.touched_since(before), Some(vec![b])); + assert!(c.aspects_since(before).is_some_and(|x| x.any_of(Aspects::PRESENCE) && x.any_of(Aspects::FILE))); + // an op that changes more than photos of its own: nothing is said of what came before it + let before = c.revision; + let album = c.alloc_album_id(); + c.apply(Op::AddAlbum { album: Album::new(album, "Trip") }).unwrap(); + assert_eq!(c.touched_since(before), None); + assert_eq!(c.aspects_since(start), None); + assert_eq!(c.touched_since(c.revision), Some(vec![]), "from after it, it is known again"); + // a revision that is not this catalog's past + assert_eq!(c.touched_since(c.revision + 5), None); + // a revision set from outside (a library just loaded): nothing is known of how the catalog got there, and after + // the next op nothing of before it + let old = c.revision; + c.revision = 7 << 32; + assert_eq!(c.touched_since(old), None); + assert_eq!(c.aspects_since(c.revision), None); + let loaded = c.revision; + c.apply(Op::SetRating { id: a, rating: 1 }).unwrap(); + assert_eq!(c.touched_since(loaded), Some(vec![a])); + assert_eq!(c.touched_since(old), None); + // an op that fails changes nothing, and what is remembered never says less than what happened + let before = c.revision; + assert!(c.apply(Op::SetRating { id: PhotoId(9_999), rating: 1 }).is_err()); + assert_eq!(c.revision, before); + c.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap(); + assert!(c.touched_since(before).is_some_and(|ids| ids.contains(&a))); + assert!(c.aspects_since(before).is_some_and(|x| x.any_of(Aspects::FLAG))); + // a batch that fails midway is undone as a whole; a batch in a batch is remembered photo by photo; a batch + // with an op that changes more than photos is not + let before = c.revision; + assert!(c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 5 }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }).is_err()); + assert_eq!((c.revision, c.photo(a).map(|p| p.rating)), (before, Some(1))); + c.apply(Op::Batch { ops: vec![Op::Batch { ops: vec![Op::SetRating { id: a, rating: 2 }] }] }).unwrap(); + // (the photo the failed batch asked for and never found may be named too: more is said, never less) + assert!(c.touched_since(before).is_some_and(|ids| ids.contains(&a))); + let before = c.revision; + c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 3 }, Op::RenameAlbum { id: album, name: "Journey".into() }] }).unwrap(); + assert_eq!(c.touched_since(before), None); + // more ops than are remembered: the oldest are answered with "anything" + let long_ago = c.revision; + for i in 0..9000u32 { + c.apply(Op::SetRating { id: a, rating: (i % 5) as u8 }).unwrap(); + } + assert_eq!(c.touched_since(long_ago), None); + assert_eq!(c.touched_since(c.revision - 10), Some(vec![a])); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c1f1c093170..5e6fcb0395d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -172,6 +172,9 @@ pub struct Interaction { pub original: Arc, } +/// The most photos an edit may touch for the view to follow it photo by photo; a larger edit is worked out whole. +const MAX_FOLLOWED: usize = 256; + /// Source of [`Session::visible_shared`] generations (process-wide, so two sessions never share one). static VISIBLE_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); static LIBRARY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -193,10 +196,18 @@ pub struct Session { /// A view holds the photos it shows until it is refreshed (`library.holdView`): an edit that makes a photo stop /// matching a smart album's rules, Picks or the filter bar leaves it where it is. Off: the photo goes at once. pub hold_view: bool, - /// The view that is held and the photos in it, before stacks are arranged ([`Session::hold_view`]). Another - /// source, filter or sort is another view, and starts from what matches; so does a smart album whose rules - /// were changed. `None` for a view that nothing can stop matching (a source with no filter over it). - held: Option<(String, Vec)>, + /// The view last worked out, the catalog's revision then, and the photos in it before stacks are arranged. + /// A small edit is followed from it: only the photos the edit touched are asked about again and put at their + /// place in the order ([`Session::visible`]). It is also what a held view holds ([`Session::hold_view`]). + /// Another source, filter or sort is another view, and so is a smart album whose rules were changed. + base: Option<(String, u64, Vec)>, + /// How many times the view followed an edit from the list it had, and how many times it was worked out from + /// every photo (`ui.inspect` → `perf`): what tells a slow library from a slow edit. + pub view_followed: u64, + pub view_worked_out: u64, + /// Tests: work the view out whole every time (what following has to equal). + #[cfg(test)] + never_follow: bool, /// Identifies the current `visible` list: a new value (unique in the process) every time it /// is recomputed, so frontends can key their per-view caches on it instead of hashing the ids. visible_gen: u64, @@ -353,7 +364,11 @@ impl Session { visible: Vec::new().into(), visible_key: None, hold_view: false, - held: None, + base: None, + view_followed: 0, + view_worked_out: 0, + #[cfg(test)] + never_follow: false, visible_gen: 0, total: None, undo: Vec::new(), @@ -887,25 +902,50 @@ impl Session { // (only a view that asks something can lose a photo to an edit: the others are queried as ever, at no // cost for the hold) let holds = self.hold_view && (asks || self.filter != Filter::default()); - let held = self.held.as_ref().filter(|(held, _)| holds && *held == view).map(|(_, ids)| ids); - let mut visible = match held { - Some(ids) => { - let keep: std::collections::HashSet = ids.iter().copied().collect(); - let within = if asks { - self.view_filter(LibrarySource::All, &Filter::default()) - } else if self.source == LibrarySource::RecentlyAdded { - // (how far back it reaches was worked out for `f`: not a second pass over the library) - Filter { imported_from: f.imported_from.clone(), ..Default::default() } - } else { - self.view_filter(self.source, &Filter::default()) - }; - self.catalog.query_keeping(&f, &self.sort, &keep, &within) + let within = holds.then(|| { + if asks { + self.view_filter(LibrarySource::All, &Filter::default()) + } else if self.source == LibrarySource::RecentlyAdded { + // (how far back it reaches was worked out for `f`: not a second pass over the library) + Filter { imported_from: f.imported_from.clone(), ..Default::default() } + } else { + self.view_filter(self.source, &Filter::default()) } - None => self.catalog.query(&f, &self.sort), + }); + // Views whose order or photos are not the query's alone are worked out whole each time: an album in + // 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())); + 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. + let clocked = f.depends_on_now() + || (!f.albums_tested().is_empty() && self.catalog.albums().any(|al| al.smart.as_deref().is_some_and(Filter::depends_on_now))); + let base = self.base.take().filter(|(of, _, _)| *of == view); + // A small edit to the same view: the photos it touched are taken out, asked about again, and put back + // at their place in the order. The others neither stopped matching nor moved. + #[cfg(test)] + let clocked = clocked || self.never_follow; + let followed = base.as_ref().filter(|_| !whole && !clocked).and_then(|(_, revision, ids)| { + let touched = self.catalog.touched_since(*revision).filter(|touched| touched.len() <= MAX_FOLLOWED)?; + Some(self.catalog.follow(ids, &touched, &f, &self.sort, within.as_ref())) + }); + match followed { + Some(_) => self.view_followed += 1, + None => self.view_worked_out += 1, + } + let mut visible = match (followed, &base, &within) { + (Some(ids), _, _) => ids, + (None, Some((_, _, held)), Some(within)) => { + let keep: std::collections::HashSet = held.iter().copied().collect(); + self.catalog.query_keeping(&f, &self.sort, &keep, within) + } + _ => self.catalog.query(&f, &self.sort), }; - // what the view shows now is what it holds until it is refreshed (taken before stacks are arranged, so - // a photo folded into a stack is held with it) - self.held = holds.then(|| (view, visible.clone())); + // what the view shows now is what the next edit is followed from, and what it holds until it is + // refreshed (taken before stacks are arranged, so a photo folded into a stack is held with it) + self.base = (!whole || holds).then(|| (view, self.catalog.revision, visible.clone())); if visible.is_empty() && self.source == LibrarySource::LibraryFolder && !self.folder_holds_photos() { // the shown folder lost its last photo (deleted, moved, removed): everything, not // an empty grid under the name of a folder that is gone from the sidebar @@ -973,10 +1013,25 @@ impl Session { /// Let go of what a held view kept: the view shows what matches now ([`Session::hold_view`]). pub fn refresh_view(&mut self) { - self.held = None; + self.base = None; self.visible_key = None; } + /// [`Session::visible`] worked out from every photo, whatever was followed before: what following an edit + /// has to equal. + /// Nothing the session keeps is changed by asking: the next edit is followed from where the last one left the + /// view, so a list followed many times over is compared, not only one followed once. + #[cfg(test)] + pub(crate) fn visible_in_full(&mut self) -> Vec { + let kept = (self.base.clone(), self.visible_key.clone(), self.visible.clone(), self.visible_gen, self.view_followed, self.view_worked_out); + self.never_follow = true; + self.visible_key = None; + let whole = self.visible().to_vec(); + self.never_follow = false; + (self.base, self.visible_key, self.visible, self.visible_gen, self.view_followed, self.view_worked_out) = kept; + whole + } + /// Whether the library still holds a photo imported from the folder a `LibraryFolder` source /// shows. fn folder_holds_photos(&self) -> bool { @@ -990,6 +1045,16 @@ impl Session { if self.source == LibrarySource::Missing { return None; } + if self.filter == Filter::default() && !self.hold_view { + // nothing narrows the source: what the view lists is all of it, and is counted already (not a view + // that holds photos that stopped matching: those are not of the source any more) + let _ = self.visible(); + if let Some((_, revision, ids)) = &self.base + && *revision == self.catalog.revision + { + return Some(ids.len()); + } + } let key = (self.catalog.revision, format!("{:?}|{:?}|{:?}", self.source, self.browse, self.library_folder)); if self.total.as_ref().map(|t| &t.0) != Some(&key) { let mut f = self.source.to_filter(&Filter::default(), &self.catalog); @@ -1001,7 +1066,8 @@ impl Session { if self.source == LibrarySource::LibraryFolder { f.library_folder = Some(self.library_folder.clone().unwrap_or_else(|| ".".into())); } - let n = self.catalog.query(&f, &self.sort).len(); + // (how many, not which: nothing to put in order) + let n = self.catalog.count(&f); self.total = Some((key, n)); } self.total.as_ref().map(|t| t.1) @@ -1112,4 +1178,6 @@ mod tests_spots; #[cfg(test)] mod tests_sync; #[cfg(test)] +mod tests_view_follow; +#[cfg(test)] mod tests_xmp; diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index be6fab1dd16..e115bcf3ac5 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -424,6 +424,8 @@ impl Session { static LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); catalog.revision = LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) << 32; self.catalog = catalog; + // (nothing of the list the last library showed is this one's) + self.refresh_view(); self.library_generation = crate::LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); for entry in self.undo.iter_mut().chain(self.redo.iter_mut()) { self.pending_sidecar_repairs.append(&mut entry.retry_sidecars); diff --git a/crates/engine/src/tests_hold_view.rs b/crates/engine/src/tests_hold_view.rs index 3bb998b8cf8..f7082498c97 100644 --- a/crates/engine/src/tests_hold_view.rs +++ b/crates/engine/src/tests_hold_view.rs @@ -181,10 +181,10 @@ fn a_source_with_no_filter_over_it_holds_nothing() { let all = s.visible_cloned(); keyword(&mut s, all[0]); assert_eq!(s.visible_cloned(), all); - assert!(s.held.is_none()); - s.execute("library.filter", &json!({"rating": 1})).unwrap(); - let _ = s.visible_cloned(); - assert!(s.held.is_some(), "a filter is a question: its view is held"); + // a photo deleted from All Photos leaves it, held or not + s.execute("library.select", &json!({"ids": [all[0].0]})).unwrap(); + s.execute("photo.delete", &json!({})).unwrap(); + assert!(!s.visible_cloned().contains(&all[0])); } #[test] diff --git a/crates/engine/src/tests_view_follow.rs b/crates/engine/src/tests_view_follow.rs new file mode 100644 index 00000000000..bf0656f86d4 --- /dev/null +++ b/crates/engine/src/tests_view_follow.rs @@ -0,0 +1,221 @@ +//! The view follows a small edit from the list it had ([`Session::visible`]): whatever the edit, the result has to +//! be the list worked out from every photo. + +use lightcraft_catalog::{Op, Photo, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::Session; + +/// A small generator of numbers that is the same on every run. +struct Dice(u64); + +impl Dice { + fn roll(&mut self, sides: usize) -> usize { + self.0 = lightcraft_catalog::mix64(self.0); + (self.0 % sides.max(1) as u64) as usize + } +} + +/// A library of `n` photos in three folders, with ratings, flags, keywords and dates spread over them, an album +/// holding every third photo, a smart album of the photos without keywords, and a stack. +fn library(n: usize) -> (Session, Vec, u64, u64) { + let mut s = Session::new(); + let mut ids = Vec::new(); + for i in 0..n { + let id = s.catalog.alloc_photo_id(); + let name = format!("IMG_{:04}.jpg", (i * 37) % n); + let mut p = Photo::new( + id, + Source::File { path: format!("/pics/{}/{name}", i % 3) }, + &name, + "JPEG", + 60, + 40, + &format!("2026-01-{:02}T10:00:00", 1 + i % 9), + ); + p.captured = Some(format!("2025-{:02}-{:02}T10:00:{:02}", 1 + i % 12, 1 + i % 28, i % 60)); + s.commit("Add", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + ids.push(id); + } + let pick = |s: &mut Session, ids: Vec, command: &str, params: Value| { + s.execute("library.select", &json!({"ids": ids})).unwrap(); + s.execute(command, ¶ms).unwrap(); + }; + let every = |k: usize, of: usize| ids.iter().enumerate().filter(|(i, _)| i % of == k).map(|(_, id)| id.0).collect::>(); + pick(&mut s, every(0, 4), "photo.rate", json!({"rating": 3})); + pick(&mut s, every(1, 4), "photo.rate", json!({"rating": 5})); + pick(&mut s, every(0, 5), "photo.flag", json!({"flag": "pick"})); + pick(&mut s, every(0, 2), "photo.setMeta", json!({"addKeywords": ["travel"]})); + pick(&mut s, every(0, 7), "photo.setMeta", json!({"addKeywords": ["weddings"]})); + let album = s.execute("album.create", &json!({"name": "Trip"})).unwrap()["id"].as_u64().unwrap(); + s.execute("album.addPhotos", &json!({"id": album, "ids": every(0, 3)})).unwrap(); + let rules = json!({"ruleSet": {"match": "all", "rules": [{"field": "keywordCount", "op": "is", "value": 0}]}}); + let smart = s.execute("album.createSmart", &json!({"name": "Unkeyworded", "rules": rules})).unwrap()["id"].as_u64().unwrap(); + pick(&mut s, vec![ids[10].0, ids[11].0, ids[12].0], "stack.group", json!({})); + (s, ids, album, smart) +} + +/// One edit at random: most touch a photo or a few (what it is rated, flagged, keyworded, developed; when it was +/// taken; where its file is; whether it is in the library at all), some change an album, a stack or the library's +/// past, and now and then a photo is added or removed for good. +fn edit(s: &mut Session, dice: &mut Dice, ids: &mut Vec, album: u64) { + let chosen: Vec = (0..1 + dice.roll(3)).map(|_| ids[dice.roll(ids.len())].0).collect(); + let one = PhotoId(chosen[0]); + let n = dice.roll(1000); + // (ops a command would refuse here, or on a photo that is gone, are edits that were not made: also a case) + match dice.roll(9) { + 0 => { + let _ = + s.commit("Capture time", Op::SetCaptured { id: one, captured: Some(format!("2025-{:02}-{:02}T08:00:00", 1 + n % 12, 1 + n % 28)) }); + return; + } + 1 => { + let name = format!("REN_{n:04}.jpg"); + let source = Source::File { path: format!("/pics/{}/{name}", n % 3) }; + let _ = s.commit("Locate", Op::Relink { id: one, file_name: name, source, format: None }); + return; + } + 2 if n.is_multiple_of(4) => { + let id = s.catalog.alloc_photo_id(); + let name = format!("NEW_{n:04}.jpg"); + let mut p = Photo::new(id, Source::File { path: format!("/pics/{}/{name}", n % 3) }, &name, "JPEG", 60, 40, "2026-02-01T10:00:00"); + p.captured = Some(format!("2025-{:02}-11T09:00:00", 1 + n % 12)); + if s.commit("Add", Op::AddPhoto { photo: Box::new(p) }).is_ok() { + ids.push(id); + } + return; + } + 2 if n % 4 == 1 => { + let _ = s.commit("Remove", Op::RemovePhoto { id: one }); + return; + } + 2 => { + let _ = s.commit("Local", Op::SetLocal { id: one, local: n.is_multiple_of(2) }); + return; + } + _ => {} + } + // (a photo in Recently Deleted can't be chosen: the edit is then not made, which is an edit too) + let _ = s.execute("library.select", &json!({"ids": chosen})); + let flag = ["pick", "reject", "none"][dice.roll(3)]; + let keyword = ["travel", "weddings", "pets"][dice.roll(3)]; + let _ = match dice.roll(12) { + 0 | 1 => s.execute("photo.rate", &json!({"rating": dice.roll(6)})), + 2 => s.execute("photo.flag", &json!({"flag": flag})), + 3 | 4 => s.execute("photo.setMeta", &json!({"addKeywords": [keyword]})), + 5 | 6 => s.execute("photo.setMeta", &json!({"keywords": []})), + 7 if n.is_multiple_of(2) => s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.1 * (n % 9) as f64})), + 7 => s.execute("stack.group", &json!({})), + 8 => s.execute("photo.delete", &json!({})), + 9 => s.execute("album.addPhotos", &json!({"id": album, "ids": chosen})), + 10 => s.execute("album.removePhotos", &json!({"id": album, "ids": chosen})), + _ => s.undo_step().map(|_| Value::Null), + }; +} + +#[test] +fn following_an_edit_gives_the_list_worked_out_from_every_photo() { + let (mut s, mut ids, album, smart) = library(240); + let mut dice = Dice(7); + let sources = [ + json!({"kind": "all"}), + json!({"kind": "picks"}), + json!({"kind": "album", "id": smart}), + json!({"kind": "album", "id": album}), + json!({"kind": "libraryFolder", "path": "/pics/1"}), + json!({"kind": "recentlyDeleted"}), + ]; + let sorts = [ + json!({"key": "random", "seed": 11}), + json!({"key": "captureDate", "ascending": false}), + json!({"key": "rating", "ascending": true}), + json!({"key": "fileName", "ascending": true}), + json!({"key": "editDate", "ascending": false}), + json!({"key": "importDate", "ascending": true}), + ]; + let filters = [json!({"rating": 0, "text": ""}), json!({"rating": 3, "text": ""}), json!({"rating": 0, "text": "travel"})]; + let mut checked = 0; + for (i, source) in sources.iter().enumerate() { + for (j, sort) in sorts.iter().enumerate() { + let filter = &filters[(i + j) % filters.len()]; + s.execute("library.source", source).unwrap(); + s.execute("library.sort", sort).unwrap(); + s.execute("library.filter", filter).unwrap(); + let _ = s.visible_cloned(); + // (every other view holds its photos until refreshed: what stays then has to be what asking every photo + // would keep) + s.execute("library.holdView", &json!({"on": (i + j) % 2 == 1})).unwrap(); + let _ = s.visible_cloned(); + for step in 0..40 { + edit(&mut s, &mut dice, &mut ids, album); + let followed = s.visible_cloned(); + let whole = s.visible_in_full(); + assert_eq!(followed, whole, "source {source}, sort {sort}, filter {filter}, hold {}, edit {step}", s.hold_view); + checked += 1; + } + } + } + assert_eq!(checked, 1440); + // and it was following that was checked: most edits touch a photo or two, and the view kept up with those + // without asking every photo again + assert!(s.view_followed > 400, "followed {} times, worked out {} times", s.view_followed, s.view_worked_out); +} + +#[test] +fn a_view_that_asks_about_the_last_days_follows_the_clock_too() { + let (mut s, ids, _, _) = library(60); + // Given a smart album of the photos taken in the last 30 days, a day after the latest of them + let now = std::sync::Arc::new(std::sync::Mutex::new("2026-01-01T12:00:00".to_string())); + let clock = now.clone(); + s.clock = Box::new(move || clock.lock().unwrap().clone()); + let rules = json!({"ruleSet": {"match": "all", "rules": [{"field": "captureDate", "op": "inLast", "value": 30}]}}); + let recent = s.execute("album.createSmart", &json!({"name": "Recent", "rules": rules})).unwrap()["id"].as_u64().unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": recent})).unwrap(); + s.execute("library.sort", &json!({"key": "fileName", "ascending": true})).unwrap(); + let shown = s.visible_cloned(); + assert!(!shown.is_empty() && shown.len() < ids.len(), "{} of {}", shown.len(), ids.len()); + // When a photo is rated two months later + *now.lock().unwrap() = "2026-03-05T12:00:00".to_string(); + let followed = s.view_followed; + s.execute("library.select", &json!({"ids": [ids[0].0]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 2})).unwrap(); + // Then the photos nobody touched have left with the days: the view was asked whole, not followed + assert!(s.visible_cloned().is_empty(), "{:?}", s.visible_cloned()); + assert_eq!(s.visible_cloned(), s.visible_in_full()); + assert_eq!(s.view_followed, followed); + // And the same through a view that only looks into that album + let rules = json!({"ruleSet": {"match": "all", "rules": [{"field": "album", "op": "is", "value": recent}]}}); + if let Ok(r) = s.execute("album.createSmart", &json!({"name": "In Recent", "rules": rules})) { + s.execute("library.source", &json!({"kind": "album", "id": r["id"]})).unwrap(); + let _ = s.visible_cloned(); + s.execute("library.select", &json!({"ids": [ids[0].0]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 3})).unwrap(); + assert_eq!(s.visible_cloned(), s.visible_in_full()); + assert_eq!(s.view_followed, followed, "a view that looks into a clocked album is asked whole too"); + } +} + +#[test] +fn an_edit_to_many_photos_or_to_more_than_photos_is_worked_out_whole() { + let (mut s, ids, album, _) = library(600); + s.execute("library.sort", &json!({"key": "random", "seed": 3})).unwrap(); + let _ = s.visible_cloned(); + let (followed, whole) = (s.view_followed, s.view_worked_out); + // one photo rated: followed + s.execute("library.select", &json!({"ids": [ids[5].0]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 1})).unwrap(); + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole)); + // five hundred photos rated at once: worked out from every photo + s.execute("library.select", &json!({"ids": ids.iter().take(500).map(|id| id.0).collect::>()})).unwrap(); + s.execute("photo.rate", &json!({"rating": 2})).unwrap(); + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole + 1)); + // an album's photos changed: what that does to which view is not asked photo by photo + s.execute("album.addPhotos", &json!({"id": album, "ids": [ids[1].0]})).unwrap(); + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole + 2)); + // nothing changed: neither + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole + 2)); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 891914d1d03..3316e3a0fa1 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -113,7 +113,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value { "selection": app.session.selection.ids.iter().map(|p| p.0).collect::>(), "activeMask": app.session.active_mask, "widgetCount": app.widgets.len(), - "perf": {"frameMs": app.perf.frame_ms, "logicMs": app.perf.logic_ms, "updateMs": app.perf.update_ms, "maxUpdateMs": app.perf.max_update_ms, "fps": app.perf.fps, "lastRenderMs": app.renderer.last_main_ms, "renderQueue": app.renderer.queued(), "rendersInFlight": app.renderer.in_flight(), "pendingSlots": app.renderer.pending_slots(), "mergeRunning": app.merge.busy(), "lastMerge": app.merge.last_result, "rendersDone": app.renderer.completed, "thumbTextures": app.renderer.thumb_textures(), "variantTextures": app.renderer.variant_textures(), "gpu": (lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available()).then(lightcraft_engine::gpu::adapter_name).flatten(), "gpuReason": lightcraft_engine::gpu::unavailable_reason(), "gpuFallback": lightcraft_engine::gpu::last_fallback()}, + "perf": {"viewFollowed": app.session.view_followed, "viewWorkedOut": app.session.view_worked_out, "frameMs": app.perf.frame_ms, "logicMs": app.perf.logic_ms, "updateMs": app.perf.update_ms, "maxUpdateMs": app.perf.max_update_ms, "fps": app.perf.fps, "lastRenderMs": app.renderer.last_main_ms, "renderQueue": app.renderer.queued(), "rendersInFlight": app.renderer.in_flight(), "pendingSlots": app.renderer.pending_slots(), "mergeRunning": app.merge.busy(), "lastMerge": app.merge.last_result, "rendersDone": app.renderer.completed, "thumbTextures": app.renderer.thumb_textures(), "variantTextures": app.renderer.variant_textures(), "gpu": (lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available()).then(lightcraft_engine::gpu::adapter_name).flatten(), "gpuReason": lightcraft_engine::gpu::unavailable_reason(), "gpuFallback": lightcraft_engine::gpu::last_fallback()}, "loupe": app.loupe_shown.map(|(p, src)| json!({ "photo": p.0, "source": src, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 37fb86df31e..b2fc4975e18 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -119,12 +119,16 @@ mod tests_switch_library; #[cfg(test)] mod tests_sync; #[cfg(test)] +mod tests_tallies; +#[cfg(test)] mod tests_temp_slider; #[cfg(test)] mod tests_titlebar; #[cfg(test)] mod tests_unsaved; #[cfg(test)] +mod tests_view_cost; +#[cfg(test)] mod tests_wb_selector; #[cfg(test)] mod tests_zoom; @@ -1592,28 +1596,35 @@ pub(crate) fn key_of(parts: impl std::hash::Hash) -> u64 { BuildHasherDefault::::default().hash_one(parts) } +/// Whether a tally of the library made when the catalog was at `revision` is still right, given that it reads only +/// `reads` of a photo: nothing changed since, or only other things of some photos did (a rating changes no folder's +/// count, a slider changes none at all). Each of these tallies asks every photo, so one kept is a pass over the +/// library saved on every edit. +fn still_right(cat: &lightcraft_catalog::Catalog, revision: u64, reads: lightcraft_catalog::Aspects) -> bool { + revision == cat.revision || cat.aspects_since(revision).is_some_and(|changed| !changed.any_of(reads)) +} + +/// What the tallies below read of a photo, besides whether it is in the library. +const READS_FILE: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::FILE); +const READS_META: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::META); +const READS_PEOPLE: lightcraft_catalog::Aspects = READS_META.with(lightcraft_catalog::Aspects::ANALYSIS); +const READS_CAPTURED: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::CAPTURED); +const READS_FLAG: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::FLAG); + impl Caches { /// The folders the library's photos were imported from. pub fn folder_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - match &self.folder_tree { - Some((r, t)) if *r == cat.revision => t.clone(), - _ => { - let t = std::sync::Arc::new(cat.folder_tree()); - self.folder_tree = Some((cat.revision, t.clone())); - t - } - } + let kept = self.folder_tree.take().filter(|(r, _)| still_right(cat, *r, READS_FILE)).map(|(_, t)| t); + let t = kept.unwrap_or_else(|| std::sync::Arc::new(cat.folder_tree())); + self.folder_tree = Some((cat.revision, t.clone())); + t } /// The library's keyword tree. pub fn keyword_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - match &self.keyword_tree { - Some((r, t)) if *r == cat.revision => t.clone(), - _ => { - let t = std::sync::Arc::new(cat.keyword_tree()); - self.keyword_tree = Some((cat.revision, t.clone())); - t - } - } + let kept = self.keyword_tree.take().filter(|(r, _)| still_right(cat, *r, READS_META)).map(|(_, t)| t); + let t = kept.unwrap_or_else(|| std::sync::Arc::new(cat.keyword_tree())); + self.keyword_tree = Some((cat.revision, t.clone())); + t } /// The Keywording box's read-only names for the selection: what exported files carry /// (`export`), or the keywords with those containing them. @@ -1689,8 +1700,9 @@ impl Caches { /// All Photos / Picks / Recently Deleted counts. pub fn counts(&mut self, cat: &lightcraft_catalog::Catalog) -> LibraryCounts { if let Some((r, c)) = self.counts - && r == cat.revision + && still_right(cat, r, READS_FLAG) { + self.counts = Some((cat.revision, c)); return c; } let mut c = LibraryCounts::default(); @@ -1709,25 +1721,17 @@ impl Caches { } /// Everyone named on a face in the library (for completing a name as it is typed). pub fn person_names(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - match &self.person_names { - Some((r, v)) if *r == cat.revision => v.clone(), - _ => { - let v = std::sync::Arc::new(cat.people().into_iter().map(|p| p.name).collect::>()); - self.person_names = Some((cat.revision, v.clone())); - v - } - } + let kept = self.person_names.take().filter(|(r, _)| still_right(cat, *r, READS_PEOPLE)).map(|(_, v)| v); + let v = kept.unwrap_or_else(|| std::sync::Arc::new(cat.people().into_iter().map(|p| p.name).collect::>())); + self.person_names = Some((cat.revision, v.clone())); + v } /// The By Date tree. pub fn date_groups(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - match &self.date_groups { - Some((r, g)) if *r == cat.revision => g.clone(), - _ => { - let g = std::sync::Arc::new(cat.date_groups()); - self.date_groups = Some((cat.revision, g.clone())); - g - } - } + let kept = self.date_groups.take().filter(|(r, _)| still_right(cat, *r, READS_CAPTURED)).map(|(_, g)| g); + let g = kept.unwrap_or_else(|| std::sync::Arc::new(cat.date_groups())); + self.date_groups = Some((cat.revision, g.clone())); + g } /// Cameras, lenses and keywords in the library (filter bar pickers). pub fn filter_values(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc { diff --git a/crates/ui-egui/src/tests_tallies.rs b/crates/ui-egui/src/tests_tallies.rs new file mode 100644 index 00000000000..ffc7408c539 --- /dev/null +++ b/crates/ui-egui/src/tests_tallies.rs @@ -0,0 +1,149 @@ +//! The side panels' tallies of the library (folders, keywords, dates, people, counts) are kept through an edit that +//! cannot have changed them, and are never kept through one that did. + +use std::sync::Arc; + +use serde_json::json; + +use crate::{LightcraftApp, Services}; + +/// A library of photos that are files in folders, taken on different days (the demo's photos are in no folder), +/// some of them keyworded. +fn app() -> LightcraftApp { + use lightcraft_catalog::{Op, Photo, Source}; + let mut s = lightcraft_engine::Session::new(); + let mut ids = Vec::new(); + for i in 0..60usize { + let id = s.catalog.alloc_photo_id(); + let name = format!("IMG_{i:03}.jpg"); + let mut p = Photo::new(id, Source::File { path: format!("/pics/{}/{name}", i % 4) }, &name, "JPEG", 60, 40, "2026-01-01T10:00:00"); + p.captured = Some(format!("2025-{:02}-{:02}T10:00:00", 1 + i % 12, 1 + i % 28)); + s.commit("Add", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + ids.push(id.0); + } + s.execute("library.select", &json!({"ids": ids.iter().step_by(2).collect::>()})).unwrap(); + s.execute("photo.setMeta", &json!({"addKeywords": ["travel"]})).unwrap(); + LightcraftApp::new(s, Services { png: None, ..Default::default() }) +} + +/// The tallies as the panels would show them now. +fn shown(a: &mut LightcraftApp) -> String { + let cat = &a.session.catalog; + format!( + "{:?}\n{:?}\n{:?}\n{:?}\n{:?}", + a.caches.folder_tree(cat), + a.caches.keyword_tree(cat), + a.caches.date_groups(cat), + a.caches.person_names(cat), + a.caches.counts(cat) + ) +} + +/// The same tallies made from every photo. +fn fresh(a: &LightcraftApp) -> String { + let cat = &a.session.catalog; + format!( + "{:?}\n{:?}\n{:?}\n{:?}\n{:?}", + cat.folder_tree(), + cat.keyword_tree(), + cat.date_groups(), + cat.people().into_iter().map(|p| p.name).collect::>(), + crate::Caches::default().counts(cat) + ) +} + +#[test] +fn a_tally_kept_through_an_edit_is_the_tally_made_from_every_photo() { + let mut a = app(); + let ids: Vec = a.session.visible_cloned().iter().map(|p| p.0).collect(); + let mut dice = 5u64; + let mut roll = |sides: usize| { + dice = lightcraft_catalog::mix64(dice); + (dice % sides as u64) as usize + }; + assert_eq!(shown(&mut a), fresh(&a)); + assert!(!a.caches.folder_tree(&a.session.catalog).is_empty() && !a.caches.date_groups(&a.session.catalog).is_empty()); + for step in 0..600 { + let id = ids[roll(ids.len())]; + // (a photo in Recently Deleted can't be chosen: the edit is then not made, which is an edit too) + let _ = a.session.execute("library.select", &json!({"ids": [id]})); + let keyword = ["travel", "weddings", "pets|dogs"][roll(3)]; + let flag = ["pick", "reject", "none"][roll(3)]; + // where a file is, when a photo was taken, a photo that comes or goes for good + { + use lightcraft_catalog::{Op, Photo, PhotoId, Source}; + let n = roll(1000); + let moved = match roll(8) { + 0 => { + let name = format!("MOVED_{n:03}.jpg"); + let source = Source::File { path: format!("/elsewhere/{}/{name}", n % 3) }; + Some(a.session.commit("Locate", Op::Relink { id: PhotoId(id), file_name: name, source, format: None })) + } + 1 => Some( + a.session + .commit("Capture time", Op::SetCaptured { id: PhotoId(id), captured: Some(format!("2024-{:02}-03T10:00:00", 1 + n % 12)) }), + ), + 2 if n.is_multiple_of(3) => Some(a.session.commit("Remove", Op::RemovePhoto { id: PhotoId(id) })), + 2 if n % 3 == 1 => { + let new = a.session.catalog.alloc_photo_id(); + let name = format!("NEW_{n:03}.jpg"); + let p = Photo::new(new, Source::File { path: format!("/new/{name}") }, &name, "JPEG", 60, 40, "2026-02-01T10:00:00"); + Some(a.session.commit("Add", Op::AddPhoto { photo: Box::new(p) })) + } + _ => None, + }; + if moved.is_some() { + if roll(3) > 0 { + assert_eq!(shown(&mut a), fresh(&a), "after edit {step}"); + } + continue; + } + } + let _ = match roll(11) { + 0 | 1 => a.session.execute("photo.rate", &json!({"rating": roll(6)})), + 2 => a.session.execute("photo.flag", &json!({"flag": flag})), + 3 | 4 => a.session.execute("photo.setMeta", &json!({"addKeywords": [keyword]})), + 5 => a.session.execute("photo.setMeta", &json!({"keywords": []})), + 6 => a.session.execute("photo.setMeta", &json!({"title": format!("Title {}", roll(4))})), + 7 => a.session.execute("develop.set", &json!({"control": "light.exposure", "value": 0.1 * roll(9) as f64})), + 8 => a.session.execute("photo.delete", &json!({})), + 9 => a.session.execute("photo.label", &json!({"label": "red"})), + _ => a.session.undo_step().map(|_| serde_json::Value::Null), + }; + // (not every frame asks for every tally: sometimes several edits pass between two looks) + if roll(3) > 0 { + assert_eq!(shown(&mut a), fresh(&a), "after edit {step}"); + } + } +} + +#[test] +fn a_rating_or_a_slider_keeps_every_tally_and_a_keyword_keeps_the_folders_and_dates() { + let mut a = app(); + let id = a.session.visible_cloned()[0].0; + a.session.execute("library.select", &json!({"ids": [id]})).unwrap(); + let look = |a: &mut LightcraftApp| { + let cat = &a.session.catalog; + (a.caches.folder_tree(cat), a.caches.keyword_tree(cat), a.caches.date_groups(cat), a.caches.person_names(cat)) + }; + let was = look(&mut a); + // a rating, then a slider: nothing is tallied again + a.session.execute("photo.rate", &json!({"rating": 2})).unwrap(); + a.session.execute("develop.set", &json!({"control": "light.exposure", "value": 0.4})).unwrap(); + let now = look(&mut a); + assert!(Arc::ptr_eq(&was.0, &now.0) && Arc::ptr_eq(&was.1, &now.1) && Arc::ptr_eq(&was.2, &now.2) && Arc::ptr_eq(&was.3, &now.3)); + // a keyword: the keyword tree is made again, the folders and the dates are not + a.session.execute("photo.setMeta", &json!({"addKeywords": ["travel"]})).unwrap(); + let now = look(&mut a); + assert!(Arc::ptr_eq(&was.0, &now.0) && Arc::ptr_eq(&was.2, &now.2), "folders and dates kept"); + assert!(!Arc::ptr_eq(&was.1, &now.1), "keywords tallied again"); + // a photo deleted: every tally is made again + a.session.execute("photo.delete", &json!({})).unwrap(); + let gone = look(&mut a); + assert!(!Arc::ptr_eq(&now.0, &gone.0) && !Arc::ptr_eq(&now.1, &gone.1) && !Arc::ptr_eq(&now.2, &gone.2)); + // an album made (more than a photo's own change): nothing is assumed + let before = look(&mut a); + a.session.execute("album.create", &json!({"name": "Trip"})).unwrap(); + let after = look(&mut a); + assert!(!Arc::ptr_eq(&before.0, &after.0)); +} diff --git a/crates/ui-egui/src/tests_view_cost.rs b/crates/ui-egui/src/tests_view_cost.rs new file mode 100644 index 00000000000..064eba6fd2f --- /dev/null +++ b/crates/ui-egui/src/tests_view_cost.rs @@ -0,0 +1,155 @@ +//! What one edit costs in a large library: a measurement, not a test (run with `--ignored --nocapture`). + +use std::time::{Duration, Instant}; + +use lightcraft_catalog::{Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +fn ms(d: Duration) -> f64 { + d.as_secs_f64() * 1000.0 +} + +/// A library of `n` photos, about a third of them keyworded from a pool of 500 keywords, showing a smart album of +/// the photos without keywords at random. +fn library(n: usize) -> lightcraft_engine::Session { + let mut s = lightcraft_engine::Session::new(); + let mut keyworded: Vec> = vec![Vec::new(); 500]; + for i in 0..n { + let id = s.catalog.alloc_photo_id(); + let name = format!("IMG_{i:06}.jpg"); + let day = 1 + (i / 400) % 28; + let month = 1 + (i / 11_200) % 12; + let mut p = Photo::new(id, Source::File { path: format!("/pics/{}/{name}", i / 1000) }, &name, "JPEG", 6000, 4000, "2026-01-01T10:00:00"); + p.captured = Some(format!("2025-{month:02}-{day:02}T10:{:02}:{:02}", (i / 60) % 60, i % 60)); + s.commit("Add", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + if i % 3 == 0 { + keyworded[(i / 3) % 500].push(id.0); + } + } + for (k, ids) in keyworded.iter().enumerate() { + s.execute("library.select", &json!({"ids": ids})).unwrap(); + s.execute("photo.setMeta", &json!({"addKeywords": [format!("keyword {k:03}")]})).unwrap(); + } + let rules = json!({"ruleSet": {"match": "all", "rules": [{"field": "keywordCount", "op": "is", "value": 0}]}}); + let album = s.execute("album.createSmart", &json!({"name": "Unkeyworded", "rules": rules})).unwrap()["id"].as_u64().unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": album})).unwrap(); + s.execute("library.sort", &json!({"key": "random"})).unwrap(); + s +} + +#[test] +#[ignore = "a measurement: run with --ignored --nocapture"] +fn what_one_keyword_costs_in_a_library_of_67_000_photos() { + let t = Instant::now(); + let mut s = library(67_000); + eprintln!("built the library in {:.0} ms", ms(t.elapsed())); + // the engine alone + let t = Instant::now(); + let shown = s.visible().len(); + eprintln!("engine: first view of {shown} photos: {:.1} ms", ms(t.elapsed())); + for round in 0..3 { + let id: PhotoId = s.visible()[100 + round]; + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + let t = Instant::now(); + s.execute("photo.setMeta", &json!({"addKeywords": ["keyword 001"]})).unwrap(); + let command = t.elapsed(); + let t = Instant::now(); + let n = s.visible().len(); + let view = t.elapsed(); + let t = Instant::now(); + let _ = s.source_total(); + let total = t.elapsed(); + eprintln!("engine: keyword {round}: command {:.1} ms, view of {n} again {:.1} ms, source total {:.1} ms", ms(command), ms(view), ms(total)); + } + // its parts + let ids = s.visible_cloned(); + let t = Instant::now(); + let f = s.source.to_filter(&s.filter, &s.catalog); + let q = s.catalog.query(&f, &s.sort); + let query = t.elapsed(); + let t = Instant::now(); + let _ = s.catalog.arrange_stacks(&q); + let stacks = t.elapsed(); + let t = Instant::now(); + let _ = s.catalog.stack_index(); + let index = t.elapsed(); + eprintln!( + "engine parts: query and sort {:.1} ms, arrange stacks {:.1} ms, stack index {:.1} ms ({} ids)", + ms(query), + ms(stacks), + ms(index), + ids.len() + ); + // what the side panels tally from every photo after each change + let time = |what: &str, f: &dyn Fn()| { + let t = Instant::now(); + f(); + eprintln!("tally: {what} {:.1} ms", ms(t.elapsed())); + }; + time("folder tree", &|| drop(s.catalog.folder_tree())); + time("keyword tree", &|| drop(s.catalog.keyword_tree())); + time("date groups", &|| drop(s.catalog.date_groups())); + time("people", &|| drop(s.catalog.people())); + time("count of a smart album", &|| { + let _ = s.catalog.count(&f); + }); + time("count of all photos", &|| { + let _ = s.catalog.count(&lightcraft_catalog::Filter::default()); + }); + // the app: a frame after an edit against a frame with nothing changed + let app = LightcraftApp::new(s, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1600.0, 1000.0], 1.0); + h.app.ui.left_panel = true; + h.request("engine.execute", json!({"command": "view.squareGrid", "params": {}}), Duration::from_secs(60)); + h.request("engine.execute", json!({"command": "panel.keywords", "params": {}}), Duration::from_secs(60)); + h.settle(Duration::from_secs(120)); + let frame = |h: &mut Headless| { + let t = Instant::now(); + h.step(); + t.elapsed() + }; + let idle: Vec = (0..5).map(|_| ms(frame(&mut h))).collect(); + eprintln!("app: frames with nothing changed: {idle:.1?} ms"); + for round in 0..3 { + let id: PhotoId = h.app.session.visible()[300 + round]; + h.app.session.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + h.step(); + h.step(); + let t = Instant::now(); + h.app.run("photo.setMeta", json!({"addKeywords": ["keyword 002"]})).unwrap(); + let command = t.elapsed(); + let first = frame(&mut h); + let second = frame(&mut h); + eprintln!("app: keyword {round}: command {:.1} ms, the frame after it {:.1} ms, the next {:.1} ms", ms(command), ms(first), ms(second)); + } + // which part of the window the frame after an edit pays for + for (what, left, right) in [("grid alone", false, false), ("grid and left panel", true, false), ("grid and Keywords panel", false, true)] { + h.app.ui.left_panel = left; + h.request("engine.execute", json!({"command": if right { "panel.keywords" } else { "panel.close" }, "params": {}}), Duration::from_secs(60)); + if right && h.app.ui.right != crate::state::RightPanel::Keywords { + h.request("engine.execute", json!({"command": "panel.keywords", "params": {}}), Duration::from_secs(60)); + } + h.settle(Duration::from_secs(120)); + let id: PhotoId = h.app.session.visible()[500]; + h.app.session.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + h.step(); + h.step(); + h.app.run("photo.setMeta", json!({"addKeywords": ["keyword 004"]})).unwrap(); + let first = frame(&mut h); + eprintln!("app: {what} (right panel {:?}): the frame after a keyword {:.1} ms", h.app.ui.right, ms(first)); + } + h.app.ui.left_panel = true; + let view = "view.photoGrid"; + h.request("engine.execute", json!({"command": view, "params": {}}), Duration::from_secs(60)); + h.settle(Duration::from_secs(120)); + let id: PhotoId = h.app.session.visible()[400]; + h.app.session.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + h.step(); + h.step(); + h.app.run("photo.setMeta", json!({"addKeywords": ["keyword 003"]})).unwrap(); + let first = frame(&mut h); + eprintln!("app: {view}: the frame after a keyword {:.1} ms", ms(first)); +} diff --git a/docs/whats-new.md b/docs/whats-new.md index a46a67a729d..a0699f77af3 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -8,6 +8,20 @@ ## 2026-10-13 +### Edits keep up in a large library +- A small edit (a keyword, a rating, a flag, a slider) no longer has the grid's list worked out again from every + photo: only the photos the edit touched are asked about again and put at their place in the order. In a library of + 67,000 photos that step went from 37 ms to under 1 ms. Still worked out whole: an edit to more than 256 photos, a + change to an album, a stack or the keyword list, an album shown in its own order, Recently Added, Missing Photos, + and a view that asks about "the last N days". +- With no filter set, the count of the source is taken from the list instead of from a second pass over the library. +- The side panels keep a tally an edit cannot have changed: a rating or a slider changes none of the folders, + keywords, dates, people and counts; a keyword leaves the folders, the dates and the counts as they are. With both + side panels open, the frame after a keyword went from about 156 ms to about 54 ms in that library (2 ms with the + panels closed, from 71 ms). +- Still tallied from every photo on each edit: the count beside each album and smart album in the left panel (about + 25 ms for a smart album in that library), and the filter bar's lists of cameras, lenses and keywords. + ### A view can hold its photos until you refresh it - View ▸ Hold View Until Refreshed (off unless you turn it on; kept with the library). With it on, an edit that makes a photo stop matching the view keeps it in the view: a keyword given in a smart album of photos without keywords,