Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

M1.13: smart albums — saved filters that update live

Brandon Thomas50741eceb419
diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs
index 4b03795c8..6b3344744 100644
--- a/crates/catalog/src/lib.rs
+++ b/crates/catalog/src/lib.rs
@@ -113,6 +113,11 @@ pub enum Op {
id: AlbumId,
cover: Option<PhotoId>,
},
+ /// Replace a smart album's rules.
+ SetAlbumRules {
+ id: AlbumId,
+ rules: Box<Filter>,
+ },
/// Several ops as one step (undo applies the inverses in reverse).
Batch {
ops: Vec<Op>,
@@ -168,8 +173,51 @@ impl Catalog {
pub fn albums(&self) -> impl Iterator<Item = &Album> {
self.albums.values()
}
+ /// Albums (regular and smart) that contain the photo.
pub fn albums_of(&self, id: PhotoId) -> Vec<AlbumId> {
- self.albums.values().filter(|a| a.photos.contains(&id)).map(|a| a.id).collect()
+ let Some(p) = self.photos.get(&id) else { return Vec::new() };
+ self.albums.values().filter(|a| self.album_contains(a.id, p)).map(|a| a.id).collect()
+ }
+
+ /// Whether album `id` contains `p` (a smart album evaluates its rules; deleted photos are in
+ /// no smart album).
+ pub fn album_contains(&self, id: AlbumId, p: &Photo) -> bool {
+ match self.albums.get(&id) {
+ Some(Album { smart: Some(rules), .. }) => !p.deleted && rules.matches(p, self),
+ Some(a) => a.photos.contains(&p.id),
+ None => false,
+ }
+ }
+
+ /// The photos of an album: the stored list, or a smart album's current matches (id order).
+ pub fn album_photos(&self, id: AlbumId) -> Vec<PhotoId> {
+ match self.albums.get(&id) {
+ Some(Album { smart: Some(_), .. }) => self.photos.values().filter(|p| self.album_contains(id, p)).map(|p| p.id).collect(),
+ Some(a) => a.photos.clone(),
+ None => Vec::new(),
+ }
+ }
+
+ /// Number of photos shown for an album in the sources list (excludes deleted photos).
+ pub fn album_count(&self, id: AlbumId) -> usize {
+ match self.albums.get(&id) {
+ Some(Album { smart: Some(_), .. }) => self.album_photos(id).len(),
+ Some(a) => a.photos.iter().filter(|p| self.photos.get(p).is_some_and(|p| !p.deleted)).count(),
+ None => 0,
+ }
+ }
+
+ /// Smart-album rules must not reference another smart album (no recursion) or deleted photos.
+ fn validate_rules(&self, rules: &Filter) -> Result<()> {
+ if rules.deleted {
+ return Err(CatalogError::Invalid("smart album rules can't select deleted photos".into()));
+ }
+ if let Some(a) = rules.album
+ && self.albums.get(&a).is_some_and(Album::is_smart)
+ {
+ return Err(CatalogError::Invalid("smart album rules can't reference another smart album".into()));
+ }
+ Ok(())
}
// ---- writes
@@ -261,6 +309,12 @@ impl Catalog {
{
return Err(CatalogError::Invalid("parent must be an existing folder".into()));
}
+ if let Some(rules) = &album.smart {
+ if album.folder || !album.photos.is_empty() {
+ return Err(CatalogError::Invalid("a smart album holds rules, not photos".into()));
+ }
+ self.validate_rules(rules)?;
+ }
let id = album.id;
self.next_album = self.next_album.max(id.0 + 1);
self.albums.insert(id, album);
@@ -296,8 +350,10 @@ impl Catalog {
}
Op::SetAlbumPhotos { id, photos } => {
let a = self.album_mut(id)?;
- if a.folder && !photos.is_empty() {
- return Err(CatalogError::Invalid("folders can't hold photos".into()));
+ if (a.folder || a.smart.is_some()) && !photos.is_empty() {
+ return Err(CatalogError::Invalid(
+ if a.folder { "folders can't hold photos" } else { "smart albums update automatically" }.into(),
+ ));
}
Op::SetAlbumPhotos { id, photos: std::mem::replace(&mut a.photos, photos) }
}
@@ -305,6 +361,14 @@ impl Catalog {
let a = self.album_mut(id)?;
Op::SetAlbumCover { id, cover: std::mem::replace(&mut a.cover, cover) }
}
+ Op::SetAlbumRules { id, rules } => {
+ self.validate_rules(&rules)?;
+ let a = self.album_mut(id)?;
+ let Some(old) = a.smart.as_mut() else {
+ return Err(CatalogError::Invalid("not a smart album".into()));
+ };
+ Op::SetAlbumRules { id, rules: std::mem::replace(old, rules) }
+ }
Op::Batch { ops } => {
let mut inverses = Vec::with_capacity(ops.len());
for op in ops {
diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs
index ad15b7ef7..f0fa839ed 100644
--- a/crates/catalog/src/model.rs
+++ b/crates/catalog/src/model.rs
@@ -203,4 +203,18 @@ pub struct Album {
pub photos: Vec<PhotoId>,
#[serde(default)]
pub cover: Option<PhotoId>,
+ /// A smart album: its photos are every (non-deleted) photo matching these rules, evaluated
+ /// live; `photos` stays empty.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub smart: Option<Box<crate::Filter>>,
+}
+
+impl Album {
+ /// A regular (manual) album.
+ pub fn new(id: AlbumId, name: impl Into<String>) -> Album {
+ Album { id, name: name.into(), parent: None, folder: false, photos: Vec::new(), cover: None, smart: None }
+ }
+ pub fn is_smart(&self) -> bool {
+ self.smart.is_some()
+ }
}
diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs
index e7a406d28..416b996ad 100644
--- a/crates/catalog/src/query.rs
+++ b/crates/catalog/src/query.rs
@@ -33,6 +33,12 @@ pub struct Filter {
pub date: Option<String>,
pub keyword: Option<String>,
pub camera: Option<String>,
+ /// Lens (case-insensitive substring).
+ pub lens: Option<String>,
+ /// Capture date range, inclusive: `dateFrom` is compared as a lower bound (`2026-04-01`),
+ /// `dateTo` as a prefix upper bound (`2026-04` includes all of April).
+ pub date_from: Option<String>,
+ pub date_to: Option<String>,
/// Import date prefix (Recently Added).
pub imported: Option<String>,
}
@@ -100,6 +106,48 @@ fn token_matches(p: &Photo, tok: &str) -> bool {
}
impl Filter {
+ /// Human-readable summary of the active rules (smart album tooltips, `album.list`).
+ pub fn describe(&self) -> String {
+ let mut v: Vec<String> = Vec::new();
+ if self.rating > 0 {
+ let op = match self.rating_op {
+ RatingOp::AtLeast => "≥",
+ RatingOp::Exactly => "=",
+ RatingOp::AtMost => "≤",
+ };
+ v.push(format!("rating {op} {}", self.rating));
+ }
+ if let Some(f) = self.flag {
+ v.push(format!("flag {}", format!("{f:?}").to_lowercase()));
+ }
+ if let Some(l) = self.label {
+ v.push(format!("label {}", format!("{l:?}").to_lowercase()));
+ }
+ if let Some(k) = self.kind {
+ v.push(format!("kind {}", format!("{k:?}").to_lowercase()));
+ }
+ if let Some(e) = self.edited {
+ v.push(if e { "edited".into() } else { "unedited".into() });
+ }
+ for (name, val) in
+ [("keyword", &self.keyword), ("camera", &self.camera), ("lens", &self.lens), ("date", &self.date), ("imported", &self.imported)]
+ {
+ if let Some(x) = val {
+ v.push(format!("{name} {x}"));
+ }
+ }
+ match (&self.date_from, &self.date_to) {
+ (Some(a), Some(b)) => v.push(format!("captured {a} – {b}")),
+ (Some(a), None) => v.push(format!("captured from {a}")),
+ (None, Some(b)) => v.push(format!("captured until {b}")),
+ _ => {}
+ }
+ if !self.text.trim().is_empty() {
+ v.push(format!("“{}”", self.text.trim()));
+ }
+ if v.is_empty() { "all photos".into() } else { v.join(", ") }
+ }
+
pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool {
if p.deleted != self.deleted {
return false;
@@ -121,7 +169,22 @@ impl Filter {
return false;
}
if let Some(a) = self.album
- && !cat.album(a).is_some_and(|al| al.photos.contains(&p.id))
+ && !cat.album_contains(a, p)
+ {
+ return false;
+ }
+ if let Some(from) = &self.date_from
+ && p.date() < from.as_str()
+ {
+ return false;
+ }
+ if let Some(to) = &self.date_to
+ && p.date().get(..to.len()).unwrap_or(p.date()) > to.as_str()
+ {
+ return false;
+ }
+ if let Some(l) = &self.lens
+ && !p.meta.lens.to_lowercase().contains(&l.to_lowercase())
{
return false;
}
diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs
index 37ecec432..a18f94794 100644
--- a/crates/catalog/src/tests.rs
+++ b/crates/catalog/src/tests.rs
@@ -57,9 +57,11 @@ fn albums_and_folders() {
let mut c = Catalog::new();
let a = photo(&mut c, "a.jpg", "2026-04-01");
let f = c.alloc_album_id();
- c.apply(Op::AddAlbum { album: Album { id: f, name: "Trips".into(), parent: None, folder: true, photos: vec![], cover: None } }).unwrap();
+ c.apply(Op::AddAlbum { album: Album { id: f, name: "Trips".into(), parent: None, folder: true, photos: vec![], cover: None, smart: None } })
+ .unwrap();
let al = c.alloc_album_id();
- c.apply(Op::AddAlbum { album: Album { id: al, name: "Alps".into(), parent: Some(f), folder: false, photos: vec![a], cover: None } }).unwrap();
+ c.apply(Op::AddAlbum { album: Album { id: al, name: "Alps".into(), parent: Some(f), folder: false, photos: vec![a], cover: None, smart: None } })
+ .unwrap();
assert_eq!(c.albums_of(a), vec![al]);
assert!(c.apply(Op::RemoveAlbum { id: f }).is_err(), "non-empty folder");
assert!(c.apply(Op::SetAlbumPhotos { id: f, photos: vec![a] }).is_err(), "folders hold no photos");
@@ -141,3 +143,51 @@ proptest::proptest! {
proptest::prop_assert_eq!(c.to_snapshot(), start);
}
}
+
+#[test]
+fn smart_albums_update_live() {
+ let mut c = Catalog::new();
+ let a = photo(&mut c, "a.jpg", "2026-04-01T10:00:00");
+ let b = photo(&mut c, "b.jpg", "2026-05-02T10:00:00");
+ let z = photo(&mut c, "z.jpg", "2025-12-31T10:00:00");
+ let id = c.alloc_album_id();
+ let rules = Filter { rating: 3, date_from: Some("2026-01-01".into()), date_to: Some("2026-04".into()), ..Default::default() };
+ c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(rules)), ..Album::new(id, "Good spring") } }).unwrap();
+ assert!(c.album_photos(id).is_empty());
+ for p in [a, b, z] {
+ c.apply(Op::SetRating { id: p, rating: 4 }).unwrap();
+ }
+ // b is after the range, z before it
+ assert_eq!(c.album_photos(id), vec![a]);
+ assert_eq!(c.album_count(id), 1);
+ assert_eq!(c.albums_of(a), vec![id]);
+ // via the album filter (what the grid uses)
+ assert_eq!(c.query(&Filter { album: Some(id), ..Default::default() }, &Sort::default()), vec![a]);
+ // deleted photos drop out
+ c.apply(Op::SetDeleted { id: a, deleted: true }).unwrap();
+ assert!(c.album_photos(id).is_empty());
+ c.apply(Op::SetDeleted { id: a, deleted: false }).unwrap();
+ // change the rules; inverse restores
+ let inv = c.apply(Op::SetAlbumRules { id, rules: Box::new(Filter { rating: 4, rating_op: RatingOp::Exactly, ..Default::default() }) }).unwrap();
+ assert_eq!(c.album_photos(id), vec![a, b, z]);
+ c.apply(inv).unwrap();
+ assert_eq!(c.album_photos(id), vec![a]);
+ // smart albums hold no photos and can't nest smart rules
+ assert!(c.apply(Op::SetAlbumPhotos { id, photos: vec![b] }).is_err());
+ let id2 = c.alloc_album_id();
+ let bad = Filter { album: Some(id), ..Default::default() };
+ assert!(c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(bad)), ..Album::new(id2, "x") } }).is_err());
+ assert!(c.apply(Op::SetAlbumRules { id, rules: Box::new(Filter { deleted: true, ..Default::default() }) }).is_err());
+ // rules on a manual album are rejected
+ let manual = c.alloc_album_id();
+ c.apply(Op::AddAlbum { album: Album::new(manual, "m") }).unwrap();
+ assert!(c.apply(Op::SetAlbumRules { id: manual, rules: Box::new(Filter::default()) }).is_err());
+ // a smart album may narrow a manual album
+ c.apply(Op::SetAlbumPhotos { id: manual, photos: vec![b, z] }).unwrap();
+ c.apply(Op::SetAlbumRules { id, rules: Box::new(Filter { album: Some(manual), lens: Some(String::new()), ..Default::default() }) }).unwrap();
+ assert_eq!(c.album_photos(id), vec![b, z]);
+ // persisted in snapshots
+ let back = Catalog::from_snapshot(&c.to_snapshot()).unwrap();
+ assert_eq!(back.album_photos(id), vec![b, z]);
+ assert!(Filter { rating: 3, keyword: Some("sea".into()), ..Default::default() }.describe().contains("rating ≥ 3, keyword sea"));
+}
diff --git a/crates/catalog/src/tests_journal.rs b/crates/catalog/src/tests_journal.rs
index 2cbe8098a..1cd6e6c47 100644
--- a/crates/catalog/src/tests_journal.rs
+++ b/crates/catalog/src/tests_journal.rs
@@ -19,7 +19,14 @@ fn op_for(c: &mut Catalog, kind: u8, a: u8, b: u8) -> Op {
let albums: Vec<AlbumId> = c.albums().map(|a| a.id).collect();
let pid = photos.get(a as usize % photos.len().max(1)).copied().unwrap_or(PhotoId(99));
let aid = albums.get(a as usize % albums.len().max(1)).copied().unwrap_or(AlbumId(99));
- match kind % 10 {
+ let rules = |b: u8| Filter {
+ rating: b % 6,
+ flag: [None, Some(Flag::Pick), Some(Flag::Reject)][b as usize % 3],
+ date_from: (b % 4 == 1).then(|| "2026-01".to_string()),
+ text: if b.is_multiple_of(5) { format!("{}", b % 10) } else { String::new() },
+ ..Default::default()
+ };
+ match kind % 12 {
0 | 1 => {
let id = c.alloc_photo_id();
let mut p = Photo::new(id, Source::File { path: format!("/p/{}.jpg", id.0) }, &format!("{}.jpg", id.0), "JPEG", 60, 40, "2026-01-01");
@@ -42,11 +49,18 @@ fn op_for(c: &mut Catalog, kind: u8, a: u8, b: u8) -> Op {
}
5 => {
let id = c.alloc_album_id();
- Op::AddAlbum { album: Album { id, name: format!("A{b}"), parent: None, folder: b.is_multiple_of(4), photos: vec![], cover: None } }
+ Op::AddAlbum {
+ album: Album { id, name: format!("A{b}"), parent: None, folder: b.is_multiple_of(4), photos: vec![], cover: None, smart: None },
+ }
}
6 => Op::SetAlbumPhotos { id: aid, photos: photos.iter().copied().filter(|p| (p.0 + b as u64).is_multiple_of(3)).collect() },
7 => Op::RenameAlbum { id: aid, name: format!("Renamed {b} ✓") },
8 => Op::SetDeleted { id: pid, deleted: b.is_multiple_of(2) },
+ 10 => {
+ let id = c.alloc_album_id();
+ Op::AddAlbum { album: Album { smart: Some(Box::new(rules(b))), ..Album::new(id, format!("Smart {b}")) } }
+ }
+ 11 => Op::SetAlbumRules { id: aid, rules: Box::new(rules(b)) },
_ => c.delete_permanently_ops(pid),
}
}
diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs
index 5030286e4..b2d0d4e5a 100644
--- a/crates/engine/src/cmd/library.rs
+++ b/crates/engine/src/cmd/library.rs
@@ -309,10 +309,56 @@ pub fn specs() -> Vec<CommandSpec> {
let photos = if !folder && bool_or(p, "addSelected", false) { s.targets(&Value::Null) } else { vec![] };
let id = s.catalog.alloc_album_id();
let cover = photos.first().copied();
- s.commit(if folder { "New Folder" } else { "New Album" }, Op::AddAlbum { album: Album { id, name, parent, folder, photos, cover } })?;
+ s.commit(
+ if folder { "New Folder" } else { "New Album" },
+ Op::AddAlbum { album: Album { id, name, parent, folder, photos, cover, smart: None } },
+ )?;
Ok(json!({"id": id.0}))
}
),
+ cmd!(
+ "album.createSmart",
+ "New Smart Album…",
+ [],
+ None,
+ "{name, rules?: partial Filter (rating, ratingOp, flag, label, kind, edited, keyword, camera, lens, dateFrom, dateTo, date, text, album), parent?: folderId} — without `rules`, saves the current view (source + filter)",
+ always,
+ |s, p| {
+ let name = str_param(p, "name").unwrap_or("Smart Album").trim().to_string();
+ if name.is_empty() {
+ return Err(bad("album.createSmart", "empty name"));
+ }
+ let rules = match p.get("rules") {
+ Some(r) => merge_rules(&lightcraft_catalog::Filter::default(), r, "album.createSmart")?,
+ None => view_rules(s),
+ };
+ let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId);
+ let id = s.catalog.alloc_album_id();
+ let album = Album { parent, smart: Some(Box::new(rules)), ..Album::new(id, name) };
+ s.commit("New Smart Album", Op::AddAlbum { album })?;
+ Ok(json!({"id": id.0, "count": s.catalog.album_count(id)}))
+ }
+ ),
+ cmd!(
+ "album.setRules",
+ "Edit Smart Album",
+ [],
+ None,
+ "{id, rules?: partial Filter merged onto the current rules (null clears a field), replace?: bool, fromView?: bool (use the current view)}",
+ always,
+ |s, p| {
+ let id = album_param(p, "id", "album.setRules")?;
+ let cur = s.catalog.album(id).and_then(|a| a.smart.as_deref().cloned()).ok_or_else(|| bad("album.setRules", "not a smart album"))?;
+ let rules = if bool_or(p, "fromView", false) {
+ view_rules(s)
+ } else {
+ let base = if bool_or(p, "replace", false) { Default::default() } else { cur };
+ merge_rules(&base, p.get("rules").unwrap_or(&Value::Null), "album.setRules")?
+ };
+ s.commit("Edit Smart Album", Op::SetAlbumRules { id, rules: Box::new(rules) })?;
+ Ok(json!({"count": s.catalog.album_count(id)}))
+ }
+ ),
cmd!("album.rename", "Rename Album", [], None, "{id, name}", always, |s, p| {
let id = album_param(p, "id", "album.rename")?;
let name = str_param(p, "name").ok_or_else(|| bad("album.rename", "missing name"))?.to_string();
@@ -337,6 +383,9 @@ pub fn specs() -> Vec<CommandSpec> {
let id = album_param(p, "id", "album.addPhotos")?;
let targets = ids_param(p).unwrap_or_else(|| s.targets(&Value::Null));
let al = s.catalog.album(id).ok_or_else(|| bad("album.addPhotos", "no such album"))?;
+ if al.is_smart() || al.folder {
+ return Err(bad("album.addPhotos", "smart albums and folders can't hold photos"));
+ }
let mut photos = al.photos.clone();
let before = photos.len();
for t in targets {
@@ -353,6 +402,9 @@ pub fn specs() -> Vec<CommandSpec> {
let id = album_param(p, "id", "album.removePhotos")?;
let targets = ids_param(p).unwrap_or_else(|| s.targets(&Value::Null));
let al = s.catalog.album(id).ok_or_else(|| bad("album.removePhotos", "no such album"))?;
+ if al.is_smart() {
+ return Err(bad("album.removePhotos", "smart albums update automatically: change their rules"));
+ }
let photos: Vec<PhotoId> = al.photos.iter().copied().filter(|x| !targets.contains(x)).collect();
s.commit("Remove from Album", Op::SetAlbumPhotos { id, photos })?;
ok()
@@ -452,6 +504,51 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
+/// `base` with a partial Filter (JSON) merged on top.
+fn merge_rules(base: &lightcraft_catalog::Filter, patch: &Value, c: &str) -> Result<lightcraft_catalog::Filter> {
+ let mut v = serde_json::to_value(base).unwrap_or_default();
+ lightcraft_develop::presets::deep_merge(&mut v, patch);
+ serde_json::from_value(v).map_err(|e| bad(c, e.to_string()))
+}
+
+/// The current view (source + filter) as smart-album rules. Viewing a smart album starts from
+/// its rules with the filter bar's settings on top.
+fn view_rules(s: &Session) -> lightcraft_catalog::Filter {
+ use lightcraft_catalog::Filter;
+ let smart = match s.source {
+ LibrarySource::Album(a) => s.catalog.album(a).and_then(|a| a.smart.as_deref().cloned()),
+ _ => None,
+ };
+ match smart {
+ Some(base) => {
+ // overlay the fields the filter bar changed
+ let cur = serde_json::to_value(&s.filter).unwrap_or_default();
+ let def = serde_json::to_value(Filter::default()).unwrap_or_default();
+ let mut patch = serde_json::Map::new();
+ if let (Some(c), Some(d)) = (cur.as_object(), def.as_object()) {
+ for (k, v) in c {
+ if d.get(k) != Some(v) {
+ patch.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ merge_rules(&base, &Value::Object(patch), "").unwrap_or(base)
+ }
+ None => {
+ let mut f = s.source.to_filter(&s.filter, &s.catalog);
+ f.deleted = false;
+ f
+ }
+ }
+}
+
+impl Session {
+ /// The current view (source + filter) as smart-album rules (see `album.createSmart`).
+ pub fn view_rules(&self) -> lightcraft_catalog::Filter {
+ view_rules(self)
+ }
+}
+
fn has_library(s: &Session) -> std::result::Result<(), String> {
if s.library.is_some() { Ok(()) } else { Err("no library is open (in-memory session)".into()) }
}
diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs
index 5348c3519..676773191 100644
--- a/crates/engine/src/cmd/query.rs
+++ b/crates/engine/src/cmd/query.rs
@@ -27,15 +27,21 @@ pub fn photo_summary(p: &Photo) -> Value {
})
}
-fn album_json(a: &Album, all: &[Album]) -> Value {
- json!({
+fn album_json(a: &Album, all: &[Album], cat: &lightcraft_catalog::Catalog) -> Value {
+ let mut v = json!({
"id": a.id.0,
"name": a.name,
"folder": a.folder,
- "count": a.photos.len(),
+ "count": cat.album_count(a.id),
"cover": a.cover.map(|c| c.0),
- "children": all.iter().filter(|c| c.parent == Some(a.id)).map(|c| album_json(c, all)).collect::<Vec<_>>(),
- })
+ "children": all.iter().filter(|c| c.parent == Some(a.id)).map(|c| album_json(c, all, cat)).collect::<Vec<_>>(),
+ });
+ if let Some(rules) = &a.smart {
+ v["smart"] = json!(true);
+ v["rules"] = serde_json::to_value(rules).unwrap_or_default();
+ v["rulesText"] = json!(rules.describe());
+ }
+ v
}
fn photo_arg(s: &Session, p: &Value, c: &str) -> crate::Result<PhotoId> {
@@ -88,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!(query "albums.list", "List Albums", [], None, "{}", always, |s, _| {
let all: Vec<Album> = s.catalog.albums().cloned().collect();
- Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all)).collect()))
+ Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all, &s.catalog)).collect()))
}),
cmd!(query "photo.inspect", "Inspect Photo", [], None, "{id?}", always, |s, p| {
let id = photo_arg(s, p, "photo.inspect")?;
diff --git a/crates/engine/src/demo.rs b/crates/engine/src/demo.rs
index 9c2358f8b..7b4951c75 100644
--- a/crates/engine/src/demo.rs
+++ b/crates/engine/src/demo.rs
@@ -61,7 +61,9 @@ pub fn load(s: &mut Session) {
ops.push(Op::AddPhoto { photo: Box::new(p) });
}
let folder = s.catalog.alloc_album_id();
- ops.push(Op::AddAlbum { album: Album { id: folder, name: "Travel 2026".into(), parent: None, folder: true, photos: vec![], cover: None } });
+ ops.push(Op::AddAlbum {
+ album: Album { id: folder, name: "Travel 2026".into(), parent: None, folder: true, photos: vec![], cover: None, smart: None },
+ });
let by_kw = |kw: &str| -> Vec<_> { scenes.iter().zip(&ids).filter(|(sc, _)| sc.meta.keywords.contains(&kw)).map(|(_, id)| *id).collect() };
for (name, parent, photos) in [
("Mountains", Some(folder), by_kw("mountains")),
@@ -73,7 +75,7 @@ pub fn load(s: &mut Session) {
] {
let id = s.catalog.alloc_album_id();
let cover = photos.first().copied();
- ops.push(Op::AddAlbum { album: Album { id, name: name.into(), parent, folder: false, photos, cover } });
+ ops.push(Op::AddAlbum { album: Album { id, name: name.into(), parent, folder: false, photos, cover, smart: None } });
}
for op in ops {
let _ = s.catalog.apply(op);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 2f971c97e..18b405495 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -285,6 +285,7 @@ impl Session {
&& self.sort.key == lightcraft_catalog::SortKey::CaptureDate
&& let LibrarySource::Album(a) = self.source
&& let Some(al) = self.catalog.album(a)
+ && !al.is_smart()
&& self.filter == Filter::default()
{
let order = al.photos.clone();
@@ -321,4 +322,6 @@ mod tests_import;
#[cfg(test)]
mod tests_library;
#[cfg(test)]
+mod tests_organize;
+#[cfg(test)]
mod tests_xmp;
diff --git a/crates/engine/src/tests_organize.rs b/crates/engine/src/tests_organize.rs
new file mode 100644
index 000000000..b088e718a
--- /dev/null
+++ b/crates/engine/src/tests_organize.rs
@@ -0,0 +1,80 @@
+//! Organizing commands: smart albums, stacks, virtual copies — through `Session::execute`, with
+//! undo and a persistent library (journal replay must reproduce the live state).
+
+use lightcraft_catalog::Flag;
+use serde_json::json;
+
+use crate::{LibrarySource, Session};
+
+fn temp_dir(tag: &str) -> std::path::PathBuf {
+ let d = std::env::temp_dir().join(format!("lc-organize-{tag}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ d
+}
+
+fn open(dir: &std::path::Path) -> Session {
+ let mut s = Session::new();
+ s.open_library(dir, true).unwrap();
+ s
+}
+
+#[test]
+fn smart_album_from_view_updates_live_and_persists() {
+ let dir = temp_dir("smart");
+ let mut s = open(&dir);
+ s.execute("library.filter", &json!({"rating": 4})).unwrap();
+ let want = s.visible_cloned();
+ assert!(!want.is_empty());
+ let r = s.execute("album.createSmart", &json!({"name": "Four plus"})).unwrap();
+ let id = r["id"].as_u64().unwrap();
+ assert_eq!(r["count"].as_u64().unwrap() as usize, want.len());
+ s.execute("library.clearFilter", &json!({})).unwrap();
+ s.execute("library.source", &json!({"kind": "album", "id": id})).unwrap();
+ let mut got = s.visible_cloned();
+ got.sort();
+ let mut w = want.clone();
+ w.sort();
+ assert_eq!(got, w);
+ // live: rating another photo 5 adds it; rating a member 1 removes it
+ let other = s.catalog.photos().find(|p| p.rating < 4 && !p.deleted).unwrap().id;
+ s.execute("photo.rate", &json!({"ids": [other.0], "rating": 5})).unwrap();
+ assert!(s.visible_cloned().contains(&other));
+ s.execute("photo.rate", &json!({"ids": [want[0].0], "rating": 1})).unwrap();
+ assert!(!s.visible_cloned().contains(&want[0]));
+ // manual membership changes are refused
+ assert!(s.execute("album.addPhotos", &json!({"id": id, "ids": [want[0].0]})).is_err());
+ // edit rules (merge), rename; undo the rename
+ s.execute("album.setRules", &json!({"id": id, "rules": {"flag": "pick"}})).unwrap();
+ let rules = s.catalog.album(lightcraft_catalog::AlbumId(id)).unwrap().smart.clone().unwrap();
+ assert_eq!((rules.rating, rules.flag), (4, Some(Flag::Pick)));
+ s.execute("album.rename", &json!({"id": id, "name": "Best picks"})).unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.catalog.album(lightcraft_catalog::AlbumId(id)).unwrap().name, "Four plus");
+ // rules via params: camera + lens + date range
+ let r2 = s
+ .execute("album.createSmart", &json!({"name": "Range", "rules": {"dateFrom": "2000-01-01", "dateTo": "2100", "lens": "", "edited": true}}))
+ .unwrap();
+ let edited = s.catalog.photos().filter(|p| !p.deleted && p.is_edited()).count();
+ assert_eq!(r2["count"].as_u64().unwrap() as usize, edited);
+ let listed = s.execute("albums.list", &json!({})).unwrap();
+ assert!(listed.to_string().contains("\"rulesText\""), "{listed}");
+ let expect = s.catalog.to_snapshot();
+ drop(s); // crash: replay the log
+ let mut s2 = open(&dir);
+ assert_eq!(s2.catalog.to_snapshot(), expect);
+ // deleting the smart album
+ s2.execute("album.delete", &json!({"id": id})).unwrap();
+ assert!(s2.catalog.album(lightcraft_catalog::AlbumId(id)).is_none());
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn smart_album_from_smart_album_view_keeps_its_rules() {
+ let mut s = Session::with_demo();
+ let id = s.execute("album.createSmart", &json!({"name": "Picks", "rules": {"flag": "pick"}})).unwrap()["id"].as_u64().unwrap();
+ s.execute("library.source", &json!({"kind": "album", "id": id})).unwrap();
+ s.execute("library.filter", &json!({"rating": 3})).unwrap();
+ let r = s.view_rules();
+ assert_eq!((r.flag, r.rating, r.album), (Some(Flag::Pick), 3, None));
+ assert_eq!(s.source, LibrarySource::Album(lightcraft_catalog::AlbumId(id)));
+}
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index a8656c6f9..439f15ad4 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -45,6 +45,7 @@ pub enum Icon {
Plus,
Minus,
Album,
+ SmartAlbum,
Folder,
Photos,
Clock,
@@ -302,6 +303,12 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, color: Color32) {
pen.rect(3.0, 5.0, 15.0, 17.0, 1.0);
pen.line(&[(6.0, 2.5), (17.5, 2.5), (17.5, 14.0)]);
}
+ SmartAlbum => {
+ pen.rect(3.0, 5.0, 15.0, 17.0, 1.0);
+ pen.line(&[(6.0, 2.5), (17.5, 2.5), (17.5, 14.0)]);
+ // a small funnel: the album is a saved filter
+ pen.closed(&[(5.5, 8.5), (12.5, 8.5), (10.0, 11.5), (10.0, 14.5), (8.0, 13.5), (8.0, 11.5)]);
+ }
Folder => pen.closed(&[(2.5, 5.0), (8.0, 5.0), (9.5, 7.0), (17.5, 7.0), (17.5, 15.5), (2.5, 15.5)]),
Photos => {
pen.rect(2.5, 4.0, 17.5, 16.0, 1.5);
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 1dd7101f5..6916f80f7 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -52,6 +52,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[
("tool.wbPicker", "White Balance Selector", Some("W"), "View"),
("tool.none", "No Tool", None, "View"),
("dialog.newAlbum", "New Album…", Some("Cmd+N"), "File"),
+ ("dialog.newSmartAlbum", "New Smart Album from Filter…", Some("Cmd+Alt+N"), "File"),
("dialog.createPreset", "Create Preset…", Some("Cmd+Shift+P"), "Photo"),
("dialog.copySettings", "Choose Edit Settings to Copy…", Some("Cmd+Shift+C"), "Photo"),
("dialog.export", "Export…", Some("Cmd+Shift+E"), "File"),
@@ -266,6 +267,10 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re
app.ui.dialog = Some(Dialog::NewAlbum { name: p.get("name").and_then(Value::as_str).unwrap_or("").into(), folder: false });
Ok(Value::Null)
}
+ "dialog.newSmartAlbum" => {
+ app.ui.dialog = Some(Dialog::NewSmartAlbum { name: p.get("name").and_then(Value::as_str).unwrap_or("").into() });
+ Ok(Value::Null)
+ }
"dialog.createPreset" => {
app.ui.dialog = Some(Dialog::CreatePreset { name: String::new(), group: "User Presets".into() });
Ok(Value::Null)
diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs
index 0269aad2c..340556a59 100644
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@ -22,6 +22,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {
Dialog::NewAlbum { folder: true, .. } => "Create Folder",
Dialog::NewAlbum { .. } => "Create Album",
Dialog::RenameAlbum { .. } => "Rename Album",
+ Dialog::NewSmartAlbum { .. } => "Create Smart Album",
Dialog::CreatePreset { .. } => "Create Preset",
Dialog::CopySettings { .. } => "Choose Edit Settings to Copy",
Dialog::Export { .. } => "Export",
@@ -38,6 +39,20 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {
.show(ctx, |ui| {
ui.spacing_mut().item_spacing.y = 8.0;
match &mut dlg {
+ Dialog::NewSmartAlbum { name } => {
+ let r = ui.add(egui::TextEdit::singleline(name).hint_text("Name").desired_width(f32::INFINITY));
+ r.request_focus();
+ if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
+ confirm = true;
+ }
+ let rules = app.session.view_rules();
+ let n = app.session.catalog.query(&rules, &Default::default()).len();
+ ui.label(egui::RichText::new(format!("Matches: {}", rules.describe())).color(t.text_label));
+ ui.label(
+ egui::RichText::new(format!("{n} photo{} now · updates automatically as photos change", if n == 1 { "" } else { "s" }))
+ .color(t.text_dim),
+ );
+ }
Dialog::NewAlbum { name, .. } | Dialog::RenameAlbum { name, .. } => {
let r = ui.add(egui::TextEdit::singleline(name).hint_text("Name").desired_width(f32::INFINITY));
r.request_focus();
@@ -217,6 +232,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_jso
match dlg {
Dialog::NewAlbum { name, folder } => app.run("album.create", json!({"name": name, "folder": folder, "addSelected": !folder})),
Dialog::RenameAlbum { id, name } => app.run("album.rename", json!({"id": id, "name": name})),
+ Dialog::NewSmartAlbum { name } => app.run("album.createSmart", json!({"name": if name.trim().is_empty() { "Smart Album" } else { name }})),
Dialog::CreatePreset { name, group } => {
app.run("preset.create", json!({"name": if name.is_empty() { "My Preset" } else { name }, "group": group}))
}
diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs
index 6312c0cbd..dc8b83daf 100644
--- a/crates/ui-egui/src/panels/grid.rs
+++ b/crates/ui-egui/src/panels/grid.rs
@@ -239,7 +239,7 @@ pub fn context_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
}
});
ui.menu_button("Add to Album", |ui| {
- let albums: Vec<_> = app.session.catalog.albums().filter(|a| !a.folder).map(|a| (a.id.0, a.name.clone())).collect();
+ let albums: Vec<_> = app.session.catalog.albums().filter(|a| !a.folder && !a.is_smart()).map(|a| (a.id.0, a.name.clone())).collect();
for (aid, name) in albums {
if ui.button(name).clicked() {
let _ = app.run("album.addPhotos", json!({"id": aid}));
diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs
index 3a4bc4950..48ecc1754 100644
--- a/crates/ui-egui/src/panels/left.rs
+++ b/crates/ui-egui/src/panels/left.rs
@@ -88,6 +88,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {
if ui.button("Create Album…").clicked() {
app.ui.dialog = Some(crate::state::Dialog::NewAlbum { name: String::new(), folder: false });
}
+ if ui.button("Create Smart Album from Filter…").clicked() {
+ app.ui.dialog = Some(crate::state::Dialog::NewSmartAlbum { name: String::new() });
+ }
if ui.button("Create Folder…").clicked() {
app.ui.dialog = Some(crate::state::Dialog::NewAlbum { name: String::new(), folder: true });
}
@@ -132,7 +135,12 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &[Album], parent
}
} else {
let sel = app.session.source == LibrarySource::Album(a.id);
- let resp = row(app, ui, &format!("album:{}", a.id.0), Icon::Album, &a.name, Some(a.photos.len()), sel, indent);
+ let icon = if a.is_smart() { Icon::SmartAlbum } else { Icon::Album };
+ let n = app.session.catalog.album_count(a.id);
+ let mut resp = row(app, ui, &format!("album:{}", a.id.0), icon, &a.name, Some(n), sel, indent);
+ if let Some(rules) = &a.smart {
+ resp = resp.on_hover_text(format!("Smart album: {}", rules.describe()));
+ }
if resp.clicked() {
let _ = app.run("library.source", json!({"kind": "album", "id": a.id.0}));
}
@@ -143,9 +151,12 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &[Album], parent
fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) {
resp.context_menu(|ui| {
- if !a.folder && ui.button("Add Selected Photos").clicked() {
+ if !a.folder && !a.is_smart() && ui.button("Add Selected Photos").clicked() {
let _ = app.run("album.addPhotos", json!({"id": a.id.0}));
}
+ if a.is_smart() && ui.button("Update Rules from Current Filter").clicked() {
+ let _ = app.run("album.setRules", json!({"id": a.id.0, "fromView": true}));
+ }
if ui.button("Rename…").clicked() {
app.ui.dialog = Some(crate::state::Dialog::RenameAlbum { id: a.id.0, name: a.name.clone() });
}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 34b3b15a7..8e3dfc4ee 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -127,6 +127,10 @@ pub enum Dialog {
id: u64,
name: String,
},
+ /// Save the current view (source + filter) as a smart album.
+ NewSmartAlbum {
+ name: String,
+ },
CreatePreset {
name: String,
group: String,