Skip to content
Open
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
23 changes: 16 additions & 7 deletions crates/catalog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,9 @@ impl Aspects {
pub const ANALYSIS: Aspects = Aspects(1 << 7);
/// Whether it is in the library at all: added, removed, deleted, restored, taken in from Local.
pub const PRESENCE: Aspects = Aspects(1 << 8);
/// The keyword list (keywords on their own and their attributes): of no photo, and read by no rule, filter or
/// sort, only by what lists keywords (the keyword tree, export names).
pub const KEYWORD_LIST: Aspects = Aspects(1 << 9);
/// Everything: the photo may count differently for any tally.
pub const ALL: Aspects = Aspects(u16::MAX);

Expand All @@ -340,9 +343,11 @@ struct Changes {
touched: std::collections::VecDeque<(u64, PhotoId, Aspects)>,
/// What the op being applied changes of its photo.
now: Aspects,
/// The latest revision made by an op that changed more than photos of its own (an album, a stack, a keyword of
/// the list…): what it changed for which photos is not known.
/// The latest revision made by an op that changed more than photos of its own (an album, a stack…): what it
/// changed for which photos is not known.
broad: u64,
/// The latest revision made by an op that changed the keyword list ([`Aspects::KEYWORD_LIST`]).
keyword_list: u64,
/// Changes up to this revision are no longer all in `touched`.
floor: u64,
/// The revision the last op recorded here made. When the catalog's revision is another, it was set from
Expand Down Expand Up @@ -589,7 +594,8 @@ impl Catalog {
if !self.remembers(revision) {
return None;
}
Some(self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a)))
let photos = self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a));
Some(if self.changes.keyword_list > revision { photos.with(Aspects::KEYWORD_LIST) } else { photos })
}

/// Whether every change since the catalog was at `revision` is remembered photo by photo.
Expand Down Expand Up @@ -622,6 +628,7 @@ impl Catalog {
self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() };
}
let broad = self.changes.broad;
let keyword_list = self.changes.keyword_list;
self.changes.torn = false;
let inv = match self.apply_inner(op) {
Ok(inv) => inv,
Expand All @@ -643,6 +650,7 @@ impl Catalog {
self.changes.touched.pop_back();
}
self.changes.broad = broad;
self.changes.keyword_list = keyword_list;
}
return Err(e);
}
Expand All @@ -653,9 +661,9 @@ impl Catalog {
}

fn apply_inner(&mut self, op: Op) -> Result<Op> {
// An op that changes one photo says which (`photo_mut`, and adding or removing it below). Every other kind
// can change what any photo matches or where it sorts: an album's photos or rules, a stack, a keyword's
// name. Listed kind by kind, so a new one has to be put on one side.
// An op that changes one photo says which (`photo_mut`, and adding or removing it below). Most other kinds
// can change what any photo matches or where it sorts: an album's photos or rules, a stack. The keyword
// list changes only lists of keywords. Listed kind by kind, so a new one has to be put on one side.
match &op {
// (a photo that comes, goes, or changes what it is to the library counts for every tally; so do the
// rare kinds whose reach nobody has to think about)
Expand Down Expand Up @@ -695,8 +703,9 @@ impl Catalog {
| Op::SetStack { .. }
| Op::SetLabelName { .. }
| Op::SetBrowsed { .. }
| Op::SetKeyword { .. }
| Op::SetFolderRecord { .. } => self.changes.broad = self.revision.saturating_add(1),
// (no photo matches, counts or sorts by it: only lists of keywords change)
Op::SetKeyword { .. } => self.changes.keyword_list = self.revision.saturating_add(1),
}
Ok(match op {
Op::AddPhoto { photo } => {
Expand Down
19 changes: 8 additions & 11 deletions crates/catalog/src/tally.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
//! A smart album's count asks every photo whether its rules hold. Asked again after every edit, that is a pass over
//! the library for each smart album each time a keyword is given. [`AlbumTally`] remembers which photos each smart
//! album holds, and after a small edit asks only the photos the edit touched ([`Catalog::touched_since`]). An op
//! that changes more than photos of its own (an album's rules or photos, a stack, the keyword list) has it counted
//! whole again, as before.
//! that changes more than photos of its own (an album's rules or photos, a stack) has to be counted whole again
//! ([`AlbumTally::of`]): the caller decides where (the app does it off the UI thread).

use std::collections::{HashMap, HashSet};

Expand Down Expand Up @@ -168,27 +168,24 @@ impl AlbumTally {
self.revision
}

/// Bring the counts up to `cat` as it is now. `true` when that was done from the photos the ops since touched
/// (or nothing had changed), `false` when every photo was asked again.
/// Bring the counts up to `cat` as it is now from the photos the ops since touched. `true` when that was done (or
/// nothing had changed); `false` when it can't be, and every photo has to be asked again ([`AlbumTally::of`]):
/// the counts are then left as they were.
///
/// `cat` has to be the catalog the counts were made of, further along. Another catalog is told apart only by
/// its revisions: a library that is loaded takes a range of its own (and then everything is counted again), but
/// two catalogs both counting from 0 look like one.
/// its revisions: a library that is loaded takes a range of its own (and then nothing is followed), but two
/// catalogs both counting from 0 look like one.
pub fn update(&mut self, cat: &Catalog) -> bool {
if self.revision == cat.revision {
return true;
}
let followed = match (cat.touched_since(self.revision), cat.aspects_since(self.revision)) {
match (cat.touched_since(self.revision), cat.aspects_since(self.revision)) {
(Some(touched), Some(changed)) if touched.len() <= MAX_FOLLOWED => {
self.follow(cat, &touched, changed);
true
}
_ => false,
};
if !followed {
*self = AlbumTally::of(cat);
}
followed
}

/// The counts after ops that touched only `touched`: each smart album asks those photos again; an album of
Expand Down
13 changes: 13 additions & 0 deletions crates/catalog/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,12 @@ fn history_handles_loaded_revisions_failed_batches_and_retention() {
let before = c.revision;
c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 3 }, Op::RenameAlbum { id: album, name: "Journey".into() }] }).unwrap();
assert_eq!(c.touched_since(before), None);
// the keyword list changes no photo: what was touched stays known, and the list is said to have changed
let before = c.revision;
c.apply(Op::SetKeyword { path: "travel|Rome".into(), info: Some(Default::default()) }).unwrap();
assert_eq!(c.touched_since(before), Some(vec![]));
assert_eq!(c.aspects_since(before), Some(Aspects::KEYWORD_LIST));
assert_eq!(c.aspects_since(c.revision), Some(Aspects::NONE), "and from after it, not");
// more ops than are remembered: the oldest are answered with "anything"
let long_ago = c.revision;
for i in 0..9000u32 {
Expand Down Expand Up @@ -1000,6 +1006,13 @@ fn an_op_that_fails_leaves_no_touched_photos_behind() {
assert_eq!(c.revision, start);
assert_eq!(c.touched_since(start), Some(vec![]));
assert_eq!(c.aspects_since(start), Some(Aspects::NONE));
// a keyword op that fails, alone or inside a batch that is rolled back, does not say the keyword list changed
assert!(c.apply(Op::SetKeyword { path: " | ".into(), info: Some(Default::default()) }).is_err());
assert_eq!(c.aspects_since(start), Some(Aspects::NONE));
let ok = Op::SetKeyword { path: "travel|Rome".into(), info: Some(Default::default()) };
assert!(c.apply(Op::Batch { ops: vec![ok, Op::SetRating { id: missing, rating: 1 }] }).is_err());
assert_eq!(c.revision, start);
assert_eq!(c.aspects_since(start), Some(Aspects::NONE));
assert_eq!(c.photo(a).map(|p| p.rating), Some(0));
// a batch that ends in a failed removal of a photo that exists
assert!(c.apply(Op::Batch { ops: vec![Op::RemovePhoto { id: b }, Op::RemovePhoto { id: b }] }).is_err());
Expand Down
101 changes: 101 additions & 0 deletions crates/engine/src/album_counts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
//! The photo counts `albums.list` answers with.
//!
//! Counting a smart album asks every photo whether its rules hold: seconds in a large library, and a window that does
//! it on its UI thread stops answering for that long. So a window offers the counts it keeps
//! ([`Session::offer_album_counts`]; they are counted on a worker thread) and `albums.list` counts nothing itself.
//!
//! With no window (the CLI, the MCP server, a script) there is no UI thread to stop, and the caller wants the numbers:
//! they are counted here, once, and kept. An edit to a photo or a few is followed photo by photo, as the sidebar's
//! are ([`AlbumTally::update`]); anything more counts every photo again.

use std::collections::HashMap;
use std::sync::Arc;

use lightcraft_catalog::tally::AlbumTally;
use lightcraft_catalog::{AlbumId, Catalog};

/// Every album's count, as `albums.list` takes them.
pub(crate) type Counts = Arc<HashMap<AlbumId, usize>>;

/// How far the counts a window keeps are from the catalog and the session clock as they are now.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CountsAge {
/// Of the catalog as it is now, and of this minute.
Current,
/// Of the catalog as it is now, but of an earlier minute: only a smart album whose rules ask about "the last N
/// days" (its own, or those of an album it tests) can have changed since.
ClockBehind,
/// Of an earlier catalog, or none yet: every smart album's count is behind.
Behind,
}

/// Counts, and how current they are.
pub(crate) struct Answer {
pub counts: Counts,
pub age: CountsAge,
}

/// The counts a session keeps for `albums.list`.
#[derive(Default)]
pub(crate) struct AlbumCounts {
/// What a window offered for the next `albums.list`.
offered: Option<Answer>,
/// Counted here, when no window offers any.
kept: Option<Kept>,
/// How often every photo was counted here (tests check that a repeated list, and an edit to a photo or a few,
/// don't).
pub scans: usize,
}

/// The counts made here.
struct Kept {
/// The library they are of ([`Session::library_generation`]): album ids start again in every library.
library: u64,
/// The minute they are of while a smart album asks about "the last N days" (else empty).
minute: String,
tally: AlbumTally,
shown: Counts,
}

impl AlbumCounts {
/// `albums.list` takes `counts` next, `age` being how far they are from the catalog and the clock as they are now.
pub fn offer(&mut self, counts: Counts, age: CountsAge) {
self.offered = Some(Answer { counts, age });
}

/// Nothing is offered any more.
pub fn withdraw(&mut self) {
self.offered = None;
}

/// The counts for `albums.list`: the ones offered, else counted here (`now` is the session clock).
pub fn answer(&mut self, cat: &Catalog, library: u64, now: &str) -> Answer {
if let Some(offered) = self.offered.take() {
return offered;
}
let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now()));
let minute = if relative { crate::clock_minute(now) } else { "" };
if relative {
// "in the last N days" counts back from the session clock, as in the grid
lightcraft_catalog::rules::set_now(Some(now.to_string()));
}
let followed = self.kept.take().filter(|k| k.library == library && k.minute == minute).and_then(|mut k| {
if k.tally.revision() == cat.revision {
return Some(k);
}
k.tally.update(cat).then(|| {
k.shown = Arc::new(k.tally.counts().clone());
k
})
});
let kept = followed.unwrap_or_else(|| {
self.scans += 1;
let tally = AlbumTally::of(cat);
let shown = Arc::new(tally.counts().clone());
Kept { library, minute: minute.to_string(), tally, shown }
});
let counts = kept.shown.clone();
self.kept = Some(kept);
Answer { counts, age: CountsAge::Current }
}
}
33 changes: 26 additions & 7 deletions crates/engine/src/cmd/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use lightcraft_develop::{CONTROLS, controls};
use serde_json::{Value, json};

use super::{CommandSpec, always, bad, cmd, has_active};
use crate::{LibrarySource, Session};
use crate::{CountsAge, LibrarySource, Session};

pub fn photo_summary(p: &Photo) -> Value {
json!({
Expand Down Expand Up @@ -38,21 +38,37 @@ pub fn photo_summary(p: &Photo) -> Value {
/// instead of overflowing the stack.
const MAX_ALBUM_DEPTH: usize = 64;

fn album_json(a: &Album, all: &[Album], counts: &HashMap<AlbumId, usize>, cat: &lightcraft_catalog::Catalog, depth: usize) -> Value {
/// The counts [`album_json`] shows a smart album with, and how far they are from the catalog and the clock as they are now.
struct AlbumCounts<'a> {
counts: &'a HashMap<AlbumId, usize>,
age: CountsAge,
}

fn album_json(a: &Album, all: &[Album], counts: &AlbumCounts, cat: &lightcraft_catalog::Catalog, depth: usize) -> Value {
let children: Vec<Value> = if depth < MAX_ALBUM_DEPTH {
all.iter().filter(|c| c.parent == Some(a.id)).map(|c| album_json(c, all, counts, cat, depth + 1)).collect()
} else {
Vec::new()
};
// An album of chosen photos is counted from its list, at once; a smart album's rules are asked of every photo, so
// its count is the one kept.
let count = if a.is_smart() { counts.counts.get(&a.id).copied().unwrap_or(0) } else { cat.album_count(a.id) };
let mut v = json!({
"id": a.id.0,
"name": a.name,
"folder": a.folder,
"count": counts.get(&a.id).copied().unwrap_or(0),
"count": count,
"cover": a.cover.map(|c| c.0),
"children": children,
});
if let Some(rules) = &a.smart {
// Behind the catalog (an edit counted by every photo is under way), or behind the clock for an album whose rules
// ask about "the last N days": the count is the one before (0 before any), and the real one is being worked out.
v["countPending"] = json!(match counts.age {
CountsAge::Current => false,
CountsAge::ClockBehind => crate::filter_depends_on_clock(rules, cat),
CountsAge::Behind => true,
});
v["smart"] = json!(true);
v["rules"] = serde_json::to_value(rules).unwrap_or_default();
v["rulesText"] = json!(rules.describe_with(cat));
Expand Down Expand Up @@ -152,11 +168,14 @@ pub fn specs() -> Vec<CommandSpec> {
.unwrap_or_default();
Ok(json!({"exif": exif, "xmp": xmp}))
}),
cmd!(query "albums.list", "List Albums", [], None, "{}", always, |s, _| {
cmd!(query "albums.list", "List Albums", [], None, "{} → [{id, name, folder, count, cover, children, smart?, rules?, rulesText?, problems?, countPending?}] — a smart album's `count` comes from the counts kept (`countPending: true`: not of the catalog as it is now yet, the ones before or 0)", always, |s, _| {
let all: Vec<Album> = s.catalog.albums().cloned().collect();
// every album counted in one pass, so a smart album tested by others is worked out once
let counts = lightcraft_catalog::tally::AlbumTally::of(&s.catalog);
Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all, counts.counts(), &s.catalog, 0)).collect()))
// counted nowhere here when a window keeps the counts; else every album in one pass, so a smart album tested
// by others is worked out once, and kept
let (now, library) = ((s.clock)(), s.library_generation());
let counted = s.album_counts.answer(&s.catalog, library, &now);
let counts = AlbumCounts { counts: &counted.counts, age: counted.age };
Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all, &counts, &s.catalog, 0)).collect()))
}),
cmd!(query "photo.inspect", "Inspect Photo", [], None, "{id?}", always, |s, p| {
let id = photo_arg(s, p, "photo.inspect")?;
Expand Down
18 changes: 18 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
extern crate lightcraft_denoise_core as lightcraft_denoise;

pub mod activity;
mod album_counts;
#[cfg(not(target_arch = "wasm32"))]
pub mod apple_photos;
pub mod availability;
Expand Down Expand Up @@ -85,6 +86,7 @@ pub mod walk;

use std::sync::Arc;

pub use album_counts::CountsAge;
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use errors::{AiModel, ErrorKind};
pub use fonts::{CRAFT_FONTS, CraftFont};
Expand Down Expand Up @@ -226,6 +228,8 @@ static LIBRARY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64:

pub struct Session {
library_generation: u64,
/// The counts `albums.list` answers with.
album_counts: album_counts::AlbumCounts,
/// Auto Sync: edits to the active photo also change the other selected photos (the settings
/// that changed, nothing else).
pub auto_sync: bool,
Expand Down Expand Up @@ -444,9 +448,23 @@ impl Session {
self.library_generation
}

/// The next `albums.list` answers with `counts` and counts nothing itself: a window that keeps the albums' counts
/// (counted off its UI thread) offers them with how far they are from the catalog and the clock as they are now,
/// and `albums.list` marks the smart albums whose count is behind as pending.
/// [`Session::withdraw_album_counts`] takes the offer back once the command has run.
pub fn offer_album_counts(&mut self, counts: Arc<std::collections::HashMap<lightcraft_catalog::AlbumId, usize>>, age: CountsAge) {
self.album_counts.offer(counts, age);
}

/// Take back what [`Session::offer_album_counts`] offered, if `albums.list` didn't use it.
pub fn withdraw_album_counts(&mut self) {
self.album_counts.withdraw();
}

pub fn new() -> Session {
Session {
library_generation: LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
album_counts: album_counts::AlbumCounts::default(),
auto_sync: false,
catalog: Catalog::new(),
source: LibrarySource::All,
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use serde_json::{Value, json};

use crate::{Selection, Session, command_specs};

mod album_counts;
mod album_order;
mod album_remove;
mod albums_local;
Expand Down
Loading
Loading