Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 62 additions & 10 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,31 @@ pub struct Interaction {
/// The most photos an edit may touch for the view to follow it photo by photo; a larger edit is worked out whole.
const MAX_FOLLOWED: usize = 256;

/// The established clock precision for relative-date views and sidebar counts.
fn clock_minute(now: &str) -> &str {
now.get(..16).unwrap_or(now)
}

/// Whether a query can change membership without a catalog edit, including the smart albums it tests.
fn filter_depends_on_clock(filter: &Filter, catalog: &Catalog) -> bool {
if filter.depends_on_now() {
return true;
}
let mut pending = filter.albums_tested();
let mut seen = std::collections::HashSet::new();
while let Some(id) = pending.pop() {
if !seen.insert(id) {
continue;
}
let Some(smart) = catalog.album(id).and_then(|album| album.smart.as_deref()) else { continue };
if smart.depends_on_now() {
return true;
}
pending.extend(smart.albums_tested());
}
false
}

/// Source of [`Session::visible_shared`] generations (process-wide, so two sessions never share one).
static VISIBLE_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
static LIBRARY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
Expand All @@ -215,6 +240,8 @@ pub struct Session {
/// Shared, so frontends can hold it across frames without copying ([`Session::visible_shared`]).
visible: Arc<[PhotoId]>,
visible_key: Option<(u64, String)>,
/// The minute used for a cached view whose rules depend on the session clock.
visible_clock_minute: Option<String>,
/// A view holds the photos it shows until it is refreshed (`library.holdView`): an edit that makes a photo stop
/// matching a smart album's rules, Picks or the filter bar leaves it where it is. Off: the photo goes at once.
pub hold_view: bool,
Expand All @@ -234,7 +261,7 @@ pub struct Session {
/// is recomputed, so frontends can key their per-view caches on it instead of hashing the ids.
visible_gen: u64,
/// Photos in the current source with no filter on (cached like `visible`).
total: Option<((u64, String), usize)>,
total: Option<((u64, String), usize, Option<String>)>,
pub undo: Vec<UndoEntry>,
/// Undo steps committed in this session, ever (the history drops its oldest past 1000, so
/// its length can't tell how many steps a command just made; see [`Session::commits`]).
Expand Down Expand Up @@ -429,6 +456,7 @@ impl Session {
selection: Selection::default(),
visible: Vec::new().into(),
visible_key: None,
visible_clock_minute: None,
hold_view: false,
base: None,
view_followed: 0,
Expand Down Expand Up @@ -1053,9 +1081,16 @@ impl Session {
// the view fills in as the background checks find files gone
key.1.push_str(&format!("|{}", self.media.availability.generation()));
}
if self.visible_key.as_ref() != Some(&key) {
// "in the last N days" rules count back from the session's clock
lightcraft_catalog::rules::set_now(Some((self.clock)()));
let key_changed = self.visible_key.as_ref() != Some(&key);
// A time-dependent cache needs one clock read to test its minute stamp. A new view also
// needs one value for the query, even when its previous cached view did not use the clock.
let current_now = (key_changed || self.visible_clock_minute.is_some()).then(|| (self.clock)());
let current_minute = current_now.as_deref().map(clock_minute);
let clock_changed = self.visible_clock_minute.as_deref().is_some_and(|cached| current_minute != Some(cached));
if key_changed || clock_changed {
// Use this same value to evaluate relative rules and stamp the result.
let now = current_now.unwrap_or_else(|| (self.clock)());
lightcraft_catalog::rules::set_now(Some(now.clone()));
let f = self.view_filter(self.source, &self.filter);
// A held view keeps the photos it shows that stopped matching what is asked of them (a smart album's
// rules, a flag, the filter bar), as long as they are still where the view looks: in the library for
Expand All @@ -1082,8 +1117,7 @@ impl Session {
let whole = own_order || matches!(self.source, LibrarySource::RecentlyAdded | LibrarySource::Missing);
// A view that asks about "the last N days" (itself, or through a smart album it looks into) changes
// with the clock as well as with edits: a photo nobody touched can stop matching. It is asked whole.
let clocked = f.depends_on_now()
|| (!f.albums_tested().is_empty() && self.catalog.albums().any(|al| al.smart.as_deref().is_some_and(Filter::depends_on_now)));
let clocked = filter_depends_on_clock(&f, &self.catalog);
let base = self.base.take().filter(|(of, _, _)| *of == view);
// A small edit to the same view: the photos it touched are taken out, asked about again, and put back
// at their place in the order. The others neither stopped matching nor moved.
Expand Down Expand Up @@ -1157,6 +1191,7 @@ impl Session {
self.visible = visible.into();
self.visible_gen = VISIBLE_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.visible_key = Some(key);
self.visible_clock_minute = clocked.then(|| clock_minute(&now).to_owned());
}
&self.visible
}
Expand Down Expand Up @@ -1189,12 +1224,20 @@ impl Session {
/// view, so a list followed many times over is compared, not only one followed once.
#[cfg(test)]
pub(crate) fn visible_in_full(&mut self) -> Vec<PhotoId> {
let kept = (self.base.clone(), self.visible_key.clone(), self.visible.clone(), self.visible_gen, self.view_followed, self.view_worked_out);
let kept = (
self.base.clone(),
self.visible_key.clone(),
self.visible_clock_minute.clone(),
self.visible.clone(),
self.visible_gen,
self.view_followed,
self.view_worked_out,
);
self.never_follow = true;
self.visible_key = None;
let whole = self.visible().to_vec();
self.never_follow = false;
(self.base, self.visible_key, self.visible, self.visible_gen, self.view_followed, self.view_worked_out) = kept;
(self.base, self.visible_key, self.visible_clock_minute, self.visible, self.visible_gen, self.view_followed, self.view_worked_out) = kept;
whole
}

Expand Down Expand Up @@ -1222,7 +1265,15 @@ impl Session {
}
}
let key = (self.catalog.revision, format!("{:?}|{:?}|{:?}", self.source, self.browse, self.library_folder));
if self.total.as_ref().map(|t| &t.0) != Some(&key) {
let key_changed = self.total.as_ref().map(|total| &total.0) != Some(&key);
let cached_minute = self.total.as_ref().and_then(|total| total.2.as_deref());
let current_now = cached_minute.map(|_| (self.clock)());
let current_minute = current_now.as_deref().map(clock_minute);
let clock_changed = cached_minute.is_some_and(|cached| current_minute != Some(cached));
if key_changed || clock_changed {
// The source count can be requested before `visible`; bind it to the session's clock itself.
let now = current_now.unwrap_or_else(|| (self.clock)());
lightcraft_catalog::rules::set_now(Some(now.clone()));
let mut f = self.source.to_filter(&Filter::default(), &self.catalog);
if self.source == LibrarySource::Folder {
let b = self.browse.clone().unwrap_or_default();
Expand All @@ -1234,7 +1285,8 @@ impl Session {
}
// (how many, not which: nothing to put in order)
let n = self.catalog.count(&f);
self.total = Some((key, n));
let clocked = filter_depends_on_clock(&f, &self.catalog);
self.total = Some((key, n, clocked.then(|| clock_minute(&now).to_owned())));
}
self.total.as_ref().map(|t| t.1)
}
Expand Down
45 changes: 44 additions & 1 deletion crates/engine/src/tests_hold_view.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
//! A view holds the photos it shows until it is refreshed (`library.holdView`): an edit that makes a photo stop
//! matching a smart album's rules, Picks or the filter bar leaves it where it is, and the others where they are.

use lightcraft_catalog::PhotoId;
use lightcraft_catalog::{Op, Photo, PhotoId, Source};
use serde_json::json;

use crate::{LibrarySource, Session};

fn relative_clock_session(captures: &[&str]) -> (Session, std::sync::Arc<std::sync::Mutex<String>>, Vec<PhotoId>) {
let mut s = Session::new();
let now = std::sync::Arc::new(std::sync::Mutex::new("2026-10-24T12:00:00".to_string()));
let clock = now.clone();
s.clock = Box::new(move || clock.lock().unwrap().clone());
let mut ids = Vec::new();
for (index, captured) in captures.iter().enumerate() {
let id = PhotoId(index as u64 + 1);
let name = format!("synthetic-{index}.jpg");
let mut photo = Photo::new(id, Source::Demo { scene: 0 }, &name, "JPEG", 2, 2, "2026-10-01T00:00:00");
photo.captured = Some((*captured).to_string());
s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();
ids.push(id);
}
(s, now, ids)
}

/// The demo library with no photo keyworded, showing a smart album of the photos without keywords, at random.
fn unkeyworded() -> Session {
let mut s = Session::with_demo();
Expand Down Expand Up @@ -198,3 +215,29 @@ fn asking_for_the_state_it_has_changes_nothing_and_a_word_is_not_a_bool() {
assert!(s.execute("library.holdView", &json!({"on": "false"})).is_err());
assert!(s.hold_view, "a refused call changes nothing");
}

#[test]
fn relative_clock_held_view_keeps_expired_photos_admits_new_matches_and_refreshes() {
let (mut s, now, ids) = relative_clock_session(&["2026-10-23T12:00:30", "2026-10-22T12:00:30"]);
let rules = json!({
"ruleSet": {
"match": "any",
"rules": [
{"field": "captureDate", "op": "inLast", "value": 1},
{"field": "captureDate", "op": "notInLast", "value": 2}
]
}
});
s.execute("library.filter", &rules).unwrap();
s.execute("library.holdView", &json!({"on": true})).unwrap();
assert_eq!(s.visible_cloned(), vec![ids[0]], "only the soon-to-expire photo matches initially");

*now.lock().unwrap() = "2026-10-24T12:01:00".to_string();
let held = s.visible_cloned();
assert_eq!(held.len(), 2, "the expired photo stays held while the newly matching photo enters: {held:?}");
assert!(held.contains(&ids[0]), "the expired photo remains held");
assert!(held.contains(&ids[1]), "the photo crossing the second relative boundary enters");

s.execute("library.refresh", &json!({})).unwrap();
assert_eq!(s.visible_cloned(), vec![ids[1]], "explicit refresh releases the expired photo");
}
142 changes: 141 additions & 1 deletion crates/engine/src/tests_view_follow.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! The view follows a small edit from the list it had ([`Session::visible`]): whatever the edit, the result has to
//! be the list worked out from every photo.

use lightcraft_catalog::{Op, Photo, PhotoId, Source};
use lightcraft_catalog::{Album, Op, Photo, PhotoId, Source};
use serde_json::{Value, json};

use crate::Session;
Expand Down Expand Up @@ -113,6 +113,23 @@ fn edit(s: &mut Session, dice: &mut Dice, ids: &mut Vec<PhotoId>, album: u64) {
};
}

fn relative_clock_session(captures: &[&str]) -> (Session, std::sync::Arc<std::sync::Mutex<String>>, Vec<PhotoId>) {
let mut s = Session::new();
let now = std::sync::Arc::new(std::sync::Mutex::new("2026-10-24T12:00:00".to_string()));
let clock = now.clone();
s.clock = Box::new(move || clock.lock().unwrap().clone());
let mut ids = Vec::new();
for (index, captured) in captures.iter().enumerate() {
let id = PhotoId(index as u64 + 1);
let name = format!("synthetic-{index}.jpg");
let mut photo = Photo::new(id, Source::Demo { scene: 0 }, &name, "JPEG", 2, 2, "2026-10-01T00:00:00");
photo.captured = Some((*captured).to_string());
s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();
ids.push(id);
}
(s, now, ids)
}

#[test]
fn following_an_edit_gives_the_list_worked_out_from_every_photo() {
let (mut s, mut ids, album, smart) = library(240);
Expand Down Expand Up @@ -161,6 +178,129 @@ fn following_an_edit_gives_the_list_worked_out_from_every_photo() {
assert!(s.view_followed > 400, "followed {} times, worked out {} times", s.view_followed, s.view_worked_out);
}

#[test]
fn relative_clock_filter_expires_without_catalog_or_history_mutation() {
let (mut s, now, ids) = relative_clock_session(&["2026-10-23T12:00:30"]);
s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}})).unwrap();
let (before_generation, before) = s.visible_shared();
assert_eq!(before.as_ref(), ids.as_slice());
let revision = s.catalog.revision;
let commits = s.commits;
let undo = s.undo.len();
let redo = s.redo.len();

*now.lock().unwrap() = "2026-10-24T12:01:00".to_string();
let (after_generation, after) = s.visible_shared();

assert!(after.is_empty(), "a relative filter must expire when its minute changes");
assert_ne!(after_generation, before_generation, "the changed list gets a new visible generation");
assert_eq!(s.catalog.revision, revision, "clock expiry is not a catalog edit");
assert_eq!(s.commits, commits, "clock expiry adds no undo step");
assert_eq!(s.undo.len(), undo);
assert_eq!(s.redo.len(), redo);
}

#[test]
fn relative_clock_direct_and_nested_smart_album_sources_expire() {
for nested in [false, true] {
let (mut s, now, ids) = relative_clock_session(&["2026-10-23T12:00:30"]);
let recent = s
.execute(
"album.createSmart",
&json!({"name": "Recent", "rules": {"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}}}),
)
.unwrap()["id"]
.as_u64()
.unwrap();
let source = if nested {
s.execute(
"album.createSmart",
&json!({"name": "In Recent", "rules": {"ruleSet": {"rules": [{"field": "album", "op": "is", "value": recent}]}}}),
)
.unwrap()["id"]
.as_u64()
.unwrap()
} else {
recent
};
s.execute("library.source", &json!({"kind": "album", "id": source})).unwrap();
assert_eq!(s.visible_cloned(), ids);
let revision = s.catalog.revision;

*now.lock().unwrap() = "2026-10-24T12:01:00".to_string();
assert!(s.visible_cloned().is_empty(), "nested={nested}");
assert_eq!(s.catalog.revision, revision, "nested={nested}");
}
}

#[test]
fn relative_clock_source_total_expires_before_or_after_visible_refresh() {
for refresh_visible in [false, true] {
let (mut s, now, _) = relative_clock_session(&["2026-10-23T12:00:30"]);
let album = s
.execute(
"album.createSmart",
&json!({"name": "Recent", "rules": {"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}}}),
)
.unwrap()["id"]
.as_u64()
.unwrap();
s.execute("library.source", &json!({"kind": "album", "id": album})).unwrap();
s.execute("library.filter", &json!({"text": "synthetic"})).unwrap();
assert_eq!(s.source_total(), Some(1), "the initial total is computed without asking for visible photos");
let revision = s.catalog.revision;

*now.lock().unwrap() = "2026-10-24T12:01:00".to_string();
if refresh_visible {
s.execute("library.refresh", &json!({})).unwrap();
assert!(s.visible_cloned().is_empty());
}
assert_eq!(s.source_total(), Some(0), "refresh_visible={refresh_visible}");
assert_eq!(s.catalog.revision, revision, "refresh_visible={refresh_visible}");
}
}

#[test]
fn relative_clock_absolute_and_same_minute_views_keep_their_generations() {
let (mut absolute, absolute_now, _) = relative_clock_session(&["2026-10-23T12:00:30"]);
absolute.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "is", "value": "2026-10-23"}]}})).unwrap();
let (absolute_generation, absolute_ids) = absolute.visible_shared();
*absolute_now.lock().unwrap() = "2026-10-25T12:10:00".to_string();
let (after_absolute_generation, after_absolute_ids) = absolute.visible_shared();
assert_eq!(after_absolute_generation, absolute_generation);
assert_eq!(after_absolute_ids, absolute_ids);

let (mut relative, relative_now, _) = relative_clock_session(&["2026-10-23T12:00:30"]);
relative.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}})).unwrap();
let (relative_generation, relative_ids) = relative.visible_shared();
*relative_now.lock().unwrap() = "2026-10-24T12:00:45".to_string();
let (same_minute_generation, same_minute_ids) = relative.visible_shared();
assert_eq!(same_minute_generation, relative_generation);
assert_eq!(same_minute_ids, relative_ids);
}

#[test]
fn relative_clock_unrelated_smart_album_does_not_expire_album_filter_view() {
let (mut s, now, ids) = relative_clock_session(&["2026-10-23T12:00:30"]);
let manual = s.catalog.alloc_album_id();
s.catalog.apply(Op::AddAlbum { album: Album::new(manual, "Manual") }).unwrap();
s.catalog.apply(Op::SetAlbumPhotos { id: manual, photos: vec![ids[0]] }).unwrap();
s.execute(
"album.createSmart",
&json!({"name": "Unrelated recent", "rules": {"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}}}),
)
.unwrap();
s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "album", "op": "is", "value": manual.0}]}})).unwrap();
let (generation, visible) = s.visible_shared();
assert_eq!(visible.as_ref(), ids.as_slice());

*now.lock().unwrap() = "2026-10-24T12:01:00".to_string();
let (after_generation, after_visible) = s.visible_shared();

assert_eq!(after_generation, generation, "an unrelated relative smart album must not expire this view");
assert_eq!(after_visible, visible);
}

#[test]
fn a_view_that_asks_about_the_last_days_follows_the_clock_too() {
let (mut s, ids, _, _) = library(60);
Expand Down
Loading
Loading