diff --git a/crates/catalog/proptest-regressions/tests_order.txt b/crates/catalog/proptest-regressions/tests_order.txt new file mode 100644 index 00000000000..bfaa8048775 --- /dev/null +++ b/crates/catalog/proptest-regressions/tests_order.txt @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc b51fced1f608fb7769423ce6f5303563c37beda7d2973d03e298b64b530cf6bc # shrinks to steps = [(2, 2, 1, 0)] diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 2c347473bcd..764170ef0e2 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -20,6 +20,8 @@ pub(crate) struct Indexes { stacks: OnceLock>>, /// Album → its photos (regular albums; a smart album's list is empty). albums: OnceLock>>, + /// Every photo in each sort order, see [`crate::order`]. + pub(crate) orders: crate::order::Orders, } /// A copy builds its own when asked (copies are made to be saved, not queried). diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 5a82d2a67d6..6d7dfc208d4 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -26,6 +26,7 @@ pub mod lock; #[cfg(not(target_arch = "wasm32"))] mod log_writer; pub mod model; +mod order; pub mod query; pub mod rules; pub mod safe_file; @@ -719,6 +720,23 @@ impl Catalog { ids.dedup(); Some(ids) } + + /// The photos whose `reads` (what a derived list reads of them) changed since the catalog was at `revision`, + /// added and removed photos included, each once, sorted by id. Ops that change no photo of their own (an + /// album, a stack, the keyword list) are not asked about. `None` when that is not known: too long ago, or the + /// catalog was set from outside (a library loaded). + pub(crate) fn photos_changed_since(&self, revision: u64, reads: Aspects) -> Option> { + // (every op that changes a photo says which, in `photo_mut` or as it adds or removes it: the ops + // `apply_inner` marks broad change no photo) + if !(self.changes.seen == self.revision && revision <= self.revision && revision >= self.changes.floor) { + return None; + } + let mut ids: Vec = self.changes.touched.iter().filter(|(r, _, a)| *r > revision && a.any_of(reads)).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)) } @@ -1218,6 +1236,7 @@ impl Catalog { /// wrote). pub fn repair(&mut self) -> Vec { let mut changed = Vec::new(); + self.index.orders.forget(); // Segmentation grids shared by the snapshot this was read from (issue #2154): each // reference takes its grid's data, and the table is not kept — a live catalog always // stores the data inline, so masks render and serialize without the snapshot's table. @@ -1543,6 +1562,8 @@ mod tests_lock; #[cfg(all(test, not(target_arch = "wasm32")))] mod tests_log_thread; #[cfg(test)] +mod tests_order; +#[cfg(test)] mod tests_repair; #[cfg(test)] mod tests_rule_order; diff --git a/crates/catalog/src/order.rs b/crates/catalog/src/order.rs new file mode 100644 index 00000000000..8d7d0650cac --- /dev/null +++ b/crates/catalog/src/order.rs @@ -0,0 +1,718 @@ +//! The whole library in each sort order, kept so that a view switch picks what matches out of an order that +//! is already there instead of sorting every photo again ([`Catalog::query_keeping`]). +//! +//! One list per sort key (ascending: a descending order is that one read backwards, as [`Sort::order`] +//! reverses a total order), built on first use and never saved. A photo is named by its place in the +//! catalog's id order, so a query marks what matches in one pass over the photos (which come in that order) +//! and reads the marks along the list, without looking a photo up by id. Each list remembers the revision it +//! was right for. When asked again, [`Catalog::photos_changed_since`] names the photos an op added, removed or +//! changed in what the key's comparison reads (`reads`: its own field, the file name that breaks ties, and +//! whether the photo is in the catalog), so a rating edit moves a photo only in the rating order. Up to +//! `IN_PLACE` such photos are moved in the list itself (a search for each, a shift of the part between); more, +//! or a photo that came or went, are taken out and put back in one pass over the list (photos that only came, all +//! after the others in id, are merged in: a search for each and one shift of the list). When that is not known +//! (too long ago, the catalog was loaded) the photos that came or went are found by comparing ids and the list is +//! sorted again from where it was ([`Catalog::remade`]: nearly in order, so about one pass), or dropped when the +//! query is of a small part of the library. A catalog copy starts without them, like the other [`crate::index`] +//! lookups. + +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, Weak}; + +use crate::query::{Filter, Sort, SortKey}; +use crate::{Aspects, Catalog, Photo, PhotoId}; + +/// A place that is no photo's. +const GONE: u32 = u32::MAX; + +/// Every photo in one sort key's ascending order. +#[derive(Clone, Debug)] +pub(crate) struct Order { + /// The photos' ids, in id order: the place of a photo in `sorted` is its place here. + ids: Vec, + /// Places in `ids`, in sort order. + sorted: Vec, +} + +impl Order { + /// `photos` (in id order) sorted by `sort`. + fn of<'a>(photos: impl Iterator, sort: &Sort) -> Order { + let photos: Vec<&Photo> = photos.collect(); + let mut sorted: Vec = (0..u32::try_from(photos.len()).unwrap_or(u32::MAX)).collect(); + // (the order is total: no two photos tie, so the sort need not keep equal ones as they were) + sorted.sort_unstable_by(|a, b| match (photos.get(*a as usize), photos.get(*b as usize)) { + (Some(a), Some(b)) => sort.order(a, b), + _ => a.cmp(b), + }); + Order { ids: photos.iter().map(|p| p.id).collect(), sorted } + } +} + +/// An order and the revision of the catalog it is right for (outside the order, so that nothing having +/// changed moves it on without copying the lists). +#[derive(Debug)] +struct Kept { + revision: u64, + order: Arc, +} + +#[derive(Debug, Default)] +struct Held { + kept: HashMap, + /// The keys a query of a middling share of the library had to sort for itself, for want of an order (see + /// [`Catalog::order_for`]): asked again, they get one. + missed: HashSet, + /// The orders being made on another thread ([`Catalog::prebuild_order`]), by key. Each is filled by its worker + /// and read here (a view that needs one before it is there waits for it: [`Catalog::order_for`]): a catalog + /// that is dropped, or [`Orders::forget`]s, drops them, so a result never reaches another catalog (a library + /// that was switched to) or an order that was forgotten. + pending: HashMap>, +} + +impl Held { + /// Takes in the order that another thread made for `key`, once that thread is done (also when it made none): it is + /// kept like any other, and brought up to date for the catalog as it is when it is used. + fn adopt(&mut self, key: SortKey) { + let Some(made) = self.pending.get(&key).and_then(|slot| slot.take_finished()) else { return }; + self.pending.remove(&key); + if let Some(Built { revision, order }) = made { + self.kept.entry(key).or_insert(Kept { revision, order: Arc::new(order) }); + } + } +} + +/// An order made on a thread of its own, from the photos as they were at `revision`. +#[derive(Debug)] +struct Built { + revision: u64, + order: Order, +} + +/// Where the thread making an order leaves it, and where a view that needs it waits. +#[derive(Debug, Default)] +struct Slot { + made: Mutex, + /// Told when the thread is done. + done: Condvar, + /// Tests: how many views went to wait for it. + #[cfg(test)] + waiting: AtomicUsize, +} + +#[derive(Debug, Default)] +struct Made { + /// The order, until it is taken in ([`Held::adopt`]). + order: Option, + /// The thread is done: with an order, or without one (it ended without making one: it panicked). + finished: bool, +} + +impl Slot { + /// Says the thread is done, with the order it made if it made one. + fn finish(&self, order: Option) { + if let Ok(mut made) = self.made.lock() { + if order.is_some() { + made.order = order; + } + made.finished = true; + } + self.done.notify_all(); + } + + /// Whether the thread is done (a slot that can't be read has nothing coming). + fn finished(&self) -> bool { + match self.made.lock() { + Ok(made) => made.finished, + Err(_) => true, + } + } + + /// What the thread made, once it is done: `None` while it is at work, then `Some` of the order (taken out, so + /// once) or of nothing. + fn take_finished(&self) -> Option> { + let Ok(mut made) = self.made.lock() else { return Some(None) }; + if made.finished { Some(made.order.take()) } else { None } + } + + /// Blocks until the thread is done. + fn wait(&self) { + let Ok(mut made) = self.made.lock() else { return }; + #[cfg(test)] + self.waiting.fetch_add(1, Ordering::SeqCst); + while !made.finished { + let Ok(next) = self.done.wait(made) else { return }; + made = next; + } + } +} + +/// What the thread making an order hands it over with. One that is dropped without having done that (the thread +/// panicked) still says the thread is done, so that nobody waits for an order that is not coming. +struct Maker(Weak); + +impl Maker { + /// Hands `built` over: to nobody, once the catalog is gone. + fn hand_over(self, built: Built) { + self.finish(Some(built)); + } + + fn finish(&self, built: Option) { + if let Some(slot) = self.0.upgrade() { + slot.finish(built); + } + } +} + +impl Drop for Maker { + fn drop(&mut self) { + // (after `hand_over` the thread is done already: this changes nothing) + self.finish(None); + } +} + +/// The work that sorts `photos` (as they were at `revision`) by `sort` and hands the order over, and the slot it is +/// handed over in. +fn making(photos: Vec>, sort: Sort, revision: u64) -> (Arc, impl FnOnce() + Send + 'static) { + let slot = Arc::new(Slot::default()); + let maker = Maker(Arc::downgrade(&slot)); + let work = move || { + let order = Order::of(photos.iter().map(|p| p.as_ref()), &sort); + maker.hand_over(Built { revision, order }); + }; + (slot, work) +} + +/// Below this many photos an order is sorted when first asked for (about 50 ms at most): a thread is not worth it. +const PREBUILD_FROM: usize = 50_000; + +/// The orders of a catalog: what is kept and being made, how many times every photo was sorted, whether the +/// platform has no threads at all (wasm32 in the browser), which is not asked again, and two diagnostics: how many +/// times a kept order was made again from every photo to follow an edit, and how many times a query walked +/// every photo. +#[derive(Debug, Default)] +pub(crate) struct Orders(Mutex, AtomicUsize, AtomicBool, AtomicUsize, AtomicUsize); + +impl Orders { + /// Forget every order (the catalog was changed other than by ops). + pub(crate) fn forget(&mut self) { + if let Ok(h) = self.0.get_mut() { + *h = Held::default(); + } + } + + /// The order kept for `key`, to tell whether it is made again (`Arc::ptr_eq`). + #[cfg(test)] + pub(crate) fn held(&self, key: SortKey) -> Option> { + self.0.lock().ok()?.kept.get(&key).map(|k| k.order.clone()) + } + + /// Whether an order is being made for `key`. + #[cfg(test)] + pub(crate) fn pending(&self, key: SortKey) -> bool { + self.0.lock().is_ok_and(|h| h.pending.contains_key(&key)) + } + + /// How many views went to wait for the order being made for `key` (for a test). + #[cfg(test)] + pub(crate) fn waiting(&self, key: SortKey) -> usize { + let Ok(held) = self.0.lock() else { return 0 }; + held.pending.get(&key).map_or(0, |slot| slot.waiting.load(Ordering::SeqCst)) + } + + /// Waits until the order being made for `key` is there (for a test); panics after a minute. + #[cfg(test)] + pub(crate) fn wait_built(&self, key: SortKey) { + let by = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !self.ready(key) { + assert!(std::time::Instant::now() < by, "the order for {key:?} was not made in a minute"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + + /// Whether `key` has an order that is kept, or one that was made on another thread and is waiting to be used; also + /// when none is being made, or none is coming (its thread ended without one). + fn ready(&self, key: SortKey) -> bool { + let Ok(held) = self.0.lock() else { return false }; + held.kept.contains_key(&key) || held.pending.get(&key).is_none_or(|slot| slot.finished()) + } + + /// How many orders are kept. + #[cfg(test)] + pub(crate) fn count(&self) -> usize { + self.0.lock().map_or(0, |h| h.kept.len()) + } +} + +/// What a sort key's comparison reads of a photo, as the aspects of the ops that change it ([`Sort::order`]: the +/// key's own field, then the file name, then the id). The import date is set when a photo is added and by no +/// other op, and the file size only by `SetContent`, which says [`Aspects::ALL`]: those read nothing more. +fn reads(key: SortKey) -> Aspects { + let key_reads = match key { + SortKey::CaptureDate => Aspects::CAPTURED, + SortKey::EditDate => Aspects::DEVELOP, + SortKey::Rating => Aspects::RATING, + SortKey::ImportDate | SortKey::FileName | SortKey::FileSize | SortKey::Random => Aspects::NONE, + }; + // (the file name breaks every tie but a name sort's own; a photo that comes or goes is in every order) + key_reads.with(Aspects::FILE).with(Aspects::PRESENCE) +} + +/// Up to this many photos touched, an order is followed by moving each in the list; more are worked out together. +const IN_PLACE: usize = 16; + +/// `sort` made ascending: the one order that is kept for its key. +fn ascending(sort: &Sort) -> Sort { + Sort { ascending: true, ..*sort } +} + +/// The work of sorting `n` things, in comparisons. +fn sorting(n: usize) -> f64 { + let n = n as f64; + if n < 2.0 { 0.0 } else { n * n.log2() } +} + +impl Catalog { + /// The photos that are `wanted`, in `sort` order. From the kept order of the whole library when one is kept + /// or worth making ([`Catalog::order_for`]); else the matches are sorted alone. `None` for a shuffle (never + /// kept), a library of more than `u32::MAX` photos, or when the matches can't be paired with the photos. + pub(crate) fn pick_in_order(&self, sort: &Sort, wanted: impl Fn(&Photo) -> bool) -> Option> { + if sort.key == SortKey::Random || u32::try_from(self.len()).is_err() { + return None; + } + // (the photos come in id order, as `ids` of an order does) + self.index.orders.4.fetch_add(1, Ordering::Relaxed); + let marks: Vec = self.photos().map(|p| wanted(p)).collect(); + let matching = marks.iter().filter(|m| **m).count(); + let Some(order) = self.order_for(sort, marks.len(), matching) else { + let mut v: Vec<&Photo> = self.photos().zip(&marks).filter(|(_, m)| **m).map(|(p, _)| p.as_ref()).collect(); + v.sort_by(|a, b| sort.order(a, b)); + return Some(v.into_iter().map(|p| p.id).collect()); + }; + if marks.len() != order.ids.len() { + return None; + } + let pick = |at: &u32| { + let at = *at as usize; + if *marks.get(at)? { order.ids.get(at).copied() } else { None } + }; + Some(if sort.ascending { order.sorted.iter().filter_map(pick).collect() } else { order.sorted.iter().rev().filter_map(pick).collect() }) + } + + /// The order kept for `sort`'s key, brought up to date now; made when that pays: a query of `matching` of the + /// `n` photos is better sorted alone while an order is not kept, as sorting every photo costs `n·log n` to its + /// `m·log m`. Under 1/16 of that, never (a folder, a search); under 1/4, the second time the key is asked + /// (a view that comes back is worth it); beyond, at once. `None`: sort the matches alone. Where the order would + /// be made, one that another thread is making ([`Catalog::prebuild_order`]) is waited for instead: it is there + /// sooner than a second sort of every photo would be, which would also take processors from it. + fn order_for(&self, sort: &Sort, n: usize, matching: usize) -> Option> { + let sort = ascending(sort); + let share = sorting(matching) / sorting(n).max(1.0); + loop { + let mut held = self.index.orders.0.lock().ok()?; + // (an order made on another thread, once it is there, is as one that was kept: brought up to date below) + held.adopt(sort.key); + if let Some(kept) = held.kept.get_mut(&sort.key) { + // what changed is no longer known: a small query is not worth making the whole order again + if share < 1.0 / 16.0 && kept.revision != self.revision && self.photos_changed_since(kept.revision, reads(sort.key)).is_none() { + held.kept.remove(&sort.key); + return None; + } + self.catch_up(&sort, kept); + return Some(kept.order.clone()); + } + if share < 1.0 / 16.0 || (share < 0.25 && held.missed.insert(sort.key)) { + return None; + } + if let Some(slot) = held.pending.get(&sort.key).cloned() { + // (not holding the lock; what the thread made is taken in above, or if it made none the order is sorted here) + drop(held); + slot.wait(); + continue; + } + let order = Arc::new(self.sorted_afresh(&sort)); + held.kept.insert(sort.key, Kept { revision: self.revision, order: order.clone() }); + return Some(order); + } + } + + /// How many times every photo was sorted from scratch for this catalog's orders (a diagnostic: what a kept order + /// and [`Catalog::prebuild_order`] are there to avoid). + #[doc(hidden)] + pub fn full_sorts(&self) -> usize { + self.index.orders.1.load(Ordering::Relaxed) + } + + /// How many times a kept order was made again from every photo to follow edits (a diagnostic: what following by + /// the photos that came or moved is there to avoid). + #[doc(hidden)] + pub fn order_remakes(&self) -> usize { + self.index.orders.3.load(Ordering::Relaxed) + } + + /// How many times a query walked every photo of the catalog to tell which match (a diagnostic). + #[doc(hidden)] + pub fn library_scans(&self) -> usize { + self.index.orders.4.load(Ordering::Relaxed) + } + + /// Notes that every photo of the catalog is about to be walked ([`Catalog::library_scans`]). + pub(crate) fn note_scan(&self) { + self.index.orders.4.fetch_add(1, Ordering::Relaxed); + } + + /// Whether the order for `key` is there to be used: kept, or made on another thread and waiting (a diagnostic). + /// `true` too when none is being made. + #[doc(hidden)] + pub fn order_ready(&self, key: SortKey) -> bool { + self.index.orders.ready(key) + } + + /// Starts making the order for `sort`'s key on a thread of its own, when the library is big enough for the first + /// sort to be felt and no order is kept or being made: the sort that a frame would otherwise wait for (the + /// first big view in a sort after the library was opened) is then done by the time it is asked for. The thread + /// gets the photos as they are now (they are shared, not copied; an edit after this copies the photo it edits) + /// and its result is tagged with the revision they were at: asked for, it is brought up to date like any kept + /// order, so it is never wrong. A big view that asks for it before it is ready waits for it (that takes less than + /// a second sort of every photo would); a small one sorts its own photos as it did. Nothing + /// is started where a thread can't be (it only costs that sort); where the platform has none, the first try is the + /// last, so a view there does not collect every photo again after each edit. + pub fn prebuild_order(&self, sort: &Sort) { + self.prebuild_order_holding(sort, || ()); + } + + /// [`Self::prebuild_order`] with something the thread holds while it works: `hold` is called once, on the calling + /// thread, only when a thread is about to start (not when nothing is to be made), and what it returns is moved + /// into the thread and dropped after the order is handed over. The engine passes an activity row, so a sort that + /// takes seconds on a big library is listed for as long as it runs. + pub fn prebuild_order_holding(&self, sort: &Sort, hold: impl FnOnce() -> H) { + self.prebuild_order_on(sort, hold, |work| std::thread::Builder::new().name("kept-order".into()).spawn(work).map(drop)); + } + + /// [`Self::prebuild_order_holding`] with the way a thread is started given: `spawn` runs the work on a thread (a test + /// starts none). A thread that cannot start for want of resources is tried again at the next call; one that the + /// platform does not have ([`std::io::ErrorKind::Unsupported`]) never is. + pub(crate) fn prebuild_order_on( + &self, + sort: &Sort, + hold: impl FnOnce() -> H, + spawn: impl FnOnce(Box) -> std::io::Result<()>, + ) { + if sort.key == SortKey::Random + || self.len() < PREBUILD_FROM + || u32::try_from(self.len()).is_err() + || self.index.orders.2.load(Ordering::Relaxed) + { + return; + } + let Ok(mut held) = self.index.orders.0.lock() else { return }; + if held.kept.contains_key(&sort.key) || held.pending.contains_key(&sort.key) { + return; + } + let sort = ascending(sort); + let (slot, make) = making(self.photos().cloned().collect(), sort, self.revision); + let holding = hold(); + let work = move || { + let _holding = holding; + make(); + }; + // (a thread that can't start drops `work`, and with it what it holds) + match spawn(Box::new(work)) { + Ok(()) => { + held.pending.insert(sort.key, slot); + } + Err(e) if e.kind() == std::io::ErrorKind::Unsupported => self.index.orders.2.store(true, Ordering::Relaxed), + Err(_) => {} + } + } + + /// An order "being made" for `sort`'s key by the test's own hand, as [`Catalog::prebuild_order`] makes one: the work + /// that makes it and hands it over is returned, to be called when the test says (or dropped, for a thread that + /// ended without an order). + #[cfg(test)] + pub(crate) fn pend_order(&self, sort: &Sort) -> Box { + let sort = ascending(sort); + let (slot, work) = making(self.photos().cloned().collect(), sort, self.revision); + if let Ok(mut held) = self.index.orders.0.lock() { + held.pending.insert(sort.key, slot); + } + Box::new(work) + } + + /// Brings `kept` up to date: the ops since its revision changed nothing it reads (it stays as it is, not + /// copied), photos that only came after all the others (each goes in at its place, the part after it shifted + /// once), a few photos (each is moved in the list itself), or many or the photos in the catalog (it is worked + /// out again from the old one). + fn catch_up(&self, sort: &Sort, kept: &mut Kept) { + let Some(touched) = self.photos_changed_since(kept.revision, reads(sort.key)) else { + // (no op since, in a library just loaded: right as it is) + if kept.revision == self.revision && kept.order.ids.len() == self.len() { + return; + } + kept.order = Arc::new(self.remade(sort, &kept.order)); + kept.revision = self.revision; + return; + }; + if !(touched.is_empty() && kept.order.ids.len() == self.len()) { + let moved = + self.merge_new(sort, &mut kept.order, &touched) || (touched.len() <= IN_PLACE && self.move_in_place(sort, &mut kept.order, &touched)); + if !moved { + kept.order = Arc::new(self.rebuilt(sort, &kept.order, &touched)); + } + } + kept.revision = self.revision; + } + + /// Puts photos that came after every photo in `order` (an import: ids are given upward, `touched` is sorted by + /// id and each is there to be found) in their places in it, with no pass over the library: each is searched + /// for in the list, and the part after it shifted once. `false` when that does not apply (a photo came or went + /// among the others, an old photo was edited too: the list is of other photos), with `order` as it was. + fn merge_new(&self, sort: &Sort, order: &mut Arc, touched: &[PhotoId]) -> bool { + let Some(first) = touched.first() else { return false }; + let n = order.ids.len(); + if n.checked_add(touched.len()) != Some(self.len()) || order.ids.last().is_some_and(|last| last >= first) { + return false; + } + let (Ok(base), Ok(top)) = (u32::try_from(n), u32::try_from(self.len())) else { return false }; + let Some(mut new) = + touched.iter().zip(base..top).map(|(id, at)| self.photo(*id).map(|p| (at, p.as_ref()))).collect::>>() + else { + return false; + }; + new.sort_unstable_by(|a, b| sort.order(a.1, b.1)); + let Order { ids, sorted } = Arc::make_mut(order); + // where each goes among the photos there (they come in order, so the places never go back) + let points: Vec = { + let key = |at: u32| ids.get(at as usize).and_then(|id| self.photo(*id)); + new.iter().map(|(_, p)| sorted.partition_point(|other| key(*other).is_some_and(|o| sort.order(o, p).is_lt()))).collect() + }; + ids.extend_from_slice(touched); + sorted.resize(n + new.len(), 0); + // from the back, each shifts what is after its place to make room, the last first + let mut end = n; + for (j, ((at, _), point)) in new.iter().zip(&points).enumerate().rev() { + if *point > end { + *order = Arc::new(self.sorted_afresh(sort)); + return true; + } + sorted.copy_within(*point..end, point + j + 1); + if let Some(slot) = sorted.get_mut(point + j) { + *slot = *at; + } + end = *point; + } + true + } + + /// The order kept for `sort`'s key, brought up to date, when it can be had without making it from every photo + /// here: one that is kept, or was made on another thread, or (a library too small for a thread to be worth it) is + /// quickly made. `None` while a big library's is not made yet: the caller goes without it, and has it made + /// ([`Catalog::prebuild_order`]). + fn order_now(&self, sort: &Sort) -> Option> { + if u32::try_from(self.len()).is_err() { + return None; + } + let sort = ascending(sort); + let mut held = self.index.orders.0.lock().ok()?; + held.adopt(sort.key); + if let Some(kept) = held.kept.get_mut(&sort.key) { + self.catch_up(&sort, kept); + return Some(kept.order.clone()); + } + if self.len() >= PREBUILD_FROM { + return None; + } + let order = Arc::new(self.sorted_afresh(&sort)); + held.kept.insert(sort.key, Kept { revision: self.revision, order: order.clone() }); + Some(order) + } + + /// The newest import date of the photos in the library (taken from the end of the import-date order when + /// that can be had, else from every photo). + pub fn latest_import(&self) -> Option { + if let Some(order) = self.order_now(&Sort { key: SortKey::ImportDate, ascending: true, ..Sort::default() }) { + // (the photos deleted or only browsed are skipped: the last import is mostly there) + let mut newest = + order.sorted.iter().rev().filter_map(|at| order.ids.get(*at as usize)).filter_map(|id| self.photo(*id)).filter(|p| p.in_library()); + return newest.next().map(|p| p.imported.clone()); + } + self.index.orders.4.fetch_add(1, Ordering::Relaxed); + self.photos().filter(|p| p.in_library()).map(|p| p.imported.as_str()).max().map(str::to_owned) + } + + /// What Recently Added lists: the photos that match `filter` (its `imported_from` is how far back) or are in + /// `keep` and match `within` (a held view, as [`Catalog::query_keeping`]), newest import first and a batch in file + /// order whatever the sort. The photos imported since that day are the end of the import-date order, so with that + /// order kept only they are looked at, not every photo; without it (a big library's is still being made) every + /// photo is, as before. + pub fn query_recent(&self, filter: &Filter, keep: &HashSet, within: &Filter) -> Vec { + let prepared = filter.prepare(self); + let within_prepared = within.prepare_one(self); + let wanted = |p: &Photo| filter.matches_in(p, self, &prepared) || (keep.contains(&p.id) && within.matches_in(p, self, &within_prepared)); + let by_import_date = Sort { key: SortKey::ImportDate, ascending: true, ..Sort::default() }; + let from = filter.imported_from.as_deref().unwrap_or_default(); + let Some(order) = self.order_now(&by_import_date) else { + self.index.orders.4.fetch_add(1, Ordering::Relaxed); + let mut all: Vec<(&str, &str, PhotoId)> = + self.photos().filter(|p| wanted(p)).map(|p| (p.imported.as_str(), p.file_name.as_str(), p.id)).collect(); + all.sort_unstable_by(|a, b| b.0.cmp(a.0).then_with(|| crate::query::cmp_name(a.1, b.1)).then(a.2.cmp(&b.2))); + return all.into_iter().map(|(_, _, id)| id).collect(); + }; + let photo_at = |at: &u32| order.ids.get(*at as usize).and_then(|id| self.photo(*id)); + let start = order.sorted.partition_point(|at| photo_at(at).is_some_and(|p| p.imported.as_str() < from)); + // (held photos from before that day come first in the import order: older than all the others) + let mut ordered: Vec<&Photo> = + keep.iter().filter_map(|id| self.photo(*id)).map(|p| p.as_ref()).filter(|p| p.imported.as_str() < from && wanted(p)).collect(); + ordered.sort_unstable_by(|a, b| { + a.imported.cmp(&b.imported).then_with(|| crate::query::cmp_name(&a.file_name, &b.file_name)).then(a.id.cmp(&b.id)) + }); + ordered.extend(order.sorted.get(start..).unwrap_or_default().iter().filter_map(photo_at).map(|p| p.as_ref()).filter(|p| wanted(p))); + // the batches newest first, each in the order it is in + let mut ids = Vec::with_capacity(ordered.len()); + let mut end = ordered.len(); + while let Some(newest) = ordered.get(..end).and_then(<[&Photo]>::last).map(|p| p.imported.as_str()) { + let begin = ordered.get(..end).map_or(0, |upto| upto.partition_point(|p| p.imported.as_str() < newest)); + ids.extend(ordered.get(begin..end).unwrap_or_default().iter().map(|p| p.id)); + end = begin; + } + ids + } + + /// Moves the `touched` photos (few, sorted by id, each once) to where they sort now, in `order` itself: no + /// copy of it unless a query's result still shares it, a search for each in the list, and a shift of the part + /// of the list between. `false` when that does not apply (a photo came or went: the list is of other photos), + /// with `order` as it was or made afresh. + fn move_in_place(&self, sort: &Sort, order: &mut Arc, touched: &[PhotoId]) -> bool { + if order.ids.len() != self.len() { + return false; + } + let places: Option> = touched + .iter() + .map(|id| if self.photo(*id).is_some() { order.ids.binary_search(id).ok().and_then(|i| u32::try_from(i).ok()) } else { None }) + .collect(); + let Some(places) = places else { return false }; + let Order { ids, sorted } = Arc::make_mut(order); + // all out first: what is left is in order, so each goes back by a search + for at in &places { + let Some(from) = sorted.iter().position(|a| a == at) else { + *order = Arc::new(self.sorted_afresh(sort)); + return true; + }; + sorted.remove(from); + } + for at in places { + let key = |at: u32| ids.get(at as usize).and_then(|id| self.photo(*id)); + let Some(p) = key(at) else { continue }; + let to = sorted.partition_point(|other| key(*other).is_some_and(|o| sort.order(o, p).is_lt())); + sorted.insert(to, at); + } + if sorted.len() != ids.len() { + *order = Arc::new(self.sorted_afresh(sort)); + } + true + } + + /// `old` worked out again after the ops that touched the photos `touched` (sorted by id, each once), from + /// the list of `old` and one pass over the photos: those taken out and put back by their keys. + fn rebuilt(&self, sort: &Sort, old: &Order, touched: &[PhotoId]) -> Order { + self.index.orders.3.fetch_add(1, Ordering::Relaxed); + let photos: Vec<&Photo> = self.photos().map(|p| p.as_ref()).collect(); + let ids: Vec = photos.iter().map(|p| p.id).collect(); + // where each photo of the old list is now (the touched ones are taken out, to go back by their new keys) + let mut now = places_now(&old.ids, &ids); + for id in touched { + if let Ok(i) = old.ids.binary_search(id) + && let Some(n) = now.get_mut(i) + { + *n = GONE; + } + } + let kept: Vec = old.sorted.iter().filter_map(|at| now.get(*at as usize).copied().filter(|n| *n != GONE)).collect(); + let mut moved: Vec = touched.iter().filter_map(|id| ids.binary_search(id).ok()).filter_map(|i| u32::try_from(i).ok()).collect(); + let key = |at: u32| photos.get(at as usize).copied(); + moved.sort_unstable_by(|a, b| match (key(*a), key(*b)) { + (Some(a), Some(b)) => sort.order(a, b), + _ => a.cmp(b), + }); + // each goes in by a search, the ones before it already in place + let mut sorted = Vec::with_capacity(kept.len().saturating_add(moved.len())); + let mut from = 0; + for at in moved { + let Some(p) = key(at) else { continue }; + let tail = kept.get(from..).unwrap_or_default(); + let to = from + tail.partition_point(|other| key(*other).is_some_and(|o| sort.order(o, p).is_lt())); + sorted.extend_from_slice(kept.get(from..to).unwrap_or_default()); + sorted.push(at); + from = to; + } + sorted.extend_from_slice(kept.get(from..).unwrap_or_default()); + if sorted.len() == ids.len() { Order { ids, sorted } } else { self.sorted_afresh(sort) } + } + + /// `old` worked out again when what changed since is not known (too many ops ago, the catalog was loaded): the + /// photos that came or went are found by comparing the ids (both lists are in id order), and the rest is + /// sorted from where `old` had them. Sorting that is nearly in order takes one pass and a merge, where + /// sorting every photo from scratch takes `n·log n` comparisons, and a photo whose key changed is put right + /// as well (the sort does not rely on `old` being right). + fn remade(&self, sort: &Sort, old: &Order) -> Order { + self.index.orders.3.fetch_add(1, Ordering::Relaxed); + let photos: Vec<&Photo> = self.photos().map(|p| p.as_ref()).collect(); + let ids: Vec = photos.iter().map(|p| p.id).collect(); + let now = places_now(&old.ids, &ids); + let mut placed = vec![false; ids.len()]; + let mut sorted: Vec = Vec::with_capacity(ids.len()); + for at in &old.sorted { + if let Some(n) = now.get(*at as usize).copied().filter(|n| *n != GONE) { + if let Some(p) = placed.get_mut(n as usize) { + *p = true; + } + sorted.push(n); + } + } + // (the photos that came go after, in id order: runs for the sort to merge in) + sorted.extend((0..u32::try_from(ids.len()).unwrap_or(u32::MAX)).filter(|at| !placed.get(*at as usize).copied().unwrap_or(true))); + // (the order is total, so a stable sort gives the one order; it is the one that finds the runs already there) + sorted.sort_by(|a, b| match (photos.get(*a as usize), photos.get(*b as usize)) { + (Some(a), Some(b)) => sort.order(a, b), + _ => a.cmp(b), + }); + Order { ids, sorted } + } + + /// Every photo, sorted. + fn sorted_afresh(&self, sort: &Sort) -> Order { + self.index.orders.1.fetch_add(1, Ordering::Relaxed); + Order::of(self.photos().map(|p| p.as_ref()), sort) + } + + /// Every photo's id in `sort`, made afresh from every photo, never from a kept order: what a kept order + /// has to equal. + #[cfg(test)] + pub(crate) fn sorted_from_scratch(&self, sort: &Sort) -> Vec { + let order = self.sorted_afresh(&ascending(sort)); + let ids = order.sorted.iter().filter_map(|at| order.ids.get(*at as usize).copied()); + if sort.ascending { ids.collect() } else { ids.rev().collect() } + } + + /// The order `sort` keeps now, as the ids a query of everything gives (ascending), for a test to compare. + #[cfg(test)] + pub(crate) fn kept_ids(&self, sort: &Sort) -> Option> { + self.pick_in_order(sort, |_| true) + } +} + +/// Where each of the `old` ids (sorted) is in `new` (sorted), [`GONE`] for one that is not there. +fn places_now(old: &[PhotoId], new: &[PhotoId]) -> Vec { + let mut j = 0; + old.iter() + .map(|id| { + while new.get(j).is_some_and(|n| n < id) { + j += 1; + } + match new.get(j) { + Some(n) if n == id => u32::try_from(j).unwrap_or(GONE), + _ => GONE, + } + }) + .collect() +} diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index efa62ea6d86..60a4c958bf7 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -81,7 +81,7 @@ fn null_as_empty<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Ok(Option::>::deserialize(d)?.unwrap_or_default()) } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum SortKey { #[default] @@ -533,11 +533,12 @@ impl Catalog { let prepared = filter.prepare(self); // `within` only decides for the few kept photos: worked out per photo, not hashed let within_prepared = within.prepare_one(self); - let mut v: Vec<&Photo> = self - .photos() - .map(|p| p.as_ref()) - .filter(|p| filter.matches_in(p, self, &prepared) || (keep.contains(&p.id) && within.matches_in(p, self, &within_prepared))) - .collect(); + let wanted = |p: &Photo| filter.matches_in(p, self, &prepared) || (keep.contains(&p.id) && within.matches_in(p, self, &within_prepared)); + // the whole library is kept in order ([`crate::order`]): what matches is picked out of it, not sorted + if let Some(ids) = self.pick_in_order(sort, wanted) { + return ids; + } + let mut v: Vec<&Photo> = self.photos().map(|p| p.as_ref()).filter(|p| wanted(p)).collect(); v.sort_by(|a, b| sort.order(a, b)); v.into_iter().map(|p| p.id).collect() } @@ -548,23 +549,54 @@ impl Catalog { /// 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(); + // (photos that came after every photo in the list were never in it: an import's, whose ids go upward. Then + // none of the others is looked for, and the list is not told apart from the touched photos id by id) + let all_new = touched.first().is_some_and(|first| was.iter().all(|id| id < first)); + let mut listed: std::collections::HashSet = std::collections::HashSet::new(); + let mut ids: Vec = if all_new { + was.to_vec() + } else { + let mut rest = Vec::with_capacity(was.len()); + for id in was { + if touched.binary_search(id).is_ok() { + listed.insert(*id); + } else { + rest.push(*id); + } + } + rest + }; let (prepared, within_prepared) = (filter.prepare_one(self), within.map(|w| w.prepare_one(self))); + let mut put: Vec<&Photo> = Vec::new(); for id in touched { let Some(p) = self.photo(*id) else { continue }; let kept = within.zip(within_prepared.as_ref()).is_some_and(|(w, wp)| listed.contains(id) && w.matches_in(p, self, wp)); if filter.matches_in(p, self, &prepared) || kept { - // (the list is in order without the touched photos, and stays so as each is put back) - let at = ids.partition_point(|other| self.photo(*other).is_some_and(|o| sort.order(o, p).is_lt())); - ids.insert(at, *id); + put.push(p.as_ref()); + } + } + // (the list is in order without the touched photos: each goes in at its place, the last first, with the part + // after it shifted once for all of them, not once for each) + put.sort_unstable_by(|a, b| sort.order(a, b)); + let points: Vec = + put.iter().map(|p| ids.partition_point(|other| self.photo(*other).is_some_and(|o| sort.order(o, p).is_lt()))).collect(); + let n = ids.len(); + ids.resize(n + put.len(), PhotoId(0)); + let mut end = n; + for (j, (p, point)) in put.iter().zip(&points).enumerate().rev() { + let at = (*point).min(end); + ids.copy_within(at..end, at + j + 1); + if let Some(slot) = ids.get_mut(at + j) { + *slot = p.id; } + end = at; } ids } /// How many photos match `filter`: [`Catalog::query`]'s length without its sorting. pub fn count(&self, filter: &Filter) -> usize { + self.note_scan(); let prepared = filter.prepare(self); self.photos().filter(|p| filter.matches_in(p, self, &prepared)).count() } diff --git a/crates/catalog/src/stacks.rs b/crates/catalog/src/stacks.rs index 84e89d1247b..fdc304fc377 100644 --- a/crates/catalog/src/stacks.rs +++ b/crates/catalog/src/stacks.rs @@ -8,10 +8,35 @@ //! collapsed stacks reduced to one photo). use std::collections::{HashMap, HashSet}; +use std::hash::{BuildHasherDefault, Hasher}; use crate::query::cmp_name; use crate::{Catalog, CatalogError, Op, PhotoId, Result, Stack, StackId}; +/// A hasher for photo ids: one mix of the number (SipHash costs several times that, and a view of a million photos is +/// asked about photo by photo). The mix keeps ids that share their low bits apart. Not for keys another party chooses. +#[derive(Default)] +struct IdHasher(u64); + +impl Hasher for IdHasher { + fn finish(&self) -> u64 { + self.0 + } + + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3); + } + } + + fn write_u64(&mut self, n: u64) { + self.0 = crate::query::mix64(n); + } +} + +type IdMap = HashMap>; +type IdSet = HashSet>; + impl Catalog { pub fn stack(&self, id: StackId) -> Option<&Stack> { self.stacks.get(&id) @@ -175,14 +200,15 @@ impl Catalog { if self.stacks.is_empty() { return ids.to_vec(); } - let index = self.stack_index(); - let present: HashSet = ids.iter().copied().collect(); + // (every photo of the view is asked about, in a view of a million: a cheap hash, and only a stack's members kept) + let index: IdMap = self.stacks.iter().flat_map(|(id, s)| s.photos.iter().map(move |p| (*p, *id))).collect(); + let present: IdSet = ids.iter().copied().filter(|id| index.contains_key(id)).collect(); let mut done: HashSet = HashSet::new(); let mut out = Vec::with_capacity(ids.len()); for id in ids { match index.get(id) { None => out.push(*id), - Some((sid, _)) => { + Some(sid) => { if !done.insert(*sid) { continue; } diff --git a/crates/catalog/src/tests_order.rs b/crates/catalog/src/tests_order.rs new file mode 100644 index 00000000000..0097f527233 --- /dev/null +++ b/crates/catalog/src/tests_order.rs @@ -0,0 +1,713 @@ +//! The kept sort orders ([`crate::order`]) equal a fresh full sort after every op that can move a photo in +//! one, its inverse, and a batch that fails and is rolled back, for every sort key both ways, so a query +//! that picks from them gives what sorting its matches gives. + +use proptest::prelude::*; + +use super::*; + +const PHOTOS: u64 = 9; + +const KEYS: [SortKey; 6] = [SortKey::CaptureDate, SortKey::ImportDate, SortKey::EditDate, SortKey::FileName, SortKey::Rating, SortKey::FileSize]; + +fn sorts() -> impl Iterator { + KEYS.into_iter().flat_map(|key| [true, false].map(|ascending| Sort { key, ascending, ..Sort::default() })) +} + +/// Many ties on every key, so the tie-breaks matter: few names (two only in another case), few dates. +fn photo(i: u64) -> Photo { + let names = ["IMG_1.jpg", "img_1.JPG", "IMG_2.jpg", "Été.jpg"]; + let mut p = + Photo::new(PhotoId(i), Source::Demo { scene: 1 }, names[(i % 4) as usize], "JPEG", 60, 40, &format!("2026-01-0{}T00:00:00", 1 + i % 3)); + p.captured = i.is_multiple_of(2).then(|| format!("2025-0{}-01T00:00:00", 1 + i % 2)); + p.rating = (i % 3) as u8; + p.file_size = i % 2; + p.edited = i.is_multiple_of(4).then(|| "2026-02-01T00:00:00".to_string()); + p +} + +fn library() -> Catalog { + library_of(PHOTOS) +} + +fn library_of(n: u64) -> Catalog { + let mut c = Catalog::new(); + for i in 1..=n { + c.apply(Op::AddPhoto { photo: Box::new(photo(i)) }).unwrap(); + } + c +} + +/// The kept order of each sort, against a fresh sort of every photo. +fn agree(c: &Catalog) -> std::result::Result<(), TestCaseError> { + for sort in sorts() { + prop_assert_eq!(c.kept_ids(&sort), Some(c.sorted_from_scratch(&sort)), "{:?}", sort); + } + Ok(()) +} + +fn op(kind: u8, n: u64, v: u8) -> Op { + let id = PhotoId(n % (PHOTOS + 2) + 1); + match kind % 12 { + 0 => Op::AddPhoto { photo: Box::new(photo(n % (PHOTOS + 4) + 1 + u64::from(v))) }, + 1 => Op::RemovePhoto { id }, + 2 => Op::SetRating { id, rating: v % 6 }, + 3 => Op::SetCaptured { id, captured: (!v.is_multiple_of(3)).then(|| format!("2025-0{}-0{}T10:00:00", 1 + v % 3, 1 + v % 2)) }, + 4 => Op::SetFile { id, file_name: ["IMG_1.jpg", "zzz.jpg", "AAA.jpg"][(v % 3) as usize].into(), source: Source::Demo { scene: 1 } }, + 5 => Op::Relink { id, file_name: ["IMG_2.jpg", "b.jpg"][(v % 2) as usize].into(), source: Source::Demo { scene: 2 }, format: None }, + 6 => Op::SetContent { + id, + width: 1, + height: 1, + file_size: u64::from(v % 3), + content_hash: None, + preview_only: None, + preview_checked: String::new(), + }, + 7 => Op::SetDevelop { + id, + settings: Default::default(), + label: String::new(), + edited: v.is_multiple_of(2).then(|| format!("2026-02-0{}T00:00:00", 1 + v % 3)), + }, + 8 => Op::SetDeleted { id, deleted: v.is_multiple_of(2) }, + // an edit no order reads + 9 => Op::SetFlag { id, flag: Flag::Pick }, + // what is applied is taken back: the last op fails (no such photo) half the time + 10 => Op::Batch { + ops: vec![ + Op::SetRating { id, rating: v % 6 }, + Op::SetFile { id: PhotoId(n % PHOTOS + 1), file_name: "q.jpg".into(), source: Source::Demo { scene: 1 } }, + Op::SetCaptured { id, captured: Some(if v.is_multiple_of(2) { "not a date".into() } else { "2024-05-05T05:05:05".into() }) }, + ], + }, + _ => Op::SetAlbumPhotos { id: AlbumId(1), photos: vec![id] }, + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn kept_orders_equal_a_fresh_sort(steps in proptest::collection::vec((0u8..12, 0u64..16, 0u8..255, 0u8..3), 1..30)) { + let mut c = library(); + // built before the ops, so every op has to be followed + agree(&c)?; + let mut inverses = Vec::new(); + for (kind, n, v, asks) in steps { + if let Ok(inv) = c.apply(op(kind, n, v)) { + inverses.push(inv); + } + // (asked after some ops and not others, so several are followed at once) + if asks != 0 { + agree(&c)?; + } + } + agree(&c)?; + for inv in inverses.into_iter().rev() { + c.apply(inv).unwrap(); + agree(&c)?; + } + // a clone and a snapshot make their own + agree(&c.clone())?; + agree(&Catalog::from_snapshot(&c.to_snapshot()).unwrap())?; + } +} + +#[test] +fn a_query_in_every_order_equals_sorting_its_matches() { + let mut c = library(); + let filter = Filter { rating: 1, ..Filter::default() }; + for sort in sorts() { + c.kept_ids(&sort); + } + c.apply(Op::SetRating { id: PhotoId(3), rating: 4 }).unwrap(); + c.apply(Op::SetFile { id: PhotoId(5), file_name: "AAA.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap(); + for sort in sorts() { + let mut want: Vec<&Photo> = c.photos().map(|p| p.as_ref()).filter(|p| filter.matches(p, &c)).collect(); + want.sort_by(|a, b| sort.order(a, b)); + assert_eq!(c.query(&filter, &sort), want.iter().map(|p| p.id).collect::>(), "{sort:?}"); + } +} + +/// The changes remembered are limited: after more than that, the order is made again, and is still right. +#[test] +fn an_order_is_made_again_when_the_changes_are_no_longer_remembered() { + let mut c = library(); + let sort = Sort { key: SortKey::Rating, ascending: false, ..Sort::default() }; + c.kept_ids(&sort); + for i in 0..9000u64 { + c.apply(Op::SetRating { id: PhotoId(i % PHOTOS + 1), rating: (i % 6) as u8 }).unwrap(); + } + assert_eq!(c.kept_ids(&sort), Some(c.sorted_from_scratch(&sort))); +} + +/// A query of a small share of the library (a folder, a search) on a key with no kept order sorts its own matches: +/// sorting the whole library for it would cost far more than the query. +#[test] +fn a_narrow_query_does_not_build_an_order_for_the_whole_library() { + let mut c = Catalog::new(); + for i in 1..=400 { + let mut p = photo(i); + p.rating = if i % 100 == 0 { 5 } else { u8::from(i % 4 == 1) }; + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let sort = Sort { key: SortKey::FileName, ascending: false, ..Sort::default() }; + let sorted = |f: &Filter| { + let mut want: Vec<&Photo> = c.photos().map(|p| p.as_ref()).filter(|p| f.matches(p, &c)).collect(); + want.sort_by(|a, b| sort.order(a, b)); + want.iter().map(|p| p.id).collect::>() + }; + let few = Filter { rating: 5, rating_op: RatingOp::Exactly, ..Filter::default() }; + assert_eq!(c.query(&few, &sort), sorted(&few)); + assert_eq!(c.query(&few, &sort), sorted(&few)); + assert_eq!(c.index.orders.count(), 0, "no order for 4 of 400 photos, however often asked"); + // about a quarter: sorted alone the first time, an order is made when the key is asked again + let third = Filter { rating: 1, rating_op: RatingOp::Exactly, ..Filter::default() }; + assert_eq!(c.query(&third, &sort), sorted(&third)); + assert_eq!(c.index.orders.count(), 0); + assert_eq!(c.query(&third, &sort), sorted(&third)); + assert_eq!(c.index.orders.count(), 1); +} + +/// Each key follows only what its comparison reads: a single op of each kind, on every photo, with several +/// values, moves the photo in every order that reads what it changed (and leaves the others alone). +#[test] +fn every_kind_of_edit_alone_leaves_every_order_right() { + for kind in 0..12 { + for n in 0..PHOTOS + 2 { + for v in 0..6 { + let mut c = library(); + agree(&c).unwrap(); + if c.apply(op(kind, n, v)).is_ok() { + agree(&c).unwrap_or_else(|e| panic!("kind {kind} photo {n} value {v}: {e}")); + } + } + } + } +} + +/// More photos touched than are moved in the list one by one: they are put back together. +#[test] +fn many_edits_at_once_leave_every_order_right() { + let mut c = library_of(80); + agree(&c).unwrap(); + for i in 1..=40u64 { + c.apply(Op::SetRating { id: PhotoId(i * 2), rating: (i % 6) as u8 }).unwrap(); + c.apply(Op::SetCaptured { id: PhotoId(i), captured: Some(format!("2024-0{}-0{}T01:00:00", 1 + i % 9, 1 + i % 7)) }).unwrap(); + } + agree(&c).unwrap(); + c.apply(Op::RemovePhoto { id: PhotoId(7) }).unwrap(); + c.apply(Op::SetRating { id: PhotoId(9), rating: 5 }).unwrap(); + agree(&c).unwrap(); +} + +/// Once the changes are no longer remembered, a small query drops the kept order and sorts its own matches, where a +/// big one makes the order again. +#[test] +fn a_small_query_does_not_remake_an_order_after_forgotten_changes() { + let mut c = library_of(400); + for (i, r) in [(100, 5u8), (200, 5)] { + c.apply(Op::SetRating { id: PhotoId(i), rating: r }).unwrap(); + } + let sort = Sort { key: SortKey::Rating, ascending: false, ..Sort::default() }; + let few = Filter { rating: 5, rating_op: RatingOp::Exactly, ..Filter::default() }; + c.kept_ids(&sort); + assert_eq!(c.index.orders.count(), 1); + for i in 0..9000u64 { + c.apply(Op::SetRating { id: PhotoId(i % 400 + 1), rating: (i % 4) as u8 }).unwrap(); + } + for i in [100, 200] { + c.apply(Op::SetRating { id: PhotoId(i), rating: 5 }).unwrap(); + } + let mut want: Vec<&Photo> = c.photos().map(|p| p.as_ref()).filter(|p| few.matches(p, &c)).collect(); + want.sort_by(|a, b| sort.order(a, b)); + assert_eq!(c.query(&few, &sort), want.iter().map(|p| p.id).collect::>()); + assert_eq!(c.index.orders.count(), 0); +} + +/// A library just loaded remembers no changes (its revision was set from outside): with no op since, a kept order +/// is still right, so alternating a big view and a small one builds it once. +#[test] +fn a_loaded_library_builds_an_order_once() { + let mut loaded = Catalog::from_snapshot(&library_of(400).to_snapshot()).unwrap(); + // (a loaded library takes a revision of its own, which is not the one its changes are remembered at) + loaded.revision = 1_000_000; + let sort = Sort { key: SortKey::FileName, ascending: true, ..Sort::default() }; + // (a few photos: sorted alone, never a reason to drop the order) + let few = Filter { rating: 5, rating_op: RatingOp::Exactly, ..Filter::default() }; + let all = Filter::default(); + let first = loaded.query(&all, &sort); + let kept = loaded.index.orders.held(sort.key).unwrap(); + loaded.query(&few, &sort); + assert_eq!(loaded.query(&all, &sort), first); + let again = loaded.index.orders.held(sort.key).unwrap(); + assert!(Arc::ptr_eq(&kept, &again), "the order was made again"); +} + +/// How many times every photo was sorted from scratch for `$c`'s orders while `$body` ran. +macro_rules! fresh_sorts { + ($c:expr, $body:expr) => {{ + let before = $c.full_sorts(); + $body; + $c.full_sorts() - before + }}; +} + +/// Photos added (keys before, among and after the ones there, and tied with them) and removed, in one batch or many: +/// every order follows without sorting every photo again, and equals a fresh sort. +#[test] +fn photos_added_and_removed_leave_every_order_right_without_a_full_sort() { + let mut c = library_of(300); + agree(&c).unwrap(); + let new = |i: u64| { + let mut p = photo(i); + // before (2024), among (2025-0x) and after (2027) the dates there; names that tie with the others' + p.captured = match i % 3 { + 0 => Some("2024-12-31T00:00:00".into()), + 1 => Some("2025-01-01T00:00:00".into()), + _ => Some("2027-01-01T00:00:00".into()), + }; + p.imported = format!("2026-01-0{}T00:00:00", 1 + i % 5); + p.rating = (i % 6) as u8; + p.file_size = i % 5; + p + }; + let n = fresh_sorts!(c, { + c.apply(Op::Batch { ops: (301..=340).map(|i| Op::AddPhoto { photo: Box::new(new(i)) }).collect() }).unwrap(); + agree(&c).unwrap_or_else(|e| panic!("{e}")); + // several imports in a row, each followed by a query + for i in 341..=360 { + c.apply(Op::AddPhoto { photo: Box::new(new(i)) }).unwrap(); + if i % 7 == 0 { + agree(&c).unwrap_or_else(|e| panic!("{e}")); + } + } + // an import undone, and some photos removed + c.apply(Op::Batch { ops: (301..=340).map(|i| Op::RemovePhoto { id: PhotoId(i) }).collect() }).unwrap(); + c.apply(Op::Batch { ops: (1..=30).map(|i| Op::RemovePhoto { id: PhotoId(i * 3) }).collect() }).unwrap(); + agree(&c).unwrap_or_else(|e| panic!("{e}")); + }); + // (`agree` makes a fresh sort per sort to compare with: 12 each time, five times) + assert_eq!(n, 12 * 5, "only the sorts the test itself makes: {n}"); +} + +/// What changed is no longer remembered (more ops than the memory holds, between two queries): the photos that +/// came or went are found by their ids and the order is sorted again from where it was, not from every photo. +#[test] +fn an_order_follows_added_photos_when_the_changes_are_no_longer_remembered() { + let mut c = library_of(300); + agree(&c).unwrap(); + // (more edits than the memory holds, of the photos' ratings among others) + for i in 0..9000u64 { + c.apply(Op::SetRating { id: PhotoId(i % 300 + 1), rating: (i % 6) as u8 }).unwrap(); + } + c.apply(Op::Batch { ops: (301..=340).map(|i| Op::AddPhoto { photo: Box::new(photo(i)) }).collect() }).unwrap(); + c.apply(Op::Batch { ops: (1..=20).map(|i| Op::RemovePhoto { id: PhotoId(i * 5) }).collect() }).unwrap(); + for sort in sorts() { + let got; + let n = fresh_sorts!(c, got = c.kept_ids(&sort)); + assert_eq!(n, 0, "{sort:?} was sorted from every photo"); + assert_eq!(got, Some(c.sorted_from_scratch(&sort)), "{sort:?}"); + } +} + +/// An edit of a sort key still moves its photo: with the changes remembered, and with them forgotten (where the +/// photo is found by sorting, not by being named). +#[test] +fn an_edited_sort_key_is_still_sorted_again() { + let mut c = library_of(300); + agree(&c).unwrap(); + c.apply(Op::SetRating { id: PhotoId(4), rating: 5 }).unwrap(); + c.apply(Op::SetCaptured { id: PhotoId(9), captured: Some("2030-01-01T00:00:00".into()) }).unwrap(); + c.apply(Op::SetFile { id: PhotoId(12), file_name: "zzz.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap(); + agree(&c).unwrap(); + for i in 0..9000u64 { + c.apply(Op::SetRating { id: PhotoId(i % 300 + 1), rating: (i % 6) as u8 }).unwrap(); + } + c.apply(Op::SetRating { id: PhotoId(77), rating: 5 }).unwrap(); + c.apply(Op::SetCaptured { id: PhotoId(78), captured: Some("2000-01-01T00:00:00".into()) }).unwrap(); + c.apply(Op::SetFile { id: PhotoId(79), file_name: "AAA.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap(); + agree(&c).unwrap(); +} + +/// A library big enough for its first sort to be made on another thread. +fn big() -> Catalog { + let mut c = Catalog::new(); + c.apply(Op::Batch { ops: (1..=50_000).map(|i| Op::AddPhoto { photo: Box::new(photo(i)) }).collect() }).unwrap(); + c +} + +fn sort_of(key: SortKey) -> Sort { + Sort { key, ascending: false, ..Sort::default() } +} + +/// An order made on another thread equals a fresh sort, and the first query for it sorts nothing. +#[test] +fn an_order_made_on_another_thread_equals_a_fresh_sort() { + let c = big(); + for key in KEYS { + let sort = sort_of(key); + c.prebuild_order(&sort); + assert!(c.index.orders.pending(key), "{key:?}: not started"); + c.index.orders.wait_built(key); + let got; + assert_eq!(fresh_sorts!(c, got = c.kept_ids(&sort)), 0, "{key:?}: sorted every photo"); + assert_eq!(got, Some(c.sorted_from_scratch(&sort)), "{key:?}"); + assert!(!c.index.orders.pending(key)); + } +} + +/// What changed while it was being made (photos added and removed, keys edited, more ops than are remembered) is +/// brought in when it is used: the order is right for the catalog as it is then. +#[test] +fn an_order_made_for_an_older_revision_is_brought_up_to_date() { + for many in [false, true] { + let mut c = big(); + let sorts = [sort_of(SortKey::CaptureDate), sort_of(SortKey::Rating), sort_of(SortKey::FileName)]; + for s in &sorts { + c.prebuild_order(s); + } + c.apply(Op::Batch { ops: (50_001..=50_040).map(|i| Op::AddPhoto { photo: Box::new(photo(i)) }).collect() }).unwrap(); + c.apply(Op::Batch { ops: (1..=20).map(|i| Op::RemovePhoto { id: PhotoId(i * 7) }).collect() }).unwrap(); + c.apply(Op::SetRating { id: PhotoId(9), rating: 5 }).unwrap(); + c.apply(Op::SetCaptured { id: PhotoId(10), captured: Some("2031-01-01T00:00:00".into()) }).unwrap(); + c.apply(Op::SetFile { id: PhotoId(11), file_name: "AAA.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap(); + if many { + for i in 0..9000u64 { + c.apply(Op::SetRating { id: PhotoId(i % 300 + 200), rating: (i % 6) as u8 }).unwrap(); + } + } + for s in &sorts { + c.index.orders.wait_built(s.key); + let got; + assert_eq!(fresh_sorts!(c, got = c.kept_ids(s)), 0, "{s:?}: sorted every photo"); + assert_eq!(got, Some(c.sorted_from_scratch(s)), "{s:?} (many: {many})"); + } + } +} + +/// A result is for the catalog that asked, in the key it asked: a copy, another key, a library that was forgotten or +/// dropped, and a library too small for a thread get nothing of it. +#[test] +fn an_order_made_on_another_thread_reaches_only_the_catalog_and_key_it_was_made_for() { + let c = big(); + let sort = sort_of(SortKey::Rating); + c.prebuild_order(&sort); + c.prebuild_order(&sort); + assert_eq!(c.index.orders.count(), 0); + let copy = c.clone(); + assert!(!copy.index.orders.pending(SortKey::Rating), "a copy starts without"); + c.index.orders.wait_built(SortKey::Rating); + // another key sorts for itself + let other = sort_of(SortKey::FileSize); + let got; + assert_eq!(fresh_sorts!(c, got = c.kept_ids(&other)), 1); + assert_eq!(got, Some(c.sorted_from_scratch(&other))); + // forgotten before it was used + let mut c = c; + c.index.orders.forget(); + assert!(!c.index.orders.pending(SortKey::Rating)); + assert_eq!(fresh_sorts!(c, drop(c.kept_ids(&sort))), 1, "the result of a forgotten order was used"); + // dropped while being made + let gone = big(); + gone.prebuild_order(&sort); + drop(gone); + // too small, and a shuffle + let small = library_of(400); + small.prebuild_order(&sort); + c.prebuild_order(&Sort { key: SortKey::Random, ..Sort::default() }); + assert!(!small.index.orders.pending(SortKey::Rating)); + assert!(!c.index.orders.pending(SortKey::Random)); +} + +/// Waits until `until` is true (for a test); panics after a minute. +fn wait_until(what: &str, until: impl Fn() -> bool) { + let by = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !until() { + assert!(std::time::Instant::now() < by, "{what}"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +/// A view of every photo in `sort`, asked for on a thread of its own. +fn ask_for_all(c: &Arc, sort: Sort) -> std::thread::JoinHandle>> { + let c = c.clone(); + std::thread::spawn(move || c.kept_ids(&sort)) +} + +/// A big view asked for while the order it needs is being made on another thread waits for that order and uses it: it +/// does not sort every photo a second time beside the thread that is doing it (the first big view after a library is +/// opened, which stopped the window for seconds in a library of a million photos). The order is made by the test's own +/// hand, so that the view is certainly asked for while it is being made. +#[test] +fn a_big_view_asked_for_while_its_order_is_made_waits_for_it() { + let c = Arc::new(big()); + let sort = sort_of(SortKey::CaptureDate); + let make = c.pend_order(&sort); + let view = ask_for_all(&c, sort); + // (handed over once the view waits for it; or once it has sorted every photo itself, which is what must not happen) + wait_until("the view neither waited nor sorted", || c.index.orders.waiting(sort.key) > 0 || c.full_sorts() > 0); + make(); + wait_until("the view did not finish", || view.is_finished()); + let got = view.join().unwrap(); + assert_eq!(c.full_sorts(), 0, "the view sorted every photo beside the order being made"); + assert!(!c.index.orders.pending(sort.key), "the order is still pending"); + assert_eq!(c.index.orders.count(), 1); + assert_eq!(got, Some(c.sorted_from_scratch(&sort))); +} + +/// The same with the order made by a thread of its own, asked for at once: the thread is not done, or if it is, its +/// order is used; either way the view sorts nothing, and nothing is left pending. +#[test] +fn a_big_view_asked_for_at_once_uses_the_order_the_thread_is_making() { + let c = big(); + let sort = sort_of(SortKey::CaptureDate); + c.prebuild_order(&sort); + assert!(c.index.orders.pending(sort.key)); + let got; + assert_eq!(fresh_sorts!(c, got = c.kept_ids(&sort)), 0, "the view sorted every photo beside the thread making the order"); + assert_eq!(got, Some(c.sorted_from_scratch(&sort))); + assert!(!c.index.orders.pending(sort.key), "an order is still being held"); + assert_eq!(c.index.orders.count(), 1); +} + +/// A thread that ends without an order (it panicked) must not leave the view waiting for ever: the view sorts for +/// itself, whether the thread ended before it was asked or while it waited. +#[test] +fn a_big_view_does_not_wait_for_an_order_that_is_not_coming() { + let c = Arc::new(big()); + let before = sort_of(SortKey::Rating); + drop(c.pend_order(&before)); + let got; + assert_eq!(fresh_sorts!(c, got = c.kept_ids(&before)), 1, "the order of a thread that ended was waited for or used"); + assert_eq!(got, Some(c.sorted_from_scratch(&before))); + assert!(!c.index.orders.pending(before.key)); + + let sort = sort_of(SortKey::CaptureDate); + let make = c.pend_order(&sort); + let view = ask_for_all(&c, sort); + wait_until("the view did not wait for the order", || c.index.orders.waiting(sort.key) > 0); + let sorted = c.full_sorts(); + drop(make); + wait_until("the view did not finish", || view.is_finished()); + let got = view.join().unwrap(); + assert_eq!(c.full_sorts(), sorted + 1, "the view did not sort for itself"); + assert!(!c.index.orders.pending(sort.key)); + assert_eq!(got, Some(c.sorted_from_scratch(&sort))); +} + +/// A view of a few photos sorts them alone, as it did, while an order is being made: only a view that would make the +/// order itself waits for it. +#[test] +fn a_small_view_does_not_wait_for_an_order_being_made() { + let c = Arc::new(big()); + let sort = sort_of(SortKey::CaptureDate); + let make = c.pend_order(&sort); + let few = Filter { only: (1..=50).map(PhotoId).collect(), ..Filter::default() }; + let view = { + let (c, few) = (c.clone(), few.clone()); + std::thread::spawn(move || c.query(&few, &sort)) + }; + // (a view that waited is let go after ten seconds, to fail rather than hang) + let by = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !view.is_finished() && std::time::Instant::now() < by { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let waited = !view.is_finished(); + make(); + let got = view.join().unwrap(); + assert!(!waited, "a view of a few photos waited for the order being made"); + assert_eq!(c.full_sorts(), 0); + assert_eq!(got.len(), 50); +} + +/// What the order's thread holds (the engine's activity row) is made on the calling thread, only when a thread is +/// started, and is dropped by the thread once the order is ready: not before the sort, and not never. +#[test] +fn the_thread_making_an_order_holds_what_it_was_given_until_the_order_is_ready() { + use std::sync::mpsc::{Sender, channel}; + use std::thread::ThreadId; + /// Says on which thread it was made and on which it was dropped. + struct Row(ThreadId, Sender<(ThreadId, ThreadId)>); + impl Drop for Row { + fn drop(&mut self) { + let _ = self.1.send((self.0, std::thread::current().id())); + } + } + let (tx, rx) = channel(); + let row = || Row(std::thread::current().id(), tx.clone()); + + // nothing is started (too small, a shuffle, an order made or being made): nothing is held + library_of(400).prebuild_order_holding(&sort_of(SortKey::Rating), row); + let c = big(); + c.prebuild_order_holding(&Sort { key: SortKey::Random, ..Sort::default() }, row); + assert!(rx.try_recv().is_err(), "a row was made where no thread starts"); + + let sort = sort_of(SortKey::Rating); + c.prebuild_order_holding(&sort, row); + c.prebuild_order_holding(&sort, row); + let (made_on, dropped_on) = rx.recv_timeout(std::time::Duration::from_secs(60)).expect("the row is dropped when the order is made"); + assert_eq!(made_on, std::thread::current().id(), "made on the thread that asked"); + assert_ne!(dropped_on, made_on, "dropped by the thread making the order"); + assert!(c.order_ready(sort.key), "dropped before the order was handed over"); + assert!(rx.try_recv().is_err(), "a second row was made for an order already being made"); +} + +/// Starts no thread: says `error`, and counts how many times it was asked and how many rows were made for it. +fn ask_twice_over(c: &Catalog, sort: &Sort, error: std::io::ErrorKind) -> (usize, usize) { + use std::cell::Cell; + let (asked, rows) = (Cell::new(0), Cell::new(0)); + for _ in 0..3 { + c.prebuild_order_on( + sort, + || rows.set(rows.get() + 1), + |work| { + asked.set(asked.get() + 1); + drop(work); + Err(std::io::Error::from(error)) + }, + ); + } + (asked.get(), rows.get()) +} + +/// Where the platform has no threads (wasm32 in the browser), asking again does not collect the photos and make the +/// activity row again each time: a view in a big library asks after every edit. Nothing is pending, and a big view +/// sorts for itself, as it always did there. +#[test] +fn a_catalog_whose_platform_has_no_threads_stops_trying() { + let c = big(); + let sort = sort_of(SortKey::Rating); + assert_eq!(ask_twice_over(&c, &sort, std::io::ErrorKind::Unsupported), (1, 1), "asked again after the platform said it has no threads"); + assert!(!c.index.orders.pending(sort.key)); + let got; + assert_eq!(fresh_sorts!(c, got = c.kept_ids(&sort)), 1); + assert_eq!(got, Some(c.sorted_from_scratch(&sort))); +} + +/// A thread that could not start for want of resources is tried again: it may start next time. +#[test] +fn a_thread_that_could_not_start_for_want_of_resources_is_tried_again() { + let c = big(); + let sort = sort_of(SortKey::Rating); + assert_eq!(ask_twice_over(&c, &sort, std::io::ErrorKind::WouldBlock), (3, 3)); + assert!(!c.index.orders.pending(sort.key)); +} + +/// A photo as an import brings it: keys before, among and after the ones in `library_of`, tied with them. +fn incoming(i: u64) -> Photo { + let mut p = photo(i); + p.captured = match i % 3 { + 0 => Some("2024-12-31T00:00:00".into()), + 1 => Some("2025-01-01T00:00:00".into()), + _ => Some("2027-01-01T00:00:00".into()), + }; + p.imported = format!("2026-01-0{}T00:00:00", 1 + i % 5); + p.rating = (i % 6) as u8; + p.file_size = i % 5; + p +} + +/// Photos that come after every photo there (an import: ids are given upward) are put in each kept order where they +/// belong, without the order being made again from every photo: at a million photos that was the pass over every +/// one of them that each import batch cost a view that is not followed. +#[test] +fn imported_photos_are_merged_into_every_order_without_remaking_it() { + let mut c = library_of(300); + agree(&c).unwrap(); + let remakes = c.order_remakes(); + for batch in 0..6u64 { + let first = 301 + batch * 16; + c.apply(Op::Batch { ops: (first..first + 16).map(|i| Op::AddPhoto { photo: Box::new(incoming(i)) }).collect() }).unwrap(); + agree(&c).unwrap_or_else(|e| panic!("{e}")); + } + // one photo at a time, with ids that skip, asked after each + for i in 0..12u64 { + c.apply(Op::AddPhoto { photo: Box::new(incoming(500 + i * 3)) }).unwrap(); + agree(&c).unwrap_or_else(|e| panic!("{e}")); + } + assert_eq!(c.order_remakes(), remakes, "an order was made again from every photo"); + // a photo that is not after the others (an undo that brings one back) is still put right, by the way it was + c.apply(Op::AddPhoto { photo: Box::new(incoming(350)) }).ok(); + c.apply(Op::AddPhoto { photo: Box::new(incoming(2)) }).ok(); + c.apply(Op::RemovePhoto { id: PhotoId(7) }).unwrap(); + c.apply(Op::AddPhoto { photo: Box::new(incoming(7)) }).unwrap(); + agree(&c).unwrap_or_else(|e| panic!("{e}")); +} + +/// What Recently Added lists, worked out from every photo: newest import first, a batch in file order. +fn recent_from_every_photo(c: &Catalog, filter: &Filter, keep: &std::collections::HashSet, within: &Filter) -> Vec { + let mut v: Vec<&Photo> = + c.photos().map(|p| p.as_ref()).filter(|p| filter.matches(p, c) || (keep.contains(&p.id) && within.matches(p, c))).collect(); + v.sort_by(|a, b| b.imported.cmp(&a.imported).then_with(|| crate::query::cmp_name(&a.file_name, &b.file_name)).then(a.id.cmp(&b.id))); + v.into_iter().map(|p| p.id).collect() +} + +/// Recently Added is read off the end of the import-date order: the photos imported since a day, in the order the +/// grid shows them, without a pass over the library; held photos from before that day join them. +#[test] +fn the_recently_added_are_the_end_of_the_import_order() { + let mut c = library_of(300); + for id in [4, 40, 41] { + c.apply(Op::SetDeleted { id: PhotoId(id), deleted: true }).unwrap(); + } + let since = Filter { imported_from: Some("2026-01-02".into()), ..Filter::default() }; + let rated = Filter { imported_from: Some("2026-01-02".into()), rating: 2, ..Filter::default() }; + let nothing = std::collections::HashSet::new(); + let held: std::collections::HashSet = (1..=9).map(PhotoId).collect(); + let everything = Filter::default(); + let check = |c: &Catalog| { + for (filter, keep, within) in + [(&since, ¬hing, &since), (&rated, ¬hing, &rated), (&since, &held, &everything), (&Filter::default(), ¬hing, &Filter::default())] + { + assert_eq!(c.query_recent(filter, keep, within), recent_from_every_photo(c, filter, keep, within), "{filter:?}, {} held", keep.len()); + } + let latest = c.photos().filter(|p| p.in_library()).map(|p| p.imported.clone()).max(); + assert_eq!(c.latest_import(), latest); + }; + // (the order is made by the first ask) + check(&c); + let (scans, sorts, remakes) = (c.library_scans(), c.full_sorts(), c.order_remakes()); + check(&c); + // an import, and an edit of a photo that it has no business with + c.apply(Op::Batch { ops: (301..=316).map(|i| Op::AddPhoto { photo: Box::new(incoming(i)) }).collect() }).unwrap(); + c.apply(Op::SetRating { id: PhotoId(5), rating: 5 }).unwrap(); + check(&c); + c.apply(Op::Batch { ops: (317..=332).map(|i| Op::AddPhoto { photo: Box::new(incoming(i)) }).collect() }).unwrap(); + check(&c); + assert_eq!((c.library_scans(), c.full_sorts(), c.order_remakes()), (scans, sorts, remakes), "a pass over every photo"); +} + +/// A list followed through an import's photos (many, tied with the others on every key, all after the old ones) and +/// through edits and removals, equals the list asked for again, for every sort both ways. +#[test] +fn a_list_followed_through_added_and_edited_photos_equals_the_query() { + let filters = [Filter::default(), Filter { rating: 2, ..Filter::default() }]; + for filter in &filters { + for sort in sorts() { + let mut c = library_of(300); + let mut list = c.query(filter, &sort); + let mut revision = c.revision; + let steps: Vec> = vec![ + (301..=360).map(|i| Op::AddPhoto { photo: Box::new(incoming(i)) }).collect(), + // old photos edited with new ones added, and some removed + (1..=30u64) + .map(|i| Op::SetRating { id: PhotoId(i * 7 % 300 + 1), rating: (i % 6) as u8 }) + .chain((361..=380).map(|i| Op::AddPhoto { photo: Box::new(incoming(i)) })) + .collect(), + (1..=20u64) + .map(|i| Op::RemovePhoto { id: PhotoId(i * 11) }) + .chain((381..=383).map(|i| Op::AddPhoto { photo: Box::new(incoming(i)) })) + .collect(), + ]; + for ops in steps { + c.apply(Op::Batch { ops }).unwrap(); + let touched = c.touched_since(revision).unwrap(); + list = c.follow(&list, &touched, filter, &sort, None); + revision = c.revision; + assert_eq!(list, c.query(filter, &sort), "{filter:?} {sort:?}"); + } + } + } +} diff --git a/crates/engine/examples/view_switch_bench.rs b/crates/engine/examples/view_switch_bench.rs new file mode 100644 index 00000000000..98ee900f2dc --- /dev/null +++ b/crates/engine/examples/view_switch_bench.rs @@ -0,0 +1,156 @@ +//! What switching the view costs in a big library, on a synthetic catalog (no files): a click on a sidebar source, +//! a sort or filter change, and the follow of an import batch while a view is shown. Times the engine calls the UI +//! thread makes (`library.source` and friends, `Session::visible`), not a frame. +//! +//! `cargo run --release -p lightcraft-engine --example view_switch_bench -- [photos] [runs]` +use std::time::{Duration, Instant}; + +use lightcraft_catalog::{Flag, Op, Photo, Source}; +use lightcraft_engine::Session; +use serde_json::{Value, json}; + +const FOLDERS: usize = 2_000; +const IMPORT_DAYS: usize = 400; + +fn photo(s: &mut Session, i: usize, imported: &str) -> Photo { + let id = s.catalog.alloc_photo_id(); + let name = format!("IMG_{:05}.jpg", (i * 7919) % 100_000); + let mut p = Photo::new(id, Source::File { path: format!("/pics/f{}/{name}", i % FOLDERS) }, &name, "JPEG", 60, 40, imported); + p.captured = Some(format!("{}-{:02}-{:02}T10:{:02}:{:02}", 2000 + i % 25, 1 + i % 12, 1 + i % 28, i % 60, (i / 60) % 60)); + p.rating = (i % 6) as u8; + p.file_size = (i as u64 * 31) % 5_000_000; + if i.is_multiple_of(40) { + p.flag = Flag::Pick; + } + p +} + +fn build(n: usize) -> Session { + let mut s = Session::new(); + let mut i = 0; + while i < n { + let chunk = (n - i).min(10_000); + let ops = (i..i + chunk) + .map(|k| { + let day = (k * IMPORT_DAYS) / n; + let imported = format!("2025-{:02}-{:02}T{:02}:00:00", 1 + (day / 28) % 12, 1 + day % 28, (k / 997) % 24); + Op::AddPhoto { photo: Box::new(photo(&mut s, k, &imported)) } + }) + .collect(); + s.catalog.apply(Op::Batch { ops }).expect("add"); + i += chunk; + } + s +} + +fn ms(d: Duration) -> f64 { + d.as_secs_f64() * 1000.0 +} + +fn median(v: &mut [f64]) -> f64 { + v.sort_by(|a, b| a.total_cmp(b)); + v[v.len() / 2] +} + +fn run(s: &mut Session, cmd: &str, p: Value) -> f64 { + let t = Instant::now(); + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")); + ms(t.elapsed()) +} + +fn main() { + let n: usize = std::env::args().nth(1).and_then(|a| a.parse().ok()).unwrap_or(500_000); + let runs: usize = std::env::args().nth(2).and_then(|a| a.parse().ok()).unwrap_or(3); + let t = Instant::now(); + let mut s = build(n); + println!("{n} photos built in {:.1} s", t.elapsed().as_secs_f64()); + let album = s.execute("album.create", &json!({"name": "Plain"})).expect("album")["id"].as_u64().expect("id"); + let ids: Vec = (0..n as u64 / 20).map(|k| k * 20 + 1).collect(); + s.execute("album.addPhotos", &json!({"id": album, "ids": ids})).expect("add to album"); + let rules = json!({"ruleSet": {"match": "all", "rules": [{"field": "rating", "op": "gte", "value": 4}]}}); + let smart = s.execute("album.createSmart", &json!({"name": "Good", "rules": rules})).expect("smart")["id"].as_u64().expect("id"); + let tiny = s.execute("album.create", &json!({"name": "Tiny"})).expect("album")["id"].as_u64().expect("id"); + // a few stacks, as a real library has (stacks make the view arrange its photos) + for k in 0..50u64 { + let at = k * (n as u64 / 60) + 2; + s.execute("library.select", &json!({"ids": [at, at + 1, at + 2]})).expect("select"); + s.execute("stack.group", &json!({})).expect("stack"); + } + + let cases: Vec<(&str, &str, Value)> = vec![ + ("All Photos", "library.source", json!({"kind": "all"})), + ("Recently Added", "library.source", json!({"kind": "recentlyAdded"})), + ("Picks", "library.source", json!({"kind": "picks"})), + ("Folder (1 of 2000)", "library.source", json!({"kind": "libraryFolder", "path": "/pics/f7"})), + ("Plain album", "library.source", json!({"kind": "album", "id": album})), + ("Smart album (rating>=4)", "library.source", json!({"kind": "album", "id": smart})), + ]; + println!("\nsource switch, ms (first = the first click of the session; then median of {runs} with the view left in between)"); + for (name, cmd, p) in &cases { + let mut v = Vec::new(); + let mut first = 0.0; + for r in 0..=runs { + run(&mut s, "library.source", json!({"kind": "album", "id": tiny})); + let d = run(&mut s, cmd, p.clone()); + if r == 0 { + first = d; + // the first ask of a session may start work in the background: give it time, as a user does + std::thread::sleep(Duration::from_secs(4)); + } else { + v.push(d); + } + } + println!("{name:<28} first {first:>9.1} median {:>9.1} worst {:>9.1}", median(&mut v.clone()), v.iter().cloned().fold(0.0, f64::max)); + } + + run(&mut s, "library.source", json!({"kind": "all"})); + println!("\nsort and filter changes on All Photos, ms"); + for key in ["fileName", "rating", "importDate", "captureDate"] { + let mut v = Vec::new(); + for _ in 0..=runs { + run(&mut s, "library.sort", json!({"key": "captureDate", "ascending": false})); + run(&mut s, "library.source", json!({"kind": "all"})); + let t = Instant::now(); + s.execute("library.sort", &json!({"key": key, "ascending": true})).expect("sort"); + s.visible(); + v.push(ms(t.elapsed())); + } + v.remove(0); + println!("sort by {key:<24} median {:>9.1} worst {:>9.1}", median(&mut v.clone()), v.iter().cloned().fold(0.0, f64::max)); + } + run(&mut s, "library.sort", json!({"key": "captureDate", "ascending": false})); + let mut v = Vec::new(); + for _ in 0..=runs { + run(&mut s, "library.filter", json!({"rating": 4})); + v.push(run(&mut s, "library.clearFilter", json!({}))); + } + v.remove(0); + println!("clear a filter median {:>9.1} worst {:>9.1}", median(&mut v.clone()), v.iter().cloned().fold(0.0, f64::max)); + + println!("\nfollowing an import batch of 16 photos while a view is shown, ms per batch (commit + visible)"); + for (name, cmd, p) in [cases[0].clone(), cases[1].clone(), cases[5].clone()] { + run(&mut s, cmd, p); + s.visible(); + let (mut v, mut k) = (Vec::new(), 0); + for b in 0..120 { + let ops = (0..16) + .map(|j| { + k += 1; + let imported = format!("2026-11-07T{:02}:{:02}:{:02}", (b / 60) % 24, b % 60, j); + Op::AddPhoto { photo: Box::new(photo(&mut s, n + k, &imported)) } + }) + .collect(); + let t = Instant::now(); + s.catalog.apply(Op::Batch { ops }).expect("batch"); + s.visible(); + v.push(ms(t.elapsed())); + } + let total: f64 = v.iter().sum(); + println!( + "{name:<28} median {:>9.2} worst {:>9.1} total for 120 batches {:>9.0}", + median(&mut v.clone()), + v.iter().cloned().fold(0.0, f64::max), + total + ); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 53077f95c62..9ea6c20d40d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1244,17 +1244,34 @@ impl Session { Some(_) => self.view_followed += 1, None => self.view_worked_out += 1, } + let recent = self.source == LibrarySource::RecentlyAdded; let mut visible = match (followed, &base, &within) { (Some(ids), _, _) => ids, + // newest import first, whatever the sort direction (the grid groups by import day); a batch stays in + // file order (name, then id). Read off the end of the import-date order, not sorted + (None, Some((_, _, held)), Some(within)) if recent => { + let keep: std::collections::HashSet = held.iter().copied().collect(); + self.catalog.query_recent(&f, &keep, within) + } + _ if recent => self.catalog.query_recent(&f, &std::collections::HashSet::new(), &f), (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), }; + // after the query: a big view has just made the order it needed itself (and this does nothing); a small one + // has not, and the first big view in this sort later is then not sorted in a frame the user waits for + self.catalog.prebuild_order_holding(&self.sort, || self.activity.start("sort", "Sorting the library", activity::Cancel::No)); + if recent { + // (Recently Added reads the import-date order, which the sort may not be) + let by_import_date = Sort { key: lightcraft_catalog::SortKey::ImportDate, ..self.sort }; + self.catalog.prebuild_order_holding(&by_import_date, || self.activity.start("sort", "Sorting the library", activity::Cancel::No)); + } // 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())); + // refreshed (taken before stacks are arranged, so a photo folded into a stack is held with it). Recently + // Added is not followed but is kept as well: its count is the length of the list, not another pass + self.base = (!whole || holds || recent).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 @@ -1279,20 +1296,6 @@ impl Session { 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)) - }); - } 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); diff --git a/crates/engine/src/tests/view_follow.rs b/crates/engine/src/tests/view_follow.rs index bc47d94c94b..3b37d25f214 100644 --- a/crates/engine/src/tests/view_follow.rs +++ b/crates/engine/src/tests/view_follow.rs @@ -433,3 +433,110 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo assert_eq!(shown(&tally), fresh(&s)); } } + +/// In a big library, showing a small view (Picks) makes the order of the current sort in the background, so that +/// All Photos, shown later, lists without sorting every photo on the thread that draws. +#[test] +fn a_small_view_makes_the_order_for_the_big_view_that_follows() { + let mut s = Session::new(); + let ops: Vec = (0..50_000usize) + .map(|i| { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new( + id, + Source::File { path: format!("/pics/{}/{i}.jpg", i % 3) }, + &format!("IMG_{i:05}.jpg"), + "JPEG", + 60, + 40, + "2026-01-01T10:00:00", + ); + p.captured = Some(format!("2025-{:02}-{:02}T10:00:{:02}", 1 + i % 12, 1 + i % 28, i % 60)); + Op::AddPhoto { photo: Box::new(p) } + }) + .collect(); + s.commit("Add", Op::Batch { ops }).unwrap(); + s.execute("library.sort", &json!({"key": "captureDate", "ascending": true})).unwrap(); + // (the id the next row gets tells whether a row was started meanwhile) + let before = s.activity.start("probe", "Probe", crate::activity::Cancel::No).id(); + s.execute("library.source", &json!({"kind": "picks"})).unwrap(); + assert!(s.visible().is_empty()); + let after = s.activity.start("probe", "Probe", crate::activity::Cancel::No); + assert_eq!(after.id(), before + 2, "making the order started no activity row (one that is listed while it runs)"); + drop(after); + let key = lightcraft_catalog::SortKey::CaptureDate; + let by = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !s.catalog.order_ready(key) || !s.activity.list().is_empty() { + assert!(std::time::Instant::now() < by, "the order was not made, or its row not removed, in a minute"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let before = s.catalog.full_sorts(); + s.execute("library.source", &json!({"kind": "all"})).unwrap(); + let all = s.visible().to_vec(); + assert_eq!(all.len(), 50_000); + assert_eq!(s.catalog.full_sorts(), before, "All Photos sorted every photo"); + let mut want: Vec<_> = s.catalog.photos().collect(); + want.sort_by(|a, b| s.sort.order(a, b)); + assert_eq!(all, want.iter().map(|p| p.id).collect::>()); +} + +/// A photo of a big library for the Recently Added tests: imported on day `day` (500 photos to a day), tied names. +fn imported_on(s: &mut Session, i: usize, day: usize) -> Op { + let id = s.catalog.alloc_photo_id(); + let name = format!("IMG_{:05}.jpg", (i * 7919) % 100_000); + let imported = format!("2026-{:02}-{:02}T10:00:00", 1 + day / 28, 1 + day % 28); + let mut p = Photo::new(id, Source::File { path: format!("/pics/{}/{name}", i % 7) }, &name, "JPEG", 60, 40, &imported); + p.captured = Some(format!("2025-{:02}-{:02}T10:00:{:02}", 1 + i % 12, 1 + i % 28, i % 60)); + Op::AddPhoto { photo: Box::new(p) } +} + +/// Recently Added from every photo, as the grid shows it: newest import first, a batch in file order. +fn recently_added_from_every_photo(s: &Session) -> Vec { + let from = crate::LibrarySource::RecentlyAdded.to_filter(&Default::default(), &s.catalog).imported_from.unwrap(); + let mut v: Vec<&Photo> = s.catalog.photos().map(|p| p.as_ref()).filter(|p| p.in_library() && p.imported.as_str() >= from.as_str()).collect(); + v.sort_by(|a, b| b.imported.cmp(&a.imported).then_with(|| lightcraft_catalog::query::cmp_name(&a.file_name, &b.file_name)).then(a.id.cmp(&b.id))); + v.into_iter().map(|p| p.id).collect() +} + +/// Recently Added in a big library is read off the end of the import-date order, when the order is kept: switching to it +/// and following the batches of an import that is going on look at the photos of the last 30 days only, never at every +/// photo (nor sort them). On a library of two million photos that was a second per click and per batch. +#[test] +fn recently_added_in_a_big_library_does_not_pass_over_every_photo() { + let mut s = Session::new(); + let ops: Vec = (0..50_000usize).map(|i| imported_on(&mut s, i, i / 500)).collect(); + s.commit("Add", Op::Batch { ops }).unwrap(); + s.execute("library.source", &json!({"kind": "picks"})).unwrap(); + // the first Recently Added asks for the import-date order to be made on another thread + s.execute("library.source", &json!({"kind": "recentlyAdded"})).unwrap(); + let by = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !s.catalog.order_ready(lightcraft_catalog::SortKey::ImportDate) || !s.activity.list().is_empty() { + assert!(std::time::Instant::now() < by, "the order was not made in a minute"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + s.execute("library.source", &json!({"kind": "picks"})).unwrap(); + let (scans, sorts, remakes) = (s.catalog.library_scans(), s.catalog.full_sorts(), s.catalog.order_remakes()); + s.execute("library.source", &json!({"kind": "recentlyAdded"})).unwrap(); + let shown = s.visible().to_vec(); + assert!(shown.len() > 10_000, "{} shown", shown.len()); + assert_eq!(shown, recently_added_from_every_photo(&s)); + assert_eq!(s.source_total(), Some(shown.len()), "its count"); + assert_eq!( + (s.catalog.library_scans(), s.catalog.full_sorts(), s.catalog.order_remakes()), + (scans, sorts, remakes), + "switching to it passed over every photo" + ); + // an import going on: batches of 16, one after the other, each followed by the view + for batch in 0..5usize { + let ops: Vec = (0..16).map(|j| imported_on(&mut s, 50_000 + batch * 16 + j, 100 + batch)).collect(); + s.commit("Import", Op::Batch { ops }).unwrap(); + let shown = s.visible().to_vec(); + assert_eq!(shown, recently_added_from_every_photo(&s), "after batch {batch}"); + assert_eq!(s.source_total(), Some(shown.len()), "its count after batch {batch}"); + } + assert_eq!( + (s.catalog.library_scans(), s.catalog.full_sorts(), s.catalog.order_remakes()), + (scans, sorts, remakes), + "following the import passed over every photo" + ); +} diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 73ec0352b2b..b021ec916b4 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -42,7 +42,7 @@ impl LibrarySource { LibrarySource::All => {} // everything imported in the 30 days up to the latest import (by import, newest first) LibrarySource::RecentlyAdded => { - let latest = cat.photos().filter(|p| p.in_library()).map(|p| p.imported.clone()).max().unwrap_or_default(); + let latest = cat.latest_import().unwrap_or_default(); let from = lightcraft_catalog::stacks::iso_seconds(&latest) .map(|s| lightcraft_catalog::dates::civil(s - RECENT_DAYS * 86_400)) .unwrap_or_else(|| latest.get(..10).unwrap_or("").to_string()); diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index ea102192177..1c5c0316faa 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2472,5 +2472,6 @@ "Welcome": "Vítejte", "Next": "Další", "Get Started": "Začít", - "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie" + "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie", + "Sorting the library": "Řazení knihovny" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index bc67606eb61..3ed023b9e41 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3507,5 +3507,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Starten Sie die App mit --control 7980 (oder LIGHTCRAFT_CONTROL_PORT), dann verbindet lightcraft-cli mcp --connect einen Agenten mit ihr.", "Welcome": "Willkommen", "Next": "Weiter", - "Get Started": "Loslegen" + "Get Started": "Loslegen", + "Sorting the library": "Bibliothek wird sortiert" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index c34057bdfe5..039f3824373 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2426,5 +2426,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicia la aplicación con --control 7980 (o LIGHTCRAFT_CONTROL_PORT), y lightcraft-cli mcp --connect conecta un agente a ella.", "Welcome": "Bienvenido", "Next": "Siguiente", - "Get Started": "Empezar" + "Get Started": "Empezar", + "Sorting the library": "Ordenando la biblioteca" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 59cc611cd61..a4b21fd8f32 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2383,5 +2383,6 @@ "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", "Bottom bar": "Alapalkki", - "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää" + "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", + "Sorting the library": "Lajitellaan kirjastoa" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 31e6814b6d5..ef8948f89b7 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3609,5 +3609,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Démarrez l'application avec --control 7980 (ou LIGHTCRAFT_CONTROL_PORT), puis lightcraft-cli mcp --connect y connecte un agent.", "Welcome": "Bienvenue", "Next": "Suivant", - "Get Started": "Commencer" + "Get Started": "Commencer", + "Sorting the library": "Tri de la bibliothèque" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 52705328cc7..82eda73f40d 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2397,5 +2397,6 @@ "Top bar": "Bilah atas", "Tool strip": "Bilah alat", "Bottom bar": "Bilah bawah", - "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto" + "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", + "Sorting the library": "Mengurutkan pustaka" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 5b0ccc0cee0..0ae661128fa 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2590,5 +2590,6 @@ "Welcome": "Benvenuto", "Next": "Avanti", "Get Started": "Inizia", - "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto" + "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto", + "Sorting the library": "Ordinamento della libreria" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 97c15dd0191..0758d312e7c 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2424,5 +2424,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "アプリを --control 7980 (または LIGHTCRAFT_CONTROL_PORT) で起動してから、lightcraft-cli mcp --connect でエージェントを接続できます。", "Welcome": "ようこそ", "Next": "次へ", - "Get Started": "始める" + "Get Started": "始める", + "Sorting the library": "ライブラリを並べ替え中" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 30769b60fa1..0f32f3c895f 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3692,5 +3692,6 @@ "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", - "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის" + "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", + "Sorting the library": "ბიბლიოთეკის დახარისხება" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index dbc29a19417..ed4d0413764 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2348,5 +2348,6 @@ "Welcome": "Witamy", "Next": "Dalej", "Get Started": "Zaczynamy", - "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć" + "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć", + "Sorting the library": "Sortowanie biblioteki" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 3aedd829064..407c11559fd 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2270,5 +2270,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicie o aplicativo com --control 7980 (ou LIGHTCRAFT_CONTROL_PORT) e o lightcraft-cli mcp --connect conecta um agente a ele.", "Welcome": "Bem-vindo", "Next": "Próximo", - "Get Started": "Começar" + "Get Started": "Começar", + "Sorting the library": "Ordenando a biblioteca" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index b3df02470e3..688fd5e1038 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2632,5 +2632,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустите приложение с --control 7980 (или LIGHTCRAFT_CONTROL_PORT), и команда lightcraft-cli mcp --connect подключит к нему одного агента.", "Welcome": "Добро пожаловать", "Next": "Далее", - "Get Started": "Начать" + "Get Started": "Начать", + "Sorting the library": "Сортировка библиотеки" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 94b9e303338..af28c88adab 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2486,5 +2486,6 @@ "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", "Bottom bar": "Nedre fältet", - "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton" + "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", + "Sorting the library": "Sorterar biblioteket" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 09b78fab1e3..d5ff12c89d6 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2422,5 +2422,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустіть програму з --control 7980 (або LIGHTCRAFT_CONTROL_PORT), і lightcraft-cli mcp --connect під'єднає до неї одного агента.", "Welcome": "Ласкаво просимо", "Next": "Далі", - "Get Started": "Почати" + "Get Started": "Почати", + "Sorting the library": "Сортування бібліотеки" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index af27e9aa0ab..f76778d8133 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2711,5 +2711,6 @@ "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", "Bottom bar": "Thanh dưới cùng", - "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác" + "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác", + "Sorting the library": "Đang sắp xếp thư viện" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ca13d782a5e..a3251c559bd 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2425,5 +2425,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 启动应用,lightcraft-cli mcp --connect 即可将一个智能体接入其中。", "Welcome": "欢迎", "Next": "下一步", - "Get Started": "开始使用" + "Get Started": "开始使用", + "Sorting the library": "正在排序图库" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index f3dfc422ec3..e5db37553f8 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2426,5 +2426,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 啟動應用程式,lightcraft-cli mcp --connect 即可將一個代理程式連接到其中。", "Welcome": "歡迎", "Next": "下一步", - "Get Started": "開始使用" + "Get Started": "開始使用", + "Sorting the library": "正在排序照片庫" } diff --git a/docs/whats-new.md b/docs/whats-new.md index ab0f90c0338..5c47e6e7ba9 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -38,6 +38,27 @@ process 5: new photos (and Reset) get it, photos you already edited keep their look until you choose Photo ▸ Update to Current Process. See [process versions](process-versions.md). +### Big views open without sorting the whole library again +- Showing All Photos, Recently Added or a smart album, or clearing a filter or search, no longer sorts every photo of + the library each time. Once a sort (capture date, import date, edit date, file name, rating or file size) has been + used for a big view, LightCraft keeps that order and moves only the photos an edit changed. On a library of 312,000 + photos, All Photos then lists in about 30 ms instead of about 330 ms, and a view sorted by file name in about 30 ms + instead of about 970 ms. A view of less than about a sixteenth of the library (a folder, a search) never builds + this order itself; a mid-sized one builds it the second time it is shown in a sort, and a larger one the first time; + after that it is fast. In a library of 50,000 photos or more, + LightCraft also makes the order for the current sort in the background as soon as a view is shown, so the first big + view in that sort (All Photos after an import that started in Picks, say) no longer freezes the window for the sort + (about 0.4 s at 324,000 photos) once the background sort is done, about half a second after the first view; a big + view shown before that waits for the background sort to finish, not sorting every photo a second time beside it. + While that sort runs, the activity stack lists it as "Sorting the library". The order of the + photos is the same as before. + Photos added or removed (an import, an undone import) go into or out of that order, even after more changes than + LightCraft remembers one by one, instead of sorting the whole library again. + Once the import-date order is kept, Recently Added is read from its end, so showing it, and following an import that + is going on while it is shown, no longer passes over every photo of the library (until that order is made it still + does; the first time Recently Added is shown it is made, in the background in a library of 50,000 photos or more). + Photos an import adds are merged into each kept order in one step instead of making the order again. + ## 2026-11-02 ### The Windows title bar is readable from the moment the window opens