diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 664ff410521..53ac4c84b52 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -28,6 +28,7 @@ mod log_writer; pub mod model; pub mod opened_folder; pub mod query; +pub mod reads; pub mod rules; pub mod safe_file; pub mod stacks; @@ -336,11 +337,18 @@ impl Aspects { pub const PRESENCE: Aspects = Aspects(1 << 8); /// Everything: the photo may count differently for any tally. pub const ALL: Aspects = Aspects(u16::MAX); + /// Everything but develop state: what a view reads that a slider tick leaves as it was ([`reads`]). + pub const ALL_BUT_DEVELOP: Aspects = Aspects::ALL.without(Aspects::DEVELOP); pub const fn with(self, other: Aspects) -> Aspects { Aspects(self.0 | other.0) } + /// These, but none of `other`. + pub const fn without(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 diff --git a/crates/catalog/src/reads.rs b/crates/catalog/src/reads.rs new file mode 100644 index 00000000000..326692cebb9 --- /dev/null +++ b/crates/catalog/src/reads.rs @@ -0,0 +1,284 @@ +//! What a view of the catalog reads of a photo, so that it can be kept through an edit that changed nothing it reads +//! ([`Catalog::unchanged_for`], on [`Catalog::aspects_since`]). A slider drag applies a develop op per tick: a +//! view that doesn't read develop state (most filters and sorts, the sidebar's trees and counts) is kept through +//! the whole drag. +//! +//! Some views *do* read develop state: "edited" filters and rules, Edit Date, Cropped, Treatment and the size rules +//! (crop and orientation change a photo's shown size), and so does any filter or rule that tests a smart album whose +//! rules read it. Those follow every develop edit ([`Catalog::filter_reads`]). + +use std::collections::HashSet; + +use crate::{AlbumId, Aspects, Catalog, Filter, Rule, RuleSet, Sort, SortKey}; + +/// Smart-album rule fields whose matches don't depend on a photo's develop state. Every other field (including one +/// added later and not listed here) counts as reading it, so a forgotten field costs a query per slider tick, never +/// a stale view. +const FIELDS_WITHOUT_DEVELOP: &[&str] = &[ + "rating", + "flag", + "label", + "text", + // an album rule reads what that album holds: see `Catalog::filter_reads_develop` + "album", + "virtualCopy", + "copyName", + "stacked", + "fileName", + "extension", + "filePath", + "kind", + "format", + "duration", + "captureDate", + "importDate", + "keywords", + "keywordCount", + "person", + "personCount", + "title", + "caption", + "altText", + "creator", + "copyright", + "copyrightStatus", + "camera", + "lens", + "focalLength", + "aperture", + "shutterSpeed", + "iso", + "flash", + "exposureBias", + "cameraSerial", + "location", + "city", + "state", + "country", + "hasGps", + "sharpness", + "bestOfGroup", +]; + +/// Search-text fields (`field:value` in [`Filter::text`]) whose matches don't depend on a photo's develop state. A +/// token on any other field (`edited:`, one added later and not listed here, or a word with a colon in it such as +/// "10:30") counts as reading it, so a forgotten field costs a query per slider tick, never a stale view. +const SEARCH_FIELDS_WITHOUT_DEVELOP: &[&str] = &[ + "rating", "stars", "flag", "label", "color", "iso", "f", "aperture", "focal", "camera", "lens", "keyword", "kw", "person", "who", "type", "kind", + "date", "copy", "virtual", "name", "file", +]; + +/// Whether a search-text word can match differently after a develop edit: a `field:value` word on a field not known +/// to be free of develop state (a quoted one too: erring that way costs a query, never a stale view). A word without +/// a colon is text, which a develop edit doesn't change. +fn token_reads_develop(token: &str) -> bool { + token.to_lowercase().split_once(':').is_some_and(|(field, _)| !SEARCH_FIELDS_WITHOUT_DEVELOP.contains(&field)) +} + +/// Whether a rule on `field` can match differently after a develop edit (Has Edits, Edit Date, Cropped, Treatment, +/// and the sizes a crop or rotation changes). +pub fn field_reads_develop(field: &str) -> bool { + !FIELDS_WITHOUT_DEVELOP.contains(&field) +} + +impl RuleSet { + /// Whether any of the rules (nested groups included) tests develop state itself; the albums an Album rule tests + /// are [`Catalog::filter_reads_develop`]'s concern. + pub fn reads_develop(&self) -> bool { + let mut next = vec![self]; + while let Some(set) = next.pop() { + for rule in &set.rules { + match rule { + Rule::Group { group } => next.push(group), + Rule::Field { field, .. } if field_reads_develop(field) => return true, + Rule::Field { .. } => {} + } + } + } + false + } +} + +impl Filter { + /// Whether the filter itself tests develop state: Edited, an `edited:` (or unlisted) search token or a rule that + /// does. The albums it tests are [`Catalog::filter_reads_develop`]'s concern. + pub fn reads_develop(&self) -> bool { + self.edited.is_some() || self.text.split_whitespace().any(token_reads_develop) || self.rule_set.as_ref().is_some_and(RuleSet::reads_develop) + } +} + +impl Sort { + /// Whether the order depends on develop state (Edit Date: every edit moves the photo). Every field and key is + /// named, with no wildcard: a new one doesn't compile until it is put on its side here. + pub fn reads_develop(&self) -> bool { + // the date headers (`group`) follow the key's date + let Sort { key, ascending: _, group: _, seed: _ } = self; + match key { + SortKey::EditDate => true, + SortKey::CaptureDate | SortKey::ImportDate | SortKey::FileName | SortKey::Rating | SortKey::FileSize | SortKey::Random => false, + } + } +} + +impl Catalog { + /// Whether which photos `filter` lets through can change with a develop edit: the filter's own fields and rules, + /// and those of every smart album it tests, directly or through other smart albums (loops in saved rules end the + /// search). + pub fn filter_reads_develop(&self, filter: &Filter) -> bool { + filter.reads_develop() || self.albums_read_develop(filter.albums_tested()) + } + + /// Whether what album `id` holds can change with a develop edit (a smart album whose rules, or those of the + /// smart albums they test, read develop state). Plain albums never do. + pub fn album_reads_develop(&self, id: AlbumId) -> bool { + self.albums_read_develop(vec![id]) + } + + fn albums_read_develop(&self, mut next: Vec) -> bool { + let mut seen: HashSet = HashSet::new(); + while let Some(id) = next.pop() { + if !seen.insert(id) { + continue; + } + let Some(rules) = self.album(id).and_then(|a| a.smart.as_deref()) else { continue }; + if rules.reads_develop() { + return true; + } + next.extend(rules.albums_tested()); + } + false + } + + /// What of a photo `filter` can read: everything but develop state, unless it (or a smart album it tests) reads + /// that too. + pub fn filter_reads(&self, filter: &Filter) -> Aspects { + if self.filter_reads_develop(filter) { Aspects::ALL } else { Aspects::ALL_BUT_DEVELOP } + } + + /// Whether something worked out from the catalog at `revision`, reading only `reads` of a photo, is still right: + /// nothing changed since, or only other things of some photos did (a slider changes no folder's count). `false` + /// when that is not known ([`Catalog::aspects_since`]). + pub fn unchanged_for(&self, revision: u64, reads: Aspects) -> bool { + revision == self.revision || self.aspects_since(revision).is_some_and(|changed| !changed.any_of(reads)) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use serde_json::json; + + use super::*; + use crate::{Album, Op, Photo, PhotoId, Source}; + + fn photo(id: u64) -> Photo { + Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("IMG_{id}.jpg"), "JPEG", 6000, 4000, "2026-01-01T00:00:00") + } + + fn rules(v: serde_json::Value) -> RuleSet { + serde_json::from_value(v).unwrap() + } + + fn smart(id: u64, rules: RuleSet) -> Op { + let mut a = Album::new(AlbumId(id), format!("Smart {id}")); + a.smart = Some(Box::new(Filter { rule_set: Some(rules), ..Default::default() })); + Op::AddAlbum { album: a } + } + + #[test] + fn filters_sorts_and_rules_that_read_develop_state() { + assert!(!Filter::default().reads_develop()); + assert!(!Filter { text: "harbour rating:3".into(), rating: 2, keyword: Some("travel".into()), ..Default::default() }.reads_develop()); + assert!(Filter { edited: Some(false), ..Default::default() }.reads_develop()); + assert!(Filter { text: "harbour Edited:yes".into(), ..Default::default() }.reads_develop()); + // a search field not known to be free of develop state counts as reading it + assert!(Filter { text: "cropped:yes".into(), ..Default::default() }.reads_develop()); + assert!(!Filter { text: "harbour kw:travel F:<4 camera:x100".into(), ..Default::default() }.reads_develop()); + assert!(Sort { key: SortKey::EditDate, ..Default::default() }.reads_develop()); + assert!(!Sort { key: SortKey::FileName, ..Default::default() }.reads_develop()); + assert!(!Sort { key: SortKey::Random, seed: 7, ..Default::default() }.reads_develop()); + for field in ["edited", "cropped", "treatment", "editDate", "longEdge", "shortEdge", "aspect", "megapixels"] { + let nested = rules( + json!({"rules": [{"field": "rating", "op": ">=", "value": 1}, {"group": {"match": "any", "rules": [{"field": field, "op": "is", "value": true}]}}]}), + ); + assert!(nested.reads_develop(), "{field}"); + } + assert!( + !rules(json!({"rules": [{"field": "rating", "op": ">=", "value": 1}, {"field": "keywords", "op": "contains", "value": "x"}]})) + .reads_develop() + ); + } + + /// Every rule field is either known not to read develop state or counts as reading it: a new field must be put + /// on one side on purpose. + #[test] + fn every_rule_field_is_classified() { + let reads: Vec<&str> = crate::rules::FIELDS.iter().map(|f| f.0).filter(|f| field_reads_develop(f)).collect(); + assert_eq!(reads, ["editDate", "longEdge", "shortEdge", "aspect", "megapixels", "edited", "cropped", "treatment"]); + for f in FIELDS_WITHOUT_DEVELOP { + assert!(crate::rules::FIELDS.iter().any(|x| x.0 == *f), "{f} is not a rule field"); + } + } + + /// Every filter field is classified: a field added to `Filter` stops this from compiling until it is listed + /// here, on the side it belongs to (and in `Filter::reads_develop` if it reads develop state). + #[test] + fn every_filter_field_is_classified() { + #[rustfmt::skip] + let Filter { + // read develop state (`Filter::reads_develop`) + edited: _, text: _, rule_set: _, + // what an album holds: `Catalog::filter_reads_develop` follows it + album: _, + // don't + rating: _, rating_op: _, flag: _, label: _, only: _, only_none: _, labels: _, kind: _, deleted: _, date: _, + library_folder: _, keyword: _, person: _, camera: _, lens: _, date_from: _, date_to: _, imported: _, + imported_from: _, merged: _, folder: _, subfolders: _, flags: _, + } = Filter::default(); + } + + #[test] + fn smart_albums_read_develop_through_the_albums_they_test() { + let mut c = Catalog::new(); + c.apply(smart(1, rules(json!({"rules": [{"field": "rating", "op": ">=", "value": 3}]})))).unwrap(); + c.apply(smart(2, rules(json!({"rules": [{"field": "edited", "op": "is", "value": true}]})))).unwrap(); + // 3 tests 2 (which reads develop); 4 and 5 test each other (a loop) and 1 + c.apply(smart(3, rules(json!({"rules": [{"field": "album", "op": "is", "value": 2}]})))).unwrap(); + c.apply(smart(4, rules(json!({"rules": [{"field": "album", "op": "is", "value": 5}, {"field": "album", "op": "is", "value": 1}]})))).unwrap(); + c.apply(smart(5, rules(json!({"rules": [{"field": "album", "op": "is", "value": 4}]})))).unwrap(); + c.apply(Op::AddAlbum { album: Album::new(AlbumId(6), "Plain") }).unwrap(); + let reads = |id: u64| c.album_reads_develop(AlbumId(id)); + assert_eq!([1, 2, 3, 4, 5, 6, 7].map(reads), [false, true, true, false, false, false, false]); + assert!(c.filter_reads_develop(&Filter { album: Some(AlbumId(3)), ..Default::default() })); + assert!(!c.filter_reads_develop(&Filter { album: Some(AlbumId(4)), ..Default::default() })); + assert_eq!(c.filter_reads(&Filter { album: Some(AlbumId(3)), ..Default::default() }), Aspects::ALL); + assert_eq!(c.filter_reads(&Filter { album: Some(AlbumId(4)), ..Default::default() }), Aspects::ALL_BUT_DEVELOP); + } + + /// A develop edit (settings and a History step, as a slider tick commits them) leaves what reads everything but + /// develop state; a rating, or a change whose reach isn't known, doesn't. + #[test] + fn develop_edits_leave_what_reads_no_develop_state() { + let mut c = Catalog::new(); + c.apply(Op::AddPhoto { photo: Box::new(photo(1)) }).unwrap(); + let start = c.revision; + let mut s = (*c.photo(PhotoId(1)).unwrap().develop).clone(); + s.light.exposure = 1.0; + let set = + Op::SetDevelop { id: PhotoId(1), settings: Arc::new(s.clone()), label: "Exposure".into(), edited: Some("2026-02-01T00:00:00".into()) }; + let step = Op::PushHistory { id: PhotoId(1), step: crate::HistoryStep { label: "Exposure".into(), settings: Arc::new(s) } }; + c.apply(Op::Batch { ops: vec![set, step] }).unwrap(); + assert!(c.unchanged_for(start, Aspects::ALL_BUT_DEVELOP)); + assert!(!c.unchanged_for(start, Aspects::ALL)); + assert!(c.unchanged_for(c.revision, Aspects::ALL), "nothing since"); + let before_rating = c.revision; + c.apply(Op::SetRating { id: PhotoId(1), rating: 3 }).unwrap(); + assert!(!c.unchanged_for(start, Aspects::ALL_BUT_DEVELOP)); + assert!(!c.unchanged_for(before_rating, Aspects::ALL_BUT_DEVELOP)); + // an album: what it changed for which photos is not known + let before_album = c.revision; + c.apply(Op::AddAlbum { album: Album::new(AlbumId(1), "Trip") }).unwrap(); + assert!(!c.unchanged_for(before_album, Aspects::ALL_BUT_DEVELOP)); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dd67b755f90..905e2dd9e42 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -243,10 +243,11 @@ pub struct Session { pub(crate) shelved_filter: Option, pub sort: Sort, pub selection: Selection, - /// The grid order for the current source/filter/sort (cached by catalog revision). + /// The grid order for the current source/filter/sort (cached by catalog revision, and kept through an edit + /// that changed nothing the view reads: see [`Session::visible`]). /// Shared, so frontends can hold it across frames without copying ([`Session::visible_shared`]). visible: Arc<[PhotoId]>, - visible_key: Option<(u64, String)>, + visible_key: Option, /// The minute used for a cached view whose rules depend on the session clock. visible_clock_minute: Option, /// A view holds the photos it shows until it is refreshed (`library.holdView`): an edit that makes a photo stop @@ -261,6 +262,9 @@ pub struct Session { /// every photo (`ui.inspect` → `perf`): what tells a slow library from a slow edit. pub view_followed: u64, pub view_worked_out: u64, + /// How many times an edit changed nothing the view reads (a slider tick in a view that reads no develop state), + /// so the list was kept as it was. + pub view_kept: u64, /// Tests: work the view out whole every time (what following has to equal). #[cfg(test)] never_follow: bool, @@ -268,7 +272,7 @@ pub struct Session { /// is recomputed, so frontends can key their per-view caches on it instead of hashing the ids. visible_gen: u64, /// Photos in the current source with no filter on (cached like `visible`). - total: Option<((u64, String), usize, Option)>, + total: Option<(ViewKey, usize, Option)>, pub undo: Vec, /// Undo steps committed in this session, ever (the history drops its oldest past 1000, so /// its length can't tell how many steps a command just made; see [`Session::commits`]). @@ -483,6 +487,7 @@ impl Session { base: None, view_followed: 0, view_worked_out: 0, + view_kept: 0, #[cfg(test)] never_follow: false, visible_gen: 0, @@ -1179,8 +1184,33 @@ impl Session { /// Photos shown in the grid/filmstrip for the current source, filter and sort. pub fn visible(&mut self) -> &[PhotoId] { - let mut key = - (self.catalog.revision, format!("{:?}|{:?}|{:?}|{:?}|{:?}", self.source, self.filter, self.sort, self.browse, self.library_folder)); + // the view fills in as the background checks find files gone (a file found there at its first check changes + // nothing it shows) + let availability = + (self.source == LibrarySource::Missing && self.media.availability.is_background()).then(|| self.media.availability.gone_generation()); + // A time-dependent cache needs one clock read to test its minute stamp. + let current_now = self.visible_clock_minute.is_some().then(|| (self.clock)()); + let clock_changed = self.visible_clock_minute.as_deref().is_some_and(|cached| current_now.as_deref().map(clock_minute) != Some(cached)); + let revision = self.catalog.revision; + if !clock_changed && let Some(at) = self.visible_key.as_ref().filter(|k| k.is(self, true, availability)).map(|k| k.revision) { + if at == revision { + return &self.visible; + } + if self.reads(&self.filter, Some(&self.sort)).is_some_and(|reads| self.catalog.unchanged_for(at, reads)) { + // an edit that changed nothing the view reads (a slider tick, where nothing asks about develop + // state): the same list, under the same generation, so nothing derived from it is worked out again + self.view_kept += 1; + if let Some(k) = &mut self.visible_key { + k.revision = revision; + } + if let Some(base) = self.base.as_mut().filter(|b| b.1 == at) { + base.1 = revision; + } + return &self.visible; + } + } + let key = ViewKey::of(self, true, availability); + let shown = 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. @@ -1190,124 +1220,111 @@ impl Session { 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 (a file found there at - // its first check changes nothing it shows) - key.1.push_str(&format!("|{}", self.media.availability.gone_generation())); - } - let key_changed = self.visible_key.as_ref() != Some(&key); - // A time-dependent cache needs one clock read to test its minute stamp. A new view also - // needs one value for the query, even when its previous cached view did not use the clock. - let current_now = (key_changed || self.visible_clock_minute.is_some()).then(|| (self.clock)()); - let current_minute = current_now.as_deref().map(clock_minute); - let clock_changed = self.visible_clock_minute.as_deref().is_some_and(|cached| current_minute != Some(cached)); - if key_changed || clock_changed { - // Use this same value to evaluate relative rules and stamp the result. - let now = current_now.unwrap_or_else(|| (self.clock)()); - lightcraft_catalog::rules::set_now(Some(now.clone())); - 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 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()) - } - }); - // 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 = filter_depends_on_clock(&f, &self.catalog); - 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 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 - self.source = LibrarySource::All; - self.library_folder = None; - return self.visible(); + let view = format!("{shown}|{rules}"); + // the same clock reading as the minute tested above evaluates relative rules and stamps the result + let now = current_now.unwrap_or_else(|| (self.clock)()); + lightcraft_catalog::rules::set_now(Some(now.clone())); + 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 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()) } - if matches!(self.source, LibrarySource::Album(_)) - && self.sort.key == lightcraft_catalog::SortKey::CaptureDate - && let LibrarySource::Album(a) = self.source - && let Some(al) = self.catalog.album(a) - && !al.is_smart() - && self.filter == Filter::default() - { - // each photo's place looked up, not searched for (a big album sorted in O(n log n)) - let mut place: std::collections::HashMap = std::collections::HashMap::with_capacity(al.photos.len()); - for (i, id) in al.photos.iter().enumerate() { - place.entry(*id).or_insert(i); - } - visible.sort_by_key(|id| place.get(id).copied().unwrap_or(usize::MAX)); - if !self.sort.ascending { - visible.reverse(); - } - } - if self.source == LibrarySource::RecentlyAdded { - // newest import first, whatever the sort direction (the grid groups by import day); - // a batch stays in file order (name, then id) - let cat = &self.catalog; - visible.sort_by(|a, b| { - let key = |id: &PhotoId| cat.photo(*id).map(|p| p.imported.clone()).unwrap_or_default(); - let name = |id: &PhotoId| cat.photo(*id).map(|p| p.file_name.as_str()); - let by_name = match (name(a), name(b)) { - (Some(x), Some(y)) => lightcraft_catalog::query::cmp_name(x, y), - _ => std::cmp::Ordering::Equal, - }; - key(b).cmp(&key(a)).then(by_name).then(a.cmp(b)) - }); + }); + // 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 = filter_depends_on_clock(&f, &self.catalog); + 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) } - if self.source == LibrarySource::Missing { - // only the photos the query kept (library photos, not Local browse records) are checked - let (cat, avail) = (&self.catalog, &self.media.availability); - visible.retain(|id| cmd::missing::is_missing(cat, avail, *id)); + _ => self.catalog.query(&f, &self.sort), + }; + // 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 + self.source = LibrarySource::All; + self.library_folder = None; + return self.visible(); + } + if matches!(self.source, LibrarySource::Album(_)) + && self.sort.key == lightcraft_catalog::SortKey::CaptureDate + && let LibrarySource::Album(a) = self.source + && let Some(al) = self.catalog.album(a) + && !al.is_smart() + && self.filter == Filter::default() + { + // each photo's place looked up, not searched for (a big album sorted in O(n log n)) + let mut place: std::collections::HashMap = std::collections::HashMap::with_capacity(al.photos.len()); + for (i, id) in al.photos.iter().enumerate() { + place.entry(*id).or_insert(i); } - if self.source != LibrarySource::RecentlyDeleted { - visible = self.catalog.arrange_stacks(&visible); + visible.sort_by_key(|id| place.get(id).copied().unwrap_or(usize::MAX)); + if !self.sort.ascending { + visible.reverse(); } - self.visible = visible.into(); - self.visible_gen = VISIBLE_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - self.visible_key = Some(key); - self.visible_clock_minute = clocked.then(|| clock_minute(&now).to_owned()); } + if self.source == LibrarySource::RecentlyAdded { + // newest import first, whatever the sort direction (the grid groups by import day); + // a batch stays in file order (name, then id) + let cat = &self.catalog; + visible.sort_by(|a, b| { + let key = |id: &PhotoId| cat.photo(*id).map(|p| p.imported.clone()).unwrap_or_default(); + let name = |id: &PhotoId| cat.photo(*id).map(|p| p.file_name.as_str()); + let by_name = match (name(a), name(b)) { + (Some(x), Some(y)) => lightcraft_catalog::query::cmp_name(x, y), + _ => std::cmp::Ordering::Equal, + }; + key(b).cmp(&key(a)).then(by_name).then(a.cmp(b)) + }); + } + if self.source == LibrarySource::Missing { + // only the photos the query kept (library photos, not Local browse records) are checked + let (cat, avail) = (&self.catalog, &self.media.availability); + visible.retain(|id| cmd::missing::is_missing(cat, avail, *id)); + } + if self.source != LibrarySource::RecentlyDeleted { + visible = self.catalog.arrange_stacks(&visible); + } + self.visible = visible.into(); + self.visible_gen = VISIBLE_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.visible_key = Some(key); + self.visible_clock_minute = clocked.then(|| clock_minute(&now).to_owned()); &self.visible } @@ -1347,12 +1364,22 @@ impl Session { self.visible_gen, self.view_followed, self.view_worked_out, + self.view_kept, ); 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_clock_minute, self.visible, self.visible_gen, self.view_followed, self.view_worked_out) = kept; + ( + self.base, + self.visible_key, + self.visible_clock_minute, + self.visible, + self.visible_gen, + self.view_followed, + self.view_worked_out, + self.view_kept, + ) = kept; whole } @@ -1379,13 +1406,22 @@ impl Session { return Some(ids.len()); } } - let key = (self.catalog.revision, format!("{:?}|{:?}|{:?}", self.source, self.browse, self.library_folder)); - let key_changed = self.total.as_ref().map(|total| &total.0) != Some(&key); let cached_minute = self.total.as_ref().and_then(|total| total.2.as_deref()); let current_now = cached_minute.map(|_| (self.clock)()); let current_minute = current_now.as_deref().map(clock_minute); let clock_changed = cached_minute.is_some_and(|cached| current_minute != Some(cached)); - if key_changed || clock_changed { + let revision = self.catalog.revision; + let counted = self.total.as_ref().filter(|(k, _, _)| k.is(self, false, None)).map(|(k, _, _)| k.revision); + let kept = !clock_changed + && counted + .is_some_and(|at| at == revision || self.reads(&Filter::default(), None).is_some_and(|reads| self.catalog.unchanged_for(at, reads))); + if kept { + // (an edit that changed nothing the source reads: the same count) + if let Some((k, _, _)) = &mut self.total { + k.revision = revision; + } + } else { + let key = ViewKey::of(self, false, None); // The source count can be requested before `visible`; bind it to the session's clock itself. let now = current_now.unwrap_or_else(|| (self.clock)()); lightcraft_catalog::rules::set_now(Some(now.clone())); @@ -1406,6 +1442,24 @@ impl Session { self.total.as_ref().map(|t| t.1) } + /// What of a photo the current source, through `filter` and `sort`, reads: everything but develop state, unless + /// one of them (or a smart album they test) reads that too. `None` for a view that also follows the clock (an + /// "in the last N days" rule: a photo nobody touched can stop matching), which is asked again after every edit. + fn reads(&self, filter: &Filter, sort: Option<&Sort>) -> Option { + let album = match self.source { + LibrarySource::Album(a) => Some(a), + _ => None, + }; + let tests_albums = album.is_some() || !filter.albums_tested().is_empty(); + if filter.depends_on_now() || (tests_albums && self.catalog.albums().any(|al| al.smart.as_deref().is_some_and(Filter::depends_on_now))) { + return None; + } + let develop = sort.is_some_and(Sort::reads_develop) + || self.catalog.filter_reads_develop(filter) + || album.is_some_and(|a| self.catalog.album_reads_develop(a)); + Some(if develop { lightcraft_catalog::Aspects::ALL } else { lightcraft_catalog::Aspects::ALL_BUT_DEVELOP }) + } + pub fn visible_cloned(&mut self) -> Vec { self.visible().to_vec() } @@ -1426,7 +1480,7 @@ impl Session { } /// The visible photos without copying them, with their generation: equal generations mean - /// the very same list (same catalog revision, source, filter, sort), so a frontend can cache + /// the very same list (same source, filter, sort, and no edit to what they read), so a frontend can cache /// whatever it derives from the list under that number. pub fn visible_shared(&mut self) -> (u64, Arc<[PhotoId]>) { self.visible(); @@ -1455,6 +1509,43 @@ impl Session { } } +/// What [`Session::visible`] (or [`Session::source_total`]) was worked out from. Compared every frame, so without +/// formatting or copying anything. +#[derive(Clone, Debug, PartialEq)] +struct ViewKey { + /// The catalog's revision then, or since: an edit that changed nothing the view reads moves it on. + revision: u64, + source: LibrarySource, + /// The filter bar and sort (`None` for the source total, which ignores them). + view: Option<(Filter, Sort)>, + browse: Option, + library_folder: Option, + /// The background checks' generation of files found gone, for Missing Photos while they run. + availability: Option, +} + +impl ViewKey { + fn of(s: &Session, filtered: bool, availability: Option) -> ViewKey { + ViewKey { + revision: s.catalog.revision, + source: s.source, + view: filtered.then(|| (s.filter.clone(), s.sort)), + browse: s.browse.clone(), + library_folder: s.library_folder.clone(), + availability, + } + } + + /// Whether this is the key of the view `s` shows now, at whatever revision. + fn is(&self, s: &Session, filtered: bool, availability: Option) -> bool { + let view = match &self.view { + Some((f, sort)) => filtered && *f == s.filter && *sort == s.sort, + None => !filtered, + }; + self.source == s.source && view && self.browse == s.browse && self.library_folder == s.library_folder && self.availability == availability + } +} + /// Automatic versions kept per photo. pub const AUTO_VERSIONS: usize = 20; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 958c1228712..1861fe3cf40 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -31,6 +31,7 @@ mod hold_view; mod ids_params; mod import; mod import_move; +mod invalidation; mod keyword_list; mod lens_refresh; mod libops; diff --git a/crates/engine/src/tests/invalidation.rs b/crates/engine/src/tests/invalidation.rs new file mode 100644 index 00000000000..1ba3db2f079 --- /dev/null +++ b/crates/engine/src/tests/invalidation.rs @@ -0,0 +1,251 @@ +//! What a develop edit invalidates: a slider tick changes one photo's develop settings, so a view that reads no +//! develop state keeps its list (same generation, nothing derived from it worked out again), and the views that do +//! read it follow the edit (see `lightcraft_catalog::reads`). + +use lightcraft_catalog::{Album, AlbumId, Filter, Op, Photo, PhotoId, RuleSet, Sort, SortKey, Source}; +use serde_json::json; + +use crate::{LibrarySource, Session}; + +/// A library of `n` photos with capture dates and a keyword each. +fn library(n: u64) -> Session { + let mut s = Session::new(); + let ops = (0..n) + .map(|i| { + let mut p = Photo::new( + PhotoId(i + 1), + Source::Demo { scene: (i % 20) as u32 }, + &format!("IMG_{i:06}.jpg"), + "JPEG", + 6000, + 4000, + "2026-01-01T00:00:00", + ); + p.captured = Some(format!("20{:02}-{:02}-{:02}T10:00:00", 10 + i % 16, 1 + i % 12, 1 + i % 28)); + p.meta.keywords = vec![format!("kw{}", i % 300)]; + Op::AddPhoto { photo: Box::new(p) } + }) + .collect(); + s.commit("Add", Op::Batch { ops }).unwrap(); + s +} + +/// Change photo `id`'s exposure (a committed edit, or a slider tick inside an interaction). +fn expose(s: &mut Session, id: PhotoId, ev: f64) { + let mut d = (*s.develop_of(id).unwrap()).clone(); + d.light.exposure = ev; + s.set_develop(id, d, "Exposure").unwrap(); +} + +fn crop(s: &mut Session, id: PhotoId, rect: lightcraft_geom::Rect) { + let mut d = (*s.develop_of(id).unwrap()).clone(); + d.crop.geometry.rect = rect; + s.set_develop(id, d, "Crop").unwrap(); +} + +fn smart(s: &mut Session, id: u64, rules: serde_json::Value) { + let mut a = Album::new(AlbumId(id), format!("Smart {id}")); + let rules: RuleSet = serde_json::from_value(rules).unwrap(); + a.smart = Some(Box::new(Filter { rule_set: Some(rules), ..Default::default() })); + s.commit("New Smart Album", Op::AddAlbum { album: a }).unwrap(); +} + +/// Slider ticks and committed develop edits leave the grid's list as it is (same generation, the very same list) +/// when nothing in view reads develop state; a library change still redoes it. +#[test] +fn develop_edits_keep_the_view() { + let mut s = library(50); + let (generation, list) = s.visible_shared(); + let total = s.source_total(); + let id = s.visible()[7]; + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("develop.beginInteraction", &json!({"label": "Exposure"})).unwrap(); + for i in 0..10 { + s.execute("develop.set", &json!({"control": "light.exposure", "value": i as f64 / 10.0})).unwrap(); + assert_eq!(s.visible_shared().0, generation, "tick {i}"); + } + s.execute("develop.endInteraction", &json!({})).unwrap(); + expose(&mut s, id, 2.0); + s.execute("edit.undo", &json!({})).unwrap(); + let (kept, same) = s.visible_shared(); + assert_eq!(kept, generation, "a committed edit and its undo"); + assert!(std::sync::Arc::ptr_eq(&list, &same)); + assert_eq!(s.source_total(), total); + // (ten ticks, then the edit and its undo before the view was asked again) + assert_eq!(s.view_kept, 11); + // a library change does + s.execute("photo.rate", &json!({"rating": 4})).unwrap(); + assert_ne!(s.visible_shared().0, generation); +} + +/// Filters, sorts and smart albums that read develop state follow every develop edit, slider ticks included. +#[test] +fn views_that_read_develop_state_follow_develop_edits() { + let mut s = library(20); + let ids = s.visible().to_vec(); + let (a, b) = (ids[3], ids[11]); + s.execute("library.select", &json!({"ids": [a.0]})).unwrap(); + + // the filter bar's Edited, during a drag + s.filter = Filter { edited: Some(true), ..Default::default() }; + assert!(s.visible().is_empty()); + s.execute("develop.beginInteraction", &json!({"label": "Exposure"})).unwrap(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.5})).unwrap(); + assert_eq!(s.visible(), [a], "a slider tick makes the photo edited"); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.0})).unwrap(); + assert!(s.visible().is_empty(), "and back"); + s.execute("develop.endInteraction", &json!({})).unwrap(); + // a search token + s.filter = Filter { text: "edited:yes".into(), ..Default::default() }; + expose(&mut s, b, 1.0); + assert_eq!(s.visible(), [b]); + + // Edit Date: the photo edited last comes first + s.filter = Filter::default(); + s.sort = Sort { key: SortKey::EditDate, ascending: false, ..Default::default() }; + s.clock = Box::new(|| "2100-05-01T10:00:00".to_string()); + expose(&mut s, a, 0.3); + assert_eq!(s.visible()[0], a); + s.clock = Box::new(|| "2100-05-01T11:00:00".to_string()); + expose(&mut s, b, 0.7); + assert_eq!(s.visible()[0], b); + + // a smart album testing Cropped, and one testing it through an Album rule + s.sort = Sort::default(); + smart(&mut s, 100, json!({"rules": [{"field": "cropped", "op": "is", "value": true}]})); + smart(&mut s, 101, json!({"rules": [{"field": "album", "op": "is", "value": 100}]})); + for album in [100, 101] { + s.source = LibrarySource::Album(AlbumId(album)); + assert!(s.visible().is_empty()); + assert_eq!(s.source_total(), Some(0)); + } + crop(&mut s, a, lightcraft_geom::Rect::new(0.1, 0.1, 0.9, 0.9)); + for album in [100, 101] { + s.source = LibrarySource::Album(AlbumId(album)); + assert_eq!(s.visible(), [a], "album {album}"); + assert_eq!(s.source_total(), Some(1), "album {album}"); + } + // and the size rules (a crop changes the shown shape) + s.source = LibrarySource::All; + let square: RuleSet = serde_json::from_value(json!({"rules": [{"field": "aspect", "op": "is", "value": "square"}]})).unwrap(); + s.filter = Filter { rule_set: Some(square), ..Default::default() }; + assert!(s.visible().is_empty()); + crop(&mut s, b, lightcraft_geom::Rect::new(0.0, 0.0, 4000.0 / 6000.0, 1.0)); + assert_eq!(s.visible(), [b]); +} + +/// Random slider ticks, committed exposures and crops, ratings and undos, in views that read develop state and +/// views that don't: what each shows (and its source's count) is what asking every photo gives, and the views that +/// read no develop state kept their list through the develop edits. +#[test] +fn kept_and_followed_views_are_what_a_full_query_gives() { + let mut s = library(120); + smart(&mut s, 100, json!({"rules": [{"field": "edited", "op": "is", "value": true}]})); + smart(&mut s, 101, json!({"rules": [{"field": "cropped", "op": "is", "value": true}]})); + smart(&mut s, 102, json!({"rules": [{"field": "album", "op": "is", "value": 101}]})); + smart(&mut s, 103, json!({"rules": [{"field": "keywords", "op": "contains", "value": "kw1"}]})); + let ids = s.visible().to_vec(); + let sources = [ + LibrarySource::All, + LibrarySource::Album(AlbumId(100)), + LibrarySource::Album(AlbumId(101)), + LibrarySource::Album(AlbumId(102)), + LibrarySource::Album(AlbumId(103)), + ]; + let filters = [ + Filter::default(), + Filter { edited: Some(false), ..Default::default() }, + Filter { text: "edited:yes".into(), ..Default::default() }, + Filter { keyword: Some("kw2".into()), ..Default::default() }, + Filter { album: Some(AlbumId(101)), ..Default::default() }, + ]; + let sorts = [SortKey::CaptureDate, SortKey::EditDate, SortKey::FileName]; + let mut n = 0u64; + let mut seconds = 0u64; + for (i, source) in sources.iter().enumerate() { + for (j, filter) in filters.iter().enumerate() { + s.source = *source; + s.filter = filter.clone(); + s.sort = Sort { key: sorts[(i + j) % sorts.len()], ..Default::default() }; + let _ = s.visible(); + for step in 0..24 { + n += 1; + seconds += 1; + let at = format!("2100-01-01T00:{:02}:{:02}", (seconds / 60) % 60, seconds % 60); + s.clock = Box::new(move || at.clone()); + let id = ids[(n * 37 % ids.len() as u64) as usize]; + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + match n % 8 { + 0..=3 => { + s.execute("develop.beginInteraction", &json!({"label": "Exposure"})).unwrap(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": (n % 5) as f64 / 4.0})).unwrap(); + s.execute("develop.endInteraction", &json!({})).unwrap(); + } + 4 => expose(&mut s, id, 0.0), + 5 => crop(&mut s, id, lightcraft_geom::Rect::new(0.0, 0.0, if n.is_multiple_of(3) { 1.0 } else { 0.8 }, 1.0)), + 6 => s.execute("photo.rate", &json!({"rating": n % 6})).map(|_| ()).unwrap(), + _ => { + let _ = s.undo_step(); + } + } + let shown = s.visible_cloned(); + let whole = s.visible_in_full(); + assert_eq!(shown, whole, "source {source:?}, filter {filter:?}, sort {:?}, edit {step}", s.sort.key); + let counted = s.catalog.count(&s.source.to_filter(&Filter::default(), &s.catalog)); + assert_eq!(s.source_total(), Some(counted), "source {source:?}, edit {step}"); + } + } + } + // both were checked: most of these views read develop state and follow each edit; the others kept their list + // through the develop edits + let (kept, followed) = (s.view_kept, s.view_followed); + assert!(kept >= 30 && followed > 300, "kept {kept} times, followed {followed}, worked out {}", s.view_worked_out); +} + +/// A view that asks about "the last N days" changes with the clock as well as with edits: a develop edit asks it +/// again, as every edit did before. +#[test] +fn a_view_that_follows_the_clock_is_asked_again_after_a_develop_edit() { + let mut s = library(10); + smart(&mut s, 100, json!({"rules": [{"field": "captureDate", "op": "inLast", "value": 30}]})); + s.source = LibrarySource::Album(AlbumId(100)); + let (generation, _) = s.visible_shared(); + let id = s.catalog.photos().next().unwrap().id; + expose(&mut s, id, 1.0); + assert_ne!(s.visible_shared().0, generation); +} + +/// Per-tick cost of a slider drag on a big library (the develop op plus the grid query the filmstrip asks for every +/// frame): `cargo test --release -p lightcraft-engine -- --ignored drag_tick_100k --nocapture`. +#[test] +#[ignore = "a measurement: run with --ignored --nocapture"] +fn drag_tick_100k() { + let mut s = library(100_000); + let id = s.visible()[50_000]; + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("develop.beginInteraction", &json!({"label": "Exposure"})).unwrap(); + let n = 60; + let tick = |s: &mut Session, name: &str| { + s.visible(); + s.source_total(); + let t = std::time::Instant::now(); + for i in 0..n { + s.execute("develop.set", &json!({"control": "light.exposure", "value": i as f64 / 100.0})).unwrap(); + s.visible(); + s.source_total(); + } + let ms = t.elapsed().as_secs_f64() * 1e3 / n as f64; + eprintln!("slider tick at 100k photos, {name}: {ms:.3} ms (develop.set + visible + source_total)"); + }; + tick(&mut s, "warm-up"); + tick(&mut s, "by capture date"); + s.sort = Sort { key: SortKey::FileName, ..Default::default() }; + tick(&mut s, "by file name"); + s.sort = Sort::default(); + s.filter = Filter { keyword: Some("kw7".into()), ..Default::default() }; + tick(&mut s, "keyword filter"); + // a view that reads develop state follows each tick from the photo it touched + s.filter = Filter { edited: Some(false), ..Default::default() }; + tick(&mut s, "Unedited filter"); + s.execute("develop.endInteraction", &json!({})).unwrap(); +} diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 93fe551847f..b142c6f4f7b 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -33,8 +33,8 @@ pub(crate) fn key_of(parts: impl std::hash::Hash) -> u64 { /// `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)) +pub(crate) fn still_right(cat: &lightcraft_catalog::Catalog, revision: u64, reads: lightcraft_catalog::Aspects) -> bool { + cat.unchanged_for(revision, reads) } /// What the tallies below read of a photo, besides whether it is in the library. @@ -48,6 +48,9 @@ const READS_CAPTURED: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects: const READS_FLAG: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::FLAG); +/// What reads anything of a photo but its develop state (a slider tick leaves it). +pub(crate) const READS_NO_DEVELOP: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::ALL_BUT_DEVELOP; + impl Caches { /// The folders the library's photos were imported from. pub fn folder_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { @@ -76,8 +79,11 @@ impl Caches { export: bool, ) -> std::sync::Arc> { let key = key_of((selection, export)); - match &self.keyword_names { - Some((r, k, c)) if *r == cat.revision && *k == key => c.clone(), + match &mut self.keyword_names { + Some((r, k, c)) if *k == key && still_right(cat, *r, READS_META) => { + *r = cat.revision; + c.clone() + } _ => { let c = std::sync::Arc::new(if export { panels::keywording::will_export(cat, selection) @@ -96,8 +102,11 @@ impl Caches { selection: &[lightcraft_catalog::PhotoId], ) -> std::sync::Arc> { let key = key_of(selection); - match &self.keyword_chips { - Some((r, k, c)) if *r == cat.revision && *k == key => c.clone(), + match &mut self.keyword_chips { + Some((r, k, c)) if *k == key && still_right(cat, *r, READS_META) => { + *r = cat.revision; + c.clone() + } _ => { let c = std::sync::Arc::new(panels::keywording::chips(cat, selection)); self.keyword_chips = Some((cat.revision, key, c.clone())); @@ -109,8 +118,11 @@ impl Caches { /// box's "N of M" counts). pub(crate) fn selected_photos(&mut self, cat: &lightcraft_catalog::Catalog, selection: &[lightcraft_catalog::PhotoId]) -> usize { let key = key_of(selection); - match self.selected_photos { - Some((r, k, n)) if r == cat.revision && k == key => n, + match &mut self.selected_photos { + Some((r, k, n)) if *k == key && still_right(cat, *r, READS_NO_DEVELOP) => { + *r = cat.revision; + *n + } _ => { let n = panels::keywording::distinct(cat, selection).len(); self.selected_photos = Some((cat.revision, key, n)); @@ -125,8 +137,11 @@ impl Caches { selection: &[lightcraft_catalog::PhotoId], ) -> std::sync::Arc> { let key = key_of(selection); - match &self.keyword_groups { - Some((r, k, g)) if *r == cat.revision && *k == key => g.clone(), + match &mut self.keyword_groups { + Some((r, k, g)) if *k == key && still_right(cat, *r, READS_META) => { + *r = cat.revision; + g.clone() + } _ => { let chips = self.keyword_chips(cat, selection); let g = std::sync::Arc::new(panels::keywording::grouped(&chips)); @@ -142,8 +157,11 @@ impl Caches { selection: &[lightcraft_catalog::PhotoId], ) -> std::sync::Arc { let key = key_of(selection); - match &self.keyword_ticks { - Some((r, k, t)) if *r == cat.revision && *k == key => t.clone(), + match &mut self.keyword_ticks { + Some((r, k, t)) if *k == key && still_right(cat, *r, READS_META) => { + *r = cat.revision; + t.clone() + } _ => { let t = std::sync::Arc::new(panels::keyword_list::Ticks::of(cat, selection)); self.keyword_ticks = Some((cat.revision, key, t.clone())); @@ -159,8 +177,12 @@ impl Caches { filter: &lightcraft_catalog::Filter, ) -> std::sync::Arc> { let key = lightcraft_catalog::Filter { person: None, ..filter.clone() }; - match &self.people { - Some((r, f, t)) if *r == cat.revision && *f == key => t.clone(), + // (develop state only when the filter, or a smart album it tests, reads it) + match &mut self.people { + Some((r, f, t)) if *f == key && still_right(cat, *r, cat.filter_reads(&key)) => { + *r = cat.revision; + t.clone() + } _ => { let t = std::sync::Arc::new(cat.people_in(&key)); self.people = Some((cat.revision, key, t.clone())); @@ -206,8 +228,11 @@ impl Caches { } /// Cameras, lenses and keywords in the library (filter bar pickers). pub fn filter_values(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc { - match &self.filter_values { - Some((r, v)) if *r == cat.revision => v.clone(), + match &mut self.filter_values { + Some((r, v)) if still_right(cat, *r, READS_META) => { + *r = cat.revision; + v.clone() + } _ => { let distinct = |mut v: Vec| { v.retain(|s| !s.trim().is_empty()); @@ -235,24 +260,30 @@ impl Caches { current: &[String], typed: &str, ) -> std::sync::Arc { - let k = key_of((cat.revision, current, typed)); - match &self.completions { - Some((h, v)) if *h == k => v.clone(), + let k = key_of((current, typed)); + match &mut self.completions { + Some((r, h, v)) if *h == k && still_right(cat, *r, READS_META) => { + *r = cat.revision; + v.clone() + } _ => { let v = std::sync::Arc::new(panels::keywording::offers(cat, current, typed)); - self.completions = Some((k, v.clone())); + self.completions = Some((cat.revision, k, v.clone())); v } } } /// Keyword suggestions for a photo with `current` keywords and the typed `prefix`. pub fn suggestions(&mut self, cat: &lightcraft_catalog::Catalog, current: &[String], prefix: &str, n: usize) -> std::sync::Arc> { - let k = key_of((cat.revision, current, prefix, n)); - match &self.suggestions { - Some((h, v)) if *h == k => v.clone(), + let k = key_of((current, prefix, n)); + match &mut self.suggestions { + Some((r, h, v)) if *h == k && still_right(cat, *r, READS_META) => { + *r = cat.revision; + v.clone() + } _ => { let v = std::sync::Arc::new(cat.keyword_suggestions(current, prefix, n)); - self.suggestions = Some((k, v.clone())); + self.suggestions = Some((cat.revision, k, v.clone())); v } } @@ -275,10 +306,14 @@ impl Caches { ) -> std::sync::Arc { let relative = rules.depends_on_now(); let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; - let k = key_of((cat.revision, serde_json::to_string(rules).unwrap_or_default(), editing, &folder, minute, i18n::language().code())); - if let Some((key, v)) = &self.rules_view + let k = key_of((serde_json::to_string(rules).unwrap_or_default(), editing, &folder, minute, i18n::language().code())); + // (the count follows a develop edit only when the rules, or the smart albums they test, read develop state) + let reads = cat.filter_reads(&lightcraft_catalog::Filter { rule_set: Some(rules.clone()), ..Default::default() }); + if let Some((r, key, v)) = &mut self.rules_view && *key == k + && still_right(cat, *r, reads) { + *r = cat.revision; return v.clone(); } if relative { @@ -289,7 +324,7 @@ impl Caches { let count = if problems.is_empty() { cat.query(&filter, &Default::default()).len() } else { 0 }; let v = std::sync::Arc::new(RulesView { problems, count, albums: panels::dialogs::album_entries(cat, editing) }); self.rules_view_scans += 1; - self.rules_view = Some((k, v.clone())); + self.rules_view = Some((cat.revision, k, v.clone())); v } @@ -314,9 +349,10 @@ impl Caches { &mut self, cat: &lightcraft_catalog::Catalog, ) -> std::sync::Arc>> { - if let Some((rev, v)) = &self.smart_problems - && *rev == cat.revision + if let Some((rev, v)) = &mut self.smart_problems + && still_right(cat, *rev, READS_NO_DEVELOP) { + *rev = cat.revision; return v.clone(); } let v: std::sync::Arc> = std::sync::Arc::new( @@ -386,6 +422,64 @@ mod cache_tests { Op::AddAlbum { album: a } } + /// A develop edit (one slider tick: settings, edit time and a History step) changes nothing the sidebar's + /// trees, counts and keyword lists read, nor the rule dialog's count for rules that read no develop state: none + /// is worked out again. Rules testing Has Edits or Cropped (directly or through an Album rule) follow the edit. + #[test] + fn develop_edits_only_redo_what_reads_develop_state() { + let mut cat = Catalog::default(); + let mut c = super::Caches::default(); + for i in 0..3u64 { + cat.apply(photo(i + 1, "2026-09-30T11:00:00", if i == 0 { 5 } else { 1 })).unwrap(); + } + cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); + let now = "2026-09-30T12:00:00"; + let rating = + |v: u64| -> RuleSet { serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": v}]})).unwrap() }; + let cropped: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "cropped", "op": "is", "value": true}]})).unwrap(); + let develop = |cat: &mut Catalog, id: u64, f: &dyn Fn(&mut lightcraft_develop::DevelopSettings)| { + let mut s = (*cat.photo(PhotoId(id)).unwrap().develop).clone(); + f(&mut s); + let settings = std::sync::Arc::new(s); + let step = lightcraft_catalog::HistoryStep { label: "Edit".into(), settings: settings.clone() }; + let set = Op::SetDevelop { id: PhotoId(id), settings, label: "Edit".into(), edited: Some(now.into()) }; + cat.apply(Op::Batch { ops: vec![set, Op::PushHistory { id: PhotoId(id), step }] }).unwrap(); + }; + let selection = [PhotoId(2)]; + c.rules_view(&cat, &rating(3), None, None, now); + let (tree, values, people) = (c.keyword_tree(&cat), c.filter_values(&cat), c.people(&cat, &Filter::default())); + let (chips, ticks, problems) = (c.keyword_chips(&cat, &selection), c.keyword_ticks(&cat, &selection), c.smart_album_problems(&cat)); + let suggestions = c.suggestions(&cat, &[], "", 5); + for i in 0..20 { + develop(&mut cat, 2, &|s| s.light.exposure = i as f64 / 10.0); + c.rules_view(&cat, &rating(3), None, None, now); + assert!(std::sync::Arc::ptr_eq(&tree, &c.keyword_tree(&cat))); + assert!(std::sync::Arc::ptr_eq(&values, &c.filter_values(&cat))); + assert!(std::sync::Arc::ptr_eq(&people, &c.people(&cat, &Filter::default()))); + assert!(std::sync::Arc::ptr_eq(&chips, &c.keyword_chips(&cat, &selection))); + assert!(std::sync::Arc::ptr_eq(&ticks, &c.keyword_ticks(&cat, &selection))); + assert!(std::sync::Arc::ptr_eq(&problems, &c.smart_album_problems(&cat))); + assert!(std::sync::Arc::ptr_eq(&suggestions, &c.suggestions(&cat, &[], "", 5))); + } + assert_eq!((c.rules_view_scans, c.smart_problem_scans), (1, 1), "slider ticks don't work them out again"); + // a rating is no develop edit: what reads ratings follows it + cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); + assert_eq!(c.rules_view(&cat, &rating(3), None, None, now).count, 2); + // what reads develop state follows the edit + assert_eq!(c.rules_view(&cat, &cropped, None, None, now).count, 0); + cat.apply(smart(11, serde_json::json!({"rules": [{"field": "edited", "op": "is", "value": true}]}))).unwrap(); + assert_eq!(c.album_counts(&cat, now)[&AlbumId(11)], 1, "photo 2 has edits"); + develop(&mut cat, 3, &|s| s.crop.geometry.rect = lightcraft_geom::Rect::new(0.1, 0.1, 0.9, 0.9)); + assert_eq!(c.album_counts(&cat, now)[&AlbumId(11)], 2, "a smart album testing Has Edits counts the new edit"); + assert_eq!(c.rules_view(&cat, &cropped, None, None, now).count, 1, "a rule testing Cropped sees the crop"); + // and a rule that tests such an album through an Album rule + let via: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "album", "op": "is", "value": 11}]})).unwrap(); + assert_eq!(c.rules_view(&cat, &via, None, None, now).count, 2); + develop(&mut cat, 1, &|s| s.light.exposure = 1.0); + assert_eq!(c.rules_view(&cat, &via, None, None, now).count, 3); + assert_eq!(c.album_counts(&cat, now)[&AlbumId(11)], 3); + } + /// Smart-album counts: unchanged frames reuse them; metadata and rule changes and (for /// "in the last…" rules) the clock crossing into a new minute recompute them. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 63403650b24..27cda268593 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -133,7 +133,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": {"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(), "thumbsMade": app.renderer.thumbs_made, "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(), "gpuWindowDevice": lightcraft_engine::gpu::on_window_device(), "screenTextures": app.renderer.has_screen_textures(), "mainOnGpu": app.renderer.textures.get(&crate::render::Slot::Main).is_some_and(|t| t.native.is_some()), "loupeSteps": app.loupe_timing.to_json(), "previewCache": preview_cache_json(app)}, + "perf": {"viewFollowed": app.session.view_followed, "viewWorkedOut": app.session.view_worked_out, "viewKept": app.session.view_kept, "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(), "thumbsMade": app.renderer.thumbs_made, "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(), "gpuWindowDevice": lightcraft_engine::gpu::on_window_device(), "screenTextures": app.renderer.has_screen_textures(), "mainOnGpu": app.renderer.textures.get(&crate::render::Slot::Main).is_some_and(|t| t.native.is_some()), "loupeSteps": app.loupe_timing.to_json(), "previewCache": preview_cache_json(app)}, "loupe": app.loupe_shown.map(|(p, src)| json!({ "photo": p.0, "source": src, diff --git a/crates/ui-egui/src/dialogs/faces.rs b/crates/ui-egui/src/dialogs/faces.rs index 032e6f08275..bcbe4501912 100644 --- a/crates/ui-egui/src/dialogs/faces.rs +++ b/crates/ui-egui/src/dialogs/faces.rs @@ -605,9 +605,12 @@ pub fn hints_for(app: &mut LightcraftApp, photo: u64) -> Option)>, folder_tree: Option<(u64, std::sync::Arc>)>, people: Option<(u64, lightcraft_catalog::Filter, std::sync::Arc>)>, - suggestions: Option<(u64, std::sync::Arc>)>, + /// (catalog revision, what was asked, the suggestions). + suggestions: Option<(u64, u64, std::sync::Arc>)>, /// What the Add keyword box offers for the text typed in it, by library revision, the /// selection's keywords and that text. - completions: Option<(u64, std::sync::Arc)>, + completions: Option<(u64, u64, std::sync::Arc)>, counts: Option<(u64, LibraryCounts)>, date_groups: Option<(u64, std::sync::Arc>)>, filter_values: Option<(u64, std::sync::Arc)>, @@ -632,7 +633,7 @@ pub struct Caches { /// photo or a few, don't). pub album_count_scans: usize, /// What the open smart-album rule dialog shows besides the rules ([`Caches::rules_view`]). - rules_view: Option<(u64, std::sync::Arc)>, + rules_view: Option<(u64, u64, std::sync::Arc)>, pub rules_view_scans: usize, /// A count an open dialog shows ([`Caches::dialog_count`]), by what it counts. dialog_count: Option<(u64, usize)>, diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 556f809d274..50e64b79734 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -70,13 +70,19 @@ const MAX_FOLLOWED: usize = 4096; /// What the grid derives from the visible photos, kept across frames. Everything is keyed by the /// session's visible-list generation ([`lightcraft_engine::Session::visible_shared`]), which -/// changes whenever the list is recomputed (any catalog change: crops, orientation, dates, stacks; +/// changes whenever the list is recomputed (a change to what the view reads: dates, stacks, photos; /// or another source, filter or sort) — so an unchanged frame neither copies nor hashes the ids. +/// A develop edit keeps the list of a view that reads no develop state, but photo shapes (crop, +/// orientation) are develop state: the photos it touched have their shapes read again, and the +/// justified layout is made again only when one of them changed (`shapes`, [`GridCache::reshape`]). #[derive(Default)] pub struct GridCache { runs: Option<(RunsKey, Arc>)>, - /// Layout by (runs key, width, thumbnail size, square). - layout: Option<((RunsKey, u32, u32, bool), Arc)>, + /// Layout by (runs key, width, thumbnail size, square, `shapes`). + layout: Option<((RunsKey, u32, u32, bool, u64), Arc)>, + /// Moves on when a cell's shape in a kept list changed ([`GridCache::reshape`]): the justified layout is keyed + /// on it, so an exposure tick, which changes no shape, doesn't lay the grid out again. + shapes: u64, /// Stack index by generation. stacks: Option<(u64, Arc)>, /// How many of the photos are browsed (Local) ones, by generation. @@ -92,7 +98,7 @@ pub struct GridCache { /// most of a 100 ms frame for each batch an import added. struct ListRead { ids: Arc<[PhotoId]>, - /// The catalog revision it was read at. + /// The catalog revision it was read at (or its shapes were kept up with to: [`GridCache::reshape`]). revision: u64, /// The date and grouping of the groups (`None`: the list has no date runs, no group is read). dates: Option<(SortKey, GroupBy)>, @@ -102,13 +108,24 @@ struct ListRead { named: HashMap, /// Each photo's shape; `None` for the square grid, whose cells are all alike. shapes: Option>, + /// Each photo's position, made the first time a develop edit to the list's photos asks for it. + places: Option>, } impl ListRead { fn new(ids: Arc<[PhotoId]>, revision: u64, dates: Option<(SortKey, GroupBy)>, shaped: bool) -> ListRead { let n = ids.len(); let groups = Vec::with_capacity(if dates.is_some() { n } else { 0 }); - ListRead { ids, revision, dates, groups, names: Vec::new(), named: HashMap::new(), shapes: shaped.then(|| Vec::with_capacity(n)) } + ListRead { + ids, + revision, + dates, + groups, + names: Vec::new(), + named: HashMap::new(), + shapes: shaped.then(|| Vec::with_capacity(n)), + places: None, + } } /// Read photo `id` from the catalog and put it next. @@ -252,6 +269,51 @@ impl GridCache { } } + /// The cells' shapes of the list last shown kept up with the catalog, when the list itself was kept: an edit + /// to nothing the view reads (a slider tick, a crop, a rotation) leaves the list and its generation as they + /// were, but a crop or a rotation changes a cell's shape. The photos the edit touched are read again (all of + /// them when the catalog can't say which); returns [`GridCache::shapes`], what the justified layout is + /// keyed on, moved on only when one of the shapes read is not what it was. + fn reshape(&mut self, stats: &mut GridStats, cat: &Catalog) -> u64 { + let Some(read) = self.read.as_mut().filter(|r| r.revision != cat.revision) else { return self.shapes }; + if let Some(shapes) = read.shapes.as_mut() { + // (the list was kept, so only develop state changed: the groups read stay right) + let reread = |shape: &mut f32, cat: &Catalog, id: PhotoId| { + let now = shape_of(cat, id); + // (bit for bit: a shape that can't be told apart from what it was is no change) + let changed = now.to_bits() != shape.to_bits(); + *shape = now; + changed + }; + let mut moved = false; + let touched = cat.touched_since(read.revision).filter(|t| t.len() <= MAX_FOLLOWED); + match touched { + Some(touched) => { + let ids = &read.ids; + let places = read.places.get_or_insert_with(|| ids.iter().enumerate().map(|(i, id)| (*id, i)).collect()); + for id in touched { + // (a photo folded into a stack, or not in this view, has no cell) + if let Some(shape) = places.get(&id).and_then(|i| shapes.get_mut(*i)) { + moved |= reread(shape, cat, id); + stats.photos_read += 1; + } + } + } + None => { + for (shape, id) in shapes.iter_mut().zip(read.ids.iter()) { + moved |= reread(shape, cat, *id); + } + stats.photos_read += read.ids.len() as u64; + } + } + if moved { + self.shapes = self.shapes.wrapping_add(1); + } + } + read.revision = cat.revision; + self.shapes + } + fn local(&mut self, cat: &Catalog, ids: &[PhotoId], generation: u64) -> usize { match self.local { Some((g, n)) if g == generation => n, @@ -354,8 +416,9 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { let stats = &mut app.caches.grid_stats; let runs = app.caches.grid.runs(stats, &app.session.catalog, &ids, runs_key, square); // the layout only changes with the photos (and their shapes), the grouping, the width and - // the thumbnail size - let lay_key = (runs_key, avail_w.to_bits(), target.to_bits(), square); + // the thumbnail size; a develop edit (crop, rotation) can change a shape and leave the list + let shapes = app.caches.grid.reshape(stats, &app.session.catalog); + let lay_key = (runs_key, avail_w.to_bits(), target.to_bits(), square, shapes); let lay = match &app.caches.grid.layout { Some((k, l)) if *k == lay_key => l.clone(), _ => { diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 19a9265a580..b465886d8dd 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -34,6 +34,8 @@ pub(crate) use rows::{INDENT_STEP, MIN_INDENT_STEP}; use rows::{LIBFOLDER_REVEALED, Row, SCROLL_TO_ROW, set_tree_open}; pub(crate) use rows::{content_width, indent_step, step_for}; pub(crate) use sections::PlacedSection; +#[cfg(test)] +pub(crate) use sections::missing_counted_at; pub use sections::section_drag_feedback; #[cfg(test)] pub(crate) use sections::section_drop_before; diff --git a/crates/ui-egui/src/panels/left/sections.rs b/crates/ui-egui/src/panels/left/sections.rs index b7a3ad39021..b660f1fbd46 100644 --- a/crates/ui-egui/src/panels/left/sections.rs +++ b/crates/ui-egui/src/panels/left/sections.rs @@ -378,6 +378,27 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } +/// The Missing Photos count's check: how many it found, whether it runs, when it started and the catalog revision it +/// counted (moved on while nothing it reads changes). +#[derive(Clone, Default)] +struct MissingJob { + n: std::sync::Arc, + running: std::sync::Arc, + at: f64, + rev: u64, + /// A catalog change arrived while a count was running: its recount is pending work + /// already, held until the recount stores its result. + owed: bool, +} + +const MISSING_JOB: &str = "missing-count"; + +/// Tests: the catalog revision the Missing Photos count is right at. +#[cfg(test)] +pub(crate) fn missing_counted_at(ctx: &egui::Context) -> Option { + ctx.data(|d| d.get_temp::(egui::Id::unique(MISSING_JOB))).map(|j| j.rev) +} + /// How many library photos have no file (Local browse records are not checked; see /// `cmd::missing::checked_path`). Checking stats every file, which on a network share takes /// seconds, so it runs on a worker thread: the count shown is the last finished one, refreshed @@ -389,34 +410,32 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { /// A catalog change during a timed refresh is pending from the frame it is seen, although its /// recount starts only when the refresh ends. pub(super) fn missing_count(app: &mut LightcraftApp, ui: &mut egui::Ui) -> usize { - use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::AcqRel, Ordering::Relaxed}; - #[derive(Clone, Default)] - struct Job { - n: std::sync::Arc, - running: std::sync::Arc, - at: f64, - rev: u64, - /// A catalog change arrived while a count was running: its recount is pending work - /// already, held until the recount stores its result. - owed: bool, - } - let id = egui::Id::unique("missing-count"); + use std::sync::atomic::Ordering::{AcqRel, Relaxed}; + type Job = MissingJob; + let id = egui::Id::unique(MISSING_JOB); let now = ui.input(|i| i.time); let rev = app.session.catalog.revision; let mut job: Job = ui.data(|d| d.get_temp(id)).unwrap_or(Job { rev: u64::MAX, at: f64::MIN, ..Default::default() }); + // (which files the library expects is no develop state: a slider drag doesn't check them all again) + let still = crate::still_right(&app.session.catalog, job.rev, crate::READS_NO_DEVELOP); + if still && job.rev != rev { + // kept: what it was counted at moves on, so the change record it asks stays short (as for the other caches) + job.rev = rev; + ui.data_mut(|d| d.insert_temp(id, job.clone())); + } let running = job.running.load(Relaxed); - if running && job.rev != rev && !job.owed { + if running && !still && !job.owed { // the recount waits for the running count (a timed refresh, not waited for), but settling // must wait for it from now on super::local::fs_running_counter(ui.ctx()).fetch_add(1, AcqRel); job.owed = true; ui.data_mut(|d| d.insert_temp(id, job.clone())); } - let fresh = now - job.at < 5.0 && job.rev == rev; + let fresh = now - job.at < 5.0 && still; if !fresh && !running { // the same scope as the Missing Photos view: library photos only, never Local browse records let paths = lightcraft_engine::cmd::missing::candidates(&app.session.catalog); - let pending = (job.rev != rev).then(|| super::local::fs_running_counter(ui.ctx())); + let pending = (!still).then(|| super::local::fs_running_counter(ui.ctx())); if let Some(p) = &pending && !job.owed { diff --git a/crates/ui-egui/src/tests/grid.rs b/crates/ui-egui/src/tests/grid.rs index 7196b1543e4..5de38329755 100644 --- a/crates/ui-egui/src/tests/grid.rs +++ b/crates/ui-egui/src/tests/grid.rs @@ -132,6 +132,59 @@ fn grid_headers_selection_scrolling_stacks_and_shape_changes() { assert_cheap_frames(&mut h); } +/// A develop edit (a Quick Develop click, a slider tick) leaves the list in view as it is: the grid's date runs and +/// stack index aren't rebuilt, nor the layout while no cell's shape changes. A crop or rotation can change a photo's +/// shape: the justified grid lays out again then, and the rotation shows in its rows without the list changing. +#[test] +fn develop_edits_keep_the_grid_view() { + for view in [ViewMode::PhotoGrid, ViewMode::SquareGrid] { + let mut h = grid(view); + let (generation, _) = h.app.session.visible_shared(); + let before = h.app.caches.grid_stats.clone(); + let id = h.app.session.visible()[10]; + select(&mut h, id); + for v in [0.5, 1.0] { + let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"control": "light.exposure", "value": v}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + } + assert_eq!(h.app.session.visible_shared().0, generation, "{view:?}: the list was kept"); + let s = &h.app.caches.grid_stats; + assert_eq!((s.view_builds, s.stack_index_builds), (before.view_builds, before.stack_index_builds), "{view:?}"); + assert_eq!(s.layout_builds, before.layout_builds, "{view:?}: an exposure changes no cell's shape"); + if view == ViewMode::PhotoGrid { + let landscape = h.app.session.visible()[12]; + let r = h.request("engine.execute", json!({"command": "photo.rotateRight", "params": {"ids": [landscape.0]}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(h.app.session.visible_shared().0, generation, "a rotation is develop state too"); + let cell = widget(&h, &format!("thumb:{}", landscape.0)).unwrap(); + assert!(cell.height() > cell.width(), "the rotated photo's cell is portrait: {cell:?}"); + assert_as_made_afresh(&mut h, "after a rotation in a kept list"); + assert!(h.app.caches.grid_stats.layout_builds > before.layout_builds, "the rotation lays the grid out again"); + } + assert_cheap_frames(&mut h); + } +} + +/// The sidebar's Missing Photos count is kept through develop edits (which files the library expects is no develop +/// state), and what it was counted at moves on with them, as for the other caches: the change record it asks next +/// stays short. +#[test] +fn develop_edits_move_the_missing_count_on() { + let mut h = grid(ViewMode::PhotoGrid); + h.app.ui.left_panel = true; + h.settle(SETTLE); + let id = h.app.session.visible()[10]; + select(&mut h, id); + for v in [0.5, 1.0, 1.5] { + let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"control": "light.exposure", "value": v}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(crate::panels::left::missing_counted_at(&h.view.ctx), Some(h.app.session.catalog.revision), "after exposure {v}"); + } +} + /// Selected photos whose thumbnails have not loaded (or can't) are still marked selected in the /// justified grid (issue #298), in a light theme too (a white ring vanished on the light grid): /// the ring of the active photo is heavier than the others' and both are the theme's colours, not diff --git a/docs/whats-new.md b/docs/whats-new.md index f3339263784..bb8495d7432 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,19 @@ ## Unreleased +### Slider drags stay smooth in a large library +- A slider tick (or any develop edit) no longer reworks views that don't look at develop settings: the grid keeps + its list, its date headers and its stack badges, the source's count stays as it was, and the side panels keep their + keyword lists, the filter bar's cameras, lenses and keywords, People, the rule dialog's count and the Missing + Photos count. The Photo Grid lays its rows out again only when a crop or a rotation changes a photo's shape, not on + every tick. In a library of 67,000 photos the frame after a tick went from about 7.5 ms to about 2.5 ms in the + Photo Grid (Square Grid: 7 ms to 2 ms), and from about 30 ms to about 12 ms with both side panels open and a Has + Edits smart album in the sidebar (an idle frame takes about 1 ms with the grid alone there, and about 10 ms with + both panels). +- Views that do look at develop settings still follow each tick: Edited / Unedited and the `edited:` search, the + Edit Date sort, smart albums testing Has Edits, Edit Date, Cropped, Treatment or a photo's size and shape (and + albums that test those), and the Photo Grid's rows, which follow a crop or a rotation. + ### Flatpak updates - Help ▸ Check for Updates can now reach the release service and update standalone Flatpak bundles. This permissions repair must first arrive through your existing host-side update method. Flatpaks