diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a6972..c9ca7af1cba 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -486,16 +486,18 @@ impl Catalog { out } - /// A loop through `filter`'s own album field (not its rules): smart album `owner` filtered to - /// itself, or to an album that leads back to it. + /// What is wrong with `filter`'s own album field (not its rules): it names an album that is + /// gone (a view of an album, saved as a smart album, after that album was deleted), or, for + /// smart album `owner`, itself or an album that leads back to it. pub fn album_filter_problem(&self, filter: &Filter, owner: Option) -> Option { - let (a, owner) = (filter.album?, owner?); - (a == owner || self.album_reaches(a, owner)).then(|| rules::Problem { - path: Vec::new(), - field: Some("album".into()), - issue: rules::Issue::AlbumLoop, - message: format!("its album filter (album {}) would make this album include itself", a.0), - }) + let a = filter.album?; + let problem = |issue, message| rules::Problem { path: Vec::new(), field: Some("album".into()), issue, message }; + if !self.albums.contains_key(&a) { + return Some(problem(rules::Issue::NoSuchAlbum, format!("its album filter names album {}, which is gone", a.0))); + } + let owner = owner?; + (a == owner || self.album_reaches(a, owner)) + .then(|| problem(rules::Issue::AlbumLoop, format!("its album filter (album {}) would make this album include itself", a.0))) } /// The photos of an album: the stored list, or a smart album's current matches (id order). diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 9b8dc3dbd28..44c28a664af 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -105,8 +105,14 @@ pub fn always(_: &Session) -> std::result::Result<(), String> { pub fn has_active(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no photo selected".into()) } +/// A selection of photos that are there: one whose photos an undo took away (they stay selected +/// for the redo) is none, as [`Session::targets`] would be empty. What counts is what a command acts on +/// ([`Session::selected`]): the active photo only stands in when nothing else is selected. pub fn has_selection(s: &Session) -> std::result::Result<(), String> { - if s.selection.ids.is_empty() && s.selection.active.is_none() { Err("no photos selected".into()) } else { Ok(()) } + // (the rule of `Session::selected`, without making its list: this is asked for every command, every frame) + let there = |id: &lightcraft_catalog::PhotoId| s.catalog.photo(*id).is_some(); + let any = if s.selection.ids.is_empty() { s.selection.active.iter().any(there) } else { s.selection.ids.iter().any(there) }; + if any { Ok(()) } else { Err("no photos selected".into()) } } /// Albums hold library photos: a selection of only browsed (Local) photos has nothing an album /// can take (issue #684; Add to My Photos first). diff --git a/crates/engine/src/cmd/library/filters.rs b/crates/engine/src/cmd/library/filters.rs index 1eaa5223f62..16bed71fd40 100644 --- a/crates/engine/src/cmd/library/filters.rs +++ b/crates/engine/src/cmd/library/filters.rs @@ -56,7 +56,7 @@ pub(super) fn view_rules(s: &Session) -> lightcraft_catalog::Filter { LibrarySource::Album(a) => s.catalog.album(a).and_then(|a| a.smart.as_deref().cloned()), _ => None, }; - match smart { + let mut rules = match smart { Some(base) => { // overlay the fields the filter bar changed let cur = serde_json::to_value(&s.filter).unwrap_or_default(); @@ -81,7 +81,12 @@ pub(super) fn view_rules(s: &Session) -> lightcraft_catalog::Filter { } f } + }; + // a view of a smart album limited to an album that is gone is saved without that limit + if rules.album.is_some_and(|a| s.catalog.album(a).is_none()) { + rules.album = None; } + rules } impl Session { diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 07ab6f221c6..48e373f1031 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -106,6 +106,11 @@ pub fn specs() -> Vec { if let Some(problems) = f.rule_set.as_ref().filter(|_| sets_rules).map(|rs| rs.check(&s.catalog)).filter(|p| !p.is_empty()) { return Err(bad("library.filter", problems.iter().map(ToString::to_string).collect::>().join("; "))); } + // an album this call names is one the library has (one named before and since + // deleted is let go of, `Session::reconcile_view`) + if p.get("album").is_some_and(|a| !a.is_null()) && f.album.is_some_and(|a| s.catalog.album(a).is_none()) { + return Err(bad("library.filter", "no such album")); + } s.filter = f; s.shelved_filter = None; Ok(json!({"count": s.visible().len()})) @@ -874,7 +879,7 @@ pub fn specs() -> Vec { view } else { let replace = bool_or(p, "replace", false); - let folder = cur.library_folder.clone(); + let (folder, album) = (cur.library_folder.clone(), cur.album); let base = if replace { Default::default() } else { cur }; let mut r = merge_rules(&base, p.get("rules").unwrap_or(&Value::Null), "album.setRules", &s.catalog, Some(id))?; // the rules dialog has no folder field: replacing its rules keeps the folder @@ -882,6 +887,12 @@ pub fn specs() -> Vec { if replace && p.get("rules").and_then(|r| r.get("libraryFolder")).is_none() { r.library_folder = folder; } + // nor one for the album a saved view is limited to + // (`album: null` drops it). One that is gone is let go of: this is where + // the mark on such an album sends the person + if replace && p.get("rules").and_then(|r| r.get("album")).is_none() { + r.album = album.filter(|a| s.catalog.album(*a).is_some()); + } r }; let set = Op::SetAlbumRules { id, rules: Box::new(rules) }; @@ -932,10 +943,9 @@ pub fn specs() -> Vec { } } let ops = order.into_iter().rev().map(|id| Op::RemoveAlbum { id }).collect(); + // a deleted album that was being shown gives way to All Photos, as after any + // other way it goes (`Session::reconcile_view`) s.commit(if folder { "Delete Folder" } else { "Delete Album" }, Op::Batch { ops })?; - if matches!(s.source, LibrarySource::Album(current) if removed.contains(¤t)) { - s.source = LibrarySource::All; - } ok() } ), @@ -1028,12 +1038,19 @@ pub fn specs() -> Vec { has_library_selection, |s, p| { let id = album_param(p, "id", "album.addPhotos")?; - let targets = crate::cmd::photo_ids(p, "album.addPhotos")?.unwrap_or_else(|| s.selected()); + // photos that are there: an album doesn't list one that is gone (a selection + // dragged here after an undo took one of its photos away) + let mut targets = crate::cmd::photo_ids(p, "album.addPhotos")?.unwrap_or_else(|| s.selected()); + targets.retain(|t| s.catalog.photo(*t).is_some()); 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 (targets, skipped) = album_targets_or_err(s, "album.addPhotos", targets)?; + // nothing left to add: the album is unchanged, so no undo step + if targets.is_empty() { + return Ok(json!({"added": 0, "skipped": skipped})); + } let mut photos = al.photos.clone(); let before = photos.len(); // looked up, not searched for: adding thousands to a big album stays linear diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index acaa1807009..8481120c49e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -605,6 +605,10 @@ impl Session { self.auto_write_sidecars_since(log_start); } } + if self.depth == 0 { + // whatever the command changed, and however it ended: the view points at what is there + self.reconcile_view(); + } if self.depth == 0 && self.library.is_some() { // Make the command durable before reporting success. When the command's own records // can't be appended, it fails with `NotSaved`: the change stays applied in memory and @@ -780,6 +784,7 @@ impl Session { } }; self.show_undone(&e.op); + self.reconcile_view(); self.pending_log.push(e.op); self.redo.push(UndoEntry { label: e.label.clone(), @@ -805,6 +810,7 @@ impl Session { } }; self.show_undone(&e.op); + self.reconcile_view(); self.pending_log.push(e.op); self.undo.push(UndoEntry { label: e.label.clone(), @@ -1063,8 +1069,32 @@ impl Session { self.shelved_filter.is_some() } + /// Makes the view show only albums the library holds: one that is gone is no longer the + /// source (All Photos is) or the filter's album. THE place this is checked: commands, undo + /// and redo, opening a library and every look at the grid run it, so whatever removed an + /// album (a command, an undo, a background task) or named one (a saved filter, a saved view) + /// need not know. Two lookups: it runs every time. + /// + /// An album that comes back (its deletion undone) is not shown again by itself, as after + /// `album.delete` and undo before: the grid stays where the person was put. + /// + /// What is only looked up when it is used is left as it is, and so comes back with an undo: + /// the target album (a missing one means the Quick Collection) and the selection (`active` + /// and `targets` leave out photos that are gone). + pub fn reconcile_view(&mut self) { + let cat = &self.catalog; + let gone = |a: &lightcraft_catalog::AlbumId| cat.album(*a).is_none(); + if matches!(&self.source, LibrarySource::Album(a) if gone(a)) { + self.source = LibrarySource::All; + } + if self.filter.album.as_ref().is_some_and(gone) { + self.filter.album = None; + } + } + /// Photos shown in the grid/filmstrip for the current source, filter and sort. pub fn visible(&mut self) -> &[PhotoId] { + self.reconcile_view(); let mut key = (self.catalog.revision, format!("{:?}|{:?}|{:?}|{:?}|{:?}", self.source, self.filter, self.sort, self.browse, self.library_folder)); // What a held view is told apart by: what is shown and how, and for a smart album its rules (rules that were @@ -1252,6 +1282,7 @@ impl Session { /// Photos in the current source (folder, album, …) before the filter bar and search narrow /// them; `None` where that is not a separate number (Missing Photos). pub fn source_total(&mut self) -> Option { + self.reconcile_view(); if self.source == LibrarySource::Missing { return None; } @@ -1336,8 +1367,15 @@ impl Session { } /// The photos commands act on when a call names none: the selection, else the active photo. + /// As far as its photos are there: one taken away by undo stays selected for the redo, and is + /// acted on by nothing meanwhile. pub fn selected(&self) -> Vec { - if self.selection.ids.is_empty() { self.selection.active.into_iter().collect() } else { self.selection.ids.clone() } + let there = |id: &PhotoId| self.catalog.photo(*id).is_some(); + if self.selection.ids.is_empty() { + self.selection.active.into_iter().filter(there).collect() + } else { + self.selection.ids.iter().copied().filter(there).collect() + } } } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index a5071b4b358..93543e86d7e 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -488,6 +488,15 @@ impl Session { self.selection = Selection::default(); self.source = LibrarySource::All; self.library_folder = None; + // what names albums and photos by number means others in another library: no filter + // (as after a restart; the view file keeps none), no target album, no photo come from + self.filter = Default::default(); + self.shelved_filter = None; + self.target_album = None; + self.previous_active = None; + self.active_mask = None; + self.active_spot = None; + self.before.clear(); if report.created && seed_demo { crate::demo::load(self); journal.snapshot(&self.catalog)?; @@ -558,6 +567,8 @@ impl Session { self.selection.ids.retain(|id| self.catalog.photo(*id).is_some()); self.selection.active = self.selection.active.filter(|id| self.catalog.photo(*id).is_some()); } + // the saved view may name an album the library no longer has + self.reconcile_view(); // not on Missing Photos: working that view out checks every original (minutes on a // sleeping NAS), and the app checks them in the background once it runs if self.selection.active.is_none() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae03859d21f..8532bafefda 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -47,6 +47,7 @@ mod slideshow_export; mod spots; mod sync; mod view_follow; +mod view_reconcile; pub(super) mod xmp; fn demo() -> Session { diff --git a/crates/engine/src/tests/view_reconcile.rs b/crates/engine/src/tests/view_reconcile.rs new file mode 100644 index 00000000000..9534e4d2028 --- /dev/null +++ b/crates/engine/src/tests/view_reconcile.rs @@ -0,0 +1,504 @@ +//! The view never points at an album that is gone. What the session shows and acts on (the +//! source, the album a filter names, the target album) refers to albums of the library; whenever +//! the library or the view may have changed, by whatever way, those references are checked in +//! one place (`Session::reconcile_view`). +//! +//! Scenarios: +//! - Given an album or a smart album being shown, when it goes away (deleted, its +//! creation undone, its deletion redone, the folder around it deleted, or removed by an edit +//! that is no command), then the grid shows All Photos, titled so. +//! - Given an album that went away and came back (its deletion undone), then it is not shown +//! again by itself, nor the filter's album again; it is the target again, as it was (the target +//! is looked up where it is used, so nothing had to forget it). +//! - Given a library closed while showing an album that is gone when it is opened again, then +//! it opens on All Photos. +//! - Given the filter names an album, when that album goes away, then the filter no longer names +//! it; a saved filter that names an album since deleted applies without it; a filter can't be +//! set to an album that doesn't exist, and such a call changes nothing else either. +//! - Given an album is the target, when it goes away, then photos go to the Quick Collection. +//! - Given photos are selected, when some go away by undo, then commands act on the ones that +//! are left and write the others nowhere; when they come back by redo, they are selected as +//! before (the selection is looked up where it is read, not pruned). +//! - Given another library is opened, then the filter's album and the target, which named albums +//! of the library before, name nothing: the same number is another album there. +//! - Given a smart album saved from the view of an album, when that album is deleted, +//! then the smart album says so (it is marked, as for a rule naming a deleted album) instead of +//! being quietly empty; and a smart album can't be limited to an album that doesn't exist. +//! Pressing OK in its rules dialog, or updating its rules from the current view, lets go of the +//! album that is gone and the mark with it; a new smart album saved from its view isn't born +//! with the mark. +//! - Given every selected photo is gone, then commands on the selection are not available (and +//! so record nothing and leave redo alone); photos named outright that aren't there are not +//! written into an album. +//! - Given the shown album is only changed (renamed, moved, emptied), then it is still shown. + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::{LibrarySource, Session}; + +fn photos(s: &mut Session, n: u64) { + for day in 1..=n { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::Demo { scene: 1 }, &format!("p{day}.jpg"), "JPEG", 60, 40, "2026-02-01T10:00:00"); + p.captured = Some(format!("2026-01-{day:02}T10:00:00")); + s.commit("Add Photo", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } +} + +fn run(s: &mut Session, cmd: &str, params: Value) -> Value { + s.execute(cmd, ¶ms).unwrap() +} + +fn show(s: &mut Session, id: u64) { + run(s, "library.source", json!({"kind": "album", "id": id})); + assert_eq!(s.source, LibrarySource::Album(AlbumId(id))); +} + +fn shows_all(s: &mut Session, why: &str) { + assert_eq!(s.source, LibrarySource::All, "{why}"); + assert_eq!(s.source.label(&s.catalog), "All Photos", "{why}"); + assert_eq!(s.visible_cloned().len(), 3, "{why}"); +} + +/// What can be shown: an album, a smart album. +fn kinds() -> [(&'static str, &'static str, Value); 2] { + [("album", "album.create", json!({"name": "Shown"})), ("smart album", "album.createSmart", json!({"name": "Shown", "rules": {"rating": 3}}))] +} + +#[test] +fn a_shown_album_that_goes_away_gives_way_to_all_photos() { + for (kind, create, params) in kinds() { + // deleted + let mut s = Session::new(); + photos(&mut s, 3); + let id = run(&mut s, create, params.clone())["id"].as_u64().unwrap(); + show(&mut s, id); + run(&mut s, "album.delete", json!({"id": id})); + shows_all(&mut s, &format!("{kind} deleted")); + // back by undo: not shown again by itself, and its deletion redone while shown + run(&mut s, "edit.undo", json!({})); + shows_all(&mut s, &format!("{kind} back by undo")); + show(&mut s, id); + run(&mut s, "edit.redo", json!({})); + shows_all(&mut s, &format!("{kind}'s deletion redone")); + + // its creation undone + let mut s = Session::new(); + photos(&mut s, 3); + let id = run(&mut s, create, params.clone())["id"].as_u64().unwrap(); + show(&mut s, id); + run(&mut s, "edit.undo", json!({})); + assert!(s.catalog.album(AlbumId(id)).is_none()); + shows_all(&mut s, &format!("{kind}'s creation undone")); + + // removed by an edit that is no command (a background task, a merge): seen by the next look + let mut s = Session::new(); + photos(&mut s, 3); + let id = run(&mut s, create, params.clone())["id"].as_u64().unwrap(); + show(&mut s, id); + s.commit("Remove", Op::RemoveAlbum { id: AlbumId(id) }).unwrap(); + assert_eq!(s.visible_cloned().len(), 3, "{kind} removed outside a command"); + shows_all(&mut s, &format!("{kind} removed outside a command")); + } +} + +#[test] +fn deleting_the_folder_around_the_shown_album_gives_way_too() { + let mut s = Session::new(); + photos(&mut s, 3); + let folder = run(&mut s, "album.create", json!({"name": "Trips", "folder": true}))["id"].as_u64().unwrap(); + let inner = run(&mut s, "album.create", json!({"name": "Rome", "parent": folder}))["id"].as_u64().unwrap(); + show(&mut s, inner); + run(&mut s, "album.delete", json!({"id": folder})); + shows_all(&mut s, "the folder around it deleted"); +} + +#[test] +fn an_album_that_comes_back_is_not_shown_again_by_itself() { + let mut s = Session::new(); + photos(&mut s, 3); + let id = run(&mut s, "album.create", json!({"name": "First"}))["id"].as_u64().unwrap(); + show(&mut s, id); + run(&mut s, "library.filter", json!({"album": id})); + // the filter is no undo step: this undoes the album + run(&mut s, "edit.undo", json!({})); + assert!(s.catalog.album(AlbumId(id)).is_none(), "the album's creation was undone"); + assert_eq!((s.source, s.filter.album), (LibrarySource::All, None)); + run(&mut s, "edit.redo", json!({})); + assert!(s.catalog.album(AlbumId(id)).is_some(), "and redone"); + shows_all(&mut s, "the album came back"); + assert_eq!(s.filter.album, None); + // nor does the next album made take its place + run(&mut s, "edit.undo", json!({})); + let second = run(&mut s, "album.create", json!({"name": "Second"}))["id"].as_u64().unwrap(); + assert_ne!(second, id, "ids are not handed out again"); + shows_all(&mut s, "another album was made"); +} + +/// The target album is looked up where it is used: gone, photos go to the Quick Collection; back +/// by undo, it is the target again. +#[test] +fn the_target_album_follows_the_album() { + let mut s = Session::new(); + photos(&mut s, 3); + let id = run(&mut s, "album.create", json!({"name": "Target"}))["id"].as_u64().unwrap(); + run(&mut s, "album.setTarget", json!({"id": id})); + run(&mut s, "album.delete", json!({"id": id})); + s.selection.ids = vec![PhotoId(1)]; + let r = run(&mut s, "album.toggleTarget", json!({})); + assert_ne!(r["album"].as_u64(), Some(id)); + assert_eq!(s.catalog.quick_collection().map(|a| a.0), r["album"].as_u64(), "the Quick Collection took it"); + // undone as far as the deletion: the album is back, and is the target again + for _ in 0..5 { + if s.catalog.album(AlbumId(id)).is_none() { + run(&mut s, "edit.undo", json!({})); + } + } + assert!(s.catalog.album(AlbumId(id)).is_some()); + s.selection.ids = vec![PhotoId(2)]; + assert_eq!(run(&mut s, "album.toggleTarget", json!({}))["album"].as_u64(), Some(id)); +} + +#[test] +fn a_filter_lets_go_of_an_album_that_went_away() { + let mut s = Session::new(); + photos(&mut s, 3); + let id = run(&mut s, "album.create", json!({"name": "Named"}))["id"].as_u64().unwrap(); + let other = run(&mut s, "album.create", json!({"name": "Other"}))["id"].as_u64().unwrap(); + run(&mut s, "library.filter", json!({"album": id, "rating": 0})); + assert_eq!(s.filter.album, Some(AlbumId(id))); + // another album going away changes nothing + run(&mut s, "album.delete", json!({"id": other})); + assert_eq!(s.filter.album, Some(AlbumId(id))); + run(&mut s, "album.delete", json!({"id": id})); + assert_eq!(s.filter.album, None); + assert_eq!(s.visible_cloned().len(), 3, "the filter hides nothing behind an album that is gone"); + // the step functions themselves check, not only the commands round them + s.undo_step().unwrap(); + run(&mut s, "library.filter", json!({"album": id})); + s.redo_step().unwrap(); + assert_eq!(s.filter.album, None); +} + +/// The view can come to name a missing album with the library unchanged: a saved filter applied +/// after its album was deleted. And a filter is not set to an album that isn't there. +#[test] +fn a_filter_naming_a_missing_album_is_not_taken_up() { + let mut s = Session::new(); + photos(&mut s, 3); + let id = run(&mut s, "album.create", json!({"name": "Named"}))["id"].as_u64().unwrap(); + s.filter_presets.push(crate::cmd::filters::FilterPreset { + name: "In Named".into(), + filter: lightcraft_catalog::Filter { album: Some(AlbumId(id)), rating: 0, ..Default::default() }, + }); + run(&mut s, "album.delete", json!({"id": id})); + // nothing changes in the library from here on + let r = run(&mut s, "filter.applyPreset", json!({"name": "In Named"})); + assert_eq!((s.filter.album, r["photos"].as_u64()), (None, Some(3)), "applied without the album that is gone"); + let e = s.execute("library.filter", &json!({"album": 77, "rating": 4})).unwrap_err().to_string(); + assert!(e.contains("no such album"), "{e}"); + assert_eq!((s.filter.album, s.filter.rating), (None, 0), "nothing of the call was taken up"); + assert_eq!(s.source_total(), Some(3)); + // an album that is there can be named, and cleared + let kept = run(&mut s, "album.create", json!({"name": "Kept"}))["id"].as_u64().unwrap(); + run(&mut s, "library.filter", json!({"album": kept})); + assert_eq!(s.filter.album, Some(AlbumId(kept))); + run(&mut s, "library.filter", json!({"album": null})); + assert_eq!(s.filter.album, None); +} + +/// The counted total is a look at the grid too. +#[test] +fn the_total_is_of_what_is_there() { + let mut s = Session::new(); + photos(&mut s, 3); + let id = run(&mut s, "album.create", json!({"name": "Shown"}))["id"].as_u64().unwrap(); + show(&mut s, id); + assert_eq!(s.source_total(), Some(0)); + s.commit("Remove", Op::RemoveAlbum { id: AlbumId(id) }).unwrap(); + assert_eq!(s.source_total(), Some(3)); + assert_eq!(s.source, LibrarySource::All); +} + +/// Undo takes a selected photo away: commands on the selection act on the photos that are left, +/// and the one that is gone is written nowhere. +#[test] +fn a_selected_photo_that_is_gone_is_acted_on_nowhere() { + let mut s = Session::new(); + photos(&mut s, 2); + let album = run(&mut s, "album.create", json!({"name": "Kept"}))["id"].as_u64().unwrap(); + let late = s.catalog.alloc_photo_id(); + let p = Photo::new(late, Source::Demo { scene: 1 }, "late.jpg", "JPEG", 60, 40, "2026-02-01T10:00:00"); + s.commit("Add Photo", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + s.selection.ids = vec![PhotoId(1), late]; + s.selection.active = Some(late); + run(&mut s, "edit.undo", json!({})); + assert!(s.catalog.photo(late).is_none()); + assert_eq!(s.active(), None, "no photo to act on alone"); + assert_eq!(s.targets(&json!({})).unwrap(), [PhotoId(1)], "the selection, as far as it is there"); + assert_eq!(run(&mut s, "album.addPhotos", json!({"id": album}))["added"], 1); + assert_eq!(s.catalog.album(AlbumId(album)).unwrap().photos, [PhotoId(1)]); + run(&mut s, "photo.rate", json!({"rating": 3})); + assert_eq!(s.catalog.photo(PhotoId(1)).unwrap().rating, 3, "the photo that is left is rated"); + // ids a call names itself are the caller's to get right + assert!(s.execute("photo.rate", &json!({"ids": [late.0], "rating": 1})).is_err()); +} + +/// Redo brings a selected photo back selected and active as before. +#[test] +fn photos_that_go_and_come_back_are_selected_as_before() { + let mut s = Session::new(); + photos(&mut s, 3); + s.selection.ids = vec![PhotoId(1), PhotoId(3)]; + s.selection.active = Some(PhotoId(3)); + run(&mut s, "edit.undo", json!({})); + assert!(s.catalog.photo(PhotoId(3)).is_none()); + run(&mut s, "edit.redo", json!({})); + assert_eq!((s.selection.ids.clone(), s.active()), (vec![PhotoId(1), PhotoId(3)], Some(PhotoId(3)))); +} + +/// Another library's albums have the same numbers: what named an album here names nothing there. +#[test] +fn another_library_starts_without_this_ones_album_filter_and_target() { + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let dirs = ["a", "b"].map(|n| Scratch(std::env::temp_dir().join(format!("lc-view-reconcile-switch-{n}-{}", std::process::id())))); + for d in &dirs { + let _ = std::fs::remove_dir_all(&d.0); + } + // library B has an album 1 of its own + let mut s = Session::new(); + s.open_library(&dirs[1].0, false).unwrap(); + photos(&mut s, 3); + let theirs = run(&mut s, "album.create", json!({"name": "B's album"}))["id"].as_u64().unwrap(); + drop(s); + let mut s = Session::new(); + s.open_library(&dirs[0].0, false).unwrap(); + photos(&mut s, 3); + let ours = run(&mut s, "album.create", json!({"name": "A's album"}))["id"].as_u64().unwrap(); + assert_eq!(ours, theirs, "the same number in both libraries"); + run(&mut s, "album.setTarget", json!({"id": ours})); + run(&mut s, "library.filter", json!({"album": ours, "rating": 0})); + // and what else names this library's albums and photos by number + run(&mut s, "library.filter", json!({"ruleSet": {"match": "all", "rules": [{"field": "album", "op": "is", "value": ours}]}})); + s.filter.only = vec![PhotoId(2)]; + s.previous_active = Some(PhotoId(3)); + s.active_mask = Some(1); + // a filter put aside by Enable Filters names this library's albums too + s.shelved_filter = Some(s.filter.clone()); + s.open_library(&dirs[1].0, false).unwrap(); + assert_eq!(s.catalog.album(AlbumId(theirs)).unwrap().name, "B's album"); + assert_eq!(s.target_album, None); + assert_eq!(s.filter, lightcraft_catalog::Filter::default(), "no filter left over, as after a restart"); + assert!(!s.filters_off(), "and none put aside to come back with Enable Filters"); + assert_eq!((s.previous_active, s.active_mask), (None, None)); + assert_eq!(s.visible_cloned().len(), 3); +} + +#[test] +fn a_smart_album_says_when_the_album_it_shows_is_gone() { + let mut s = Session::new(); + photos(&mut s, 3); + let rome = run(&mut s, "album.create", json!({"name": "Rome"}))["id"].as_u64().unwrap(); + s.selection.ids = vec![PhotoId(1), PhotoId(2)]; + run(&mut s, "album.addPhotos", json!({"id": rome, "ids": [1, 2]})); + show(&mut s, rome); + let saved = run(&mut s, "album.createSmart", json!({"name": "Rome view"})); + assert_eq!(saved["count"], 2); + let saved = AlbumId(saved["id"].as_u64().unwrap()); + assert!(s.catalog.smart_album_problems(saved).is_empty()); + run(&mut s, "album.delete", json!({"id": rome})); + assert_eq!(s.catalog.album_count(saved), 0); + let problems = s.catalog.smart_album_problems(saved); + assert!(problems.iter().any(|p| p.issue == lightcraft_catalog::rules::Issue::NoSuchAlbum), "{problems:?}"); + // back with the album + run(&mut s, "edit.undo", json!({})); + assert!(s.catalog.smart_album_problems(saved).is_empty()); + assert_eq!(s.catalog.album_count(saved), 2); + // and none is made that way + let e = s.execute("album.createSmart", &json!({"name": "Of nothing", "rules": {"album": 999}})).unwrap_err().to_string(); + assert!(e.contains("999"), "{e}"); +} + +/// The mark can be cleared where it sends the person: the rules dialog's OK (which replaces the +/// rules and keeps the album a view was saved from) keeps only an album that is still there, and +/// so does Update Rules from Current Filter. Other settings stay editable without clearing it. +#[test] +fn a_smart_album_lets_go_of_a_missing_album_when_its_rules_are_saved() { + let saved_view_of_a_deleted_album = |s: &mut Session| -> AlbumId { + let rome = run(s, "album.create", json!({"name": "Rome"}))["id"].as_u64().unwrap(); + show(s, rome); + let saved = AlbumId(run(s, "album.createSmart", json!({"name": "Rome view"}))["id"].as_u64().unwrap()); + run(s, "album.delete", json!({"id": rome})); + assert_eq!(s.catalog.smart_album_problems(saved).len(), 1); + saved + }; + let limit = |s: &Session, a: AlbumId| s.catalog.album(a).unwrap().smart.as_ref().unwrap().album; + + // the dialog's OK + let mut s = Session::new(); + photos(&mut s, 3); + let saved = saved_view_of_a_deleted_album(&mut s); + // a patch that sets something else leaves the rest, the mark included + run(&mut s, "album.setRules", json!({"id": saved.0, "rules": {"rating": 0}})); + assert!(limit(&s, saved).is_some() && !s.catalog.smart_album_problems(saved).is_empty()); + let r = run(&mut s, "album.setRules", json!({"id": saved.0, "replace": true, "rules": {"ruleSet": {"match": "all", "rules": []}}})); + assert_eq!(limit(&s, saved), None); + assert!(s.catalog.smart_album_problems(saved).is_empty()); + assert_eq!(r["count"], 3, "what the dialog showed would match: its rules, without the album that is gone"); + + // Update Rules from Current Filter, while it is shown + let mut s = Session::new(); + photos(&mut s, 3); + let saved = saved_view_of_a_deleted_album(&mut s); + show(&mut s, saved.0); + run(&mut s, "album.setRules", json!({"id": saved.0, "fromView": true})); + assert!(s.catalog.smart_album_problems(saved).is_empty()); + + // a new smart album from its view isn't born with the mark + let mut s = Session::new(); + photos(&mut s, 3); + let saved = saved_view_of_a_deleted_album(&mut s); + show(&mut s, saved.0); + let again = AlbumId(run(&mut s, "album.createSmart", json!({"name": "Again"}))["id"].as_u64().unwrap()); + assert!(s.catalog.smart_album_problems(again).is_empty()); + + // an album that is still there is kept by the dialog's OK, as before + let mut s = Session::new(); + photos(&mut s, 3); + let rome = run(&mut s, "album.create", json!({"name": "Rome"}))["id"].as_u64().unwrap(); + show(&mut s, rome); + let kept = AlbumId(run(&mut s, "album.createSmart", json!({"name": "Rome view"}))["id"].as_u64().unwrap()); + run(&mut s, "album.setRules", json!({"id": kept.0, "replace": true, "rules": {"ruleSet": {"match": "all", "rules": []}}})); + assert_eq!(limit(&s, kept), Some(AlbumId(rome))); +} + +/// Undo took away the only selected photo: nothing on the selection is available, so nothing is +/// recorded and redo still brings the photo back. +#[test] +fn a_selection_of_photos_that_are_gone_is_no_selection() { + let mut s = Session::new(); + photos(&mut s, 2); + let album = run(&mut s, "album.create", json!({"name": "Kept"}))["id"].as_u64().unwrap(); + let late = s.catalog.alloc_photo_id(); + let p = Photo::new(late, Source::Demo { scene: 1 }, "late.jpg", "JPEG", 60, 40, "2026-02-01T10:00:00"); + s.commit("Add Photo", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + s.selection.ids = vec![late]; + s.selection.active = Some(late); + run(&mut s, "edit.undo", json!({})); + let (steps, redo) = (s.undo.len(), s.redo.len()); + assert_eq!(redo, 1); + for (cmd, params) in [ + ("album.addPhotos", json!({"id": album})), + ("album.removePhotos", json!({"id": album})), + ("album.toggleTarget", json!({})), + ("photo.rotateRight", json!({})), + ("photo.flipHorizontal", json!({})), + ("photo.deletePermanently", json!({})), + ("photo.setMeta", json!({"title": "x"})), + ("photo.rate", json!({"rating": 3})), + ] { + let e = s.execute(cmd, ¶ms).map(|v| v.to_string()).unwrap_or_else(|e| e.to_string()); + assert_eq!((s.undo.len(), s.redo.len()), (steps, redo), "{cmd} recorded something: {e}"); + } + assert!(s.catalog.quick_collection().is_none(), "no Quick Collection was made for nothing"); + run(&mut s, "edit.redo", json!({})); + assert!(s.catalog.photo(late).is_some()); + assert_eq!(s.active(), Some(late)); + // photos named outright (a drag of the selection onto an album) that aren't there are left out + run(&mut s, "edit.undo", json!({})); + s.selection.ids = vec![PhotoId(1), late]; + let r = run(&mut s, "album.addPhotos", json!({"id": album, "ids": [1, late.0]})); + assert_eq!(r["added"], 1); + assert_eq!(s.catalog.album(AlbumId(album)).unwrap().photos, [PhotoId(1)]); +} + +/// Photos named outright that are all gone, while another photo is selected: nothing is added, +/// and no undo step is recorded for an album that did not change. +#[test] +fn naming_only_photos_that_are_gone_adds_nothing_and_records_nothing() { + let mut s = Session::new(); + photos(&mut s, 2); + let album = run(&mut s, "album.create", json!({"name": "Kept"}))["id"].as_u64().unwrap(); + s.selection.ids = vec![PhotoId(1)]; + s.selection.active = Some(PhotoId(1)); + let (steps, redo) = (s.undo.len(), s.redo.len()); + let r = run(&mut s, "album.addPhotos", json!({"id": album, "ids": [9999]})); + assert_eq!(r["added"], 0); + assert_eq!((s.undo.len(), s.redo.len()), (steps, redo)); + assert!(s.catalog.album(AlbumId(album)).unwrap().photos.is_empty()); +} + +/// The photos selected are gone but the active one is there and not among them: the commands act on the selection, +/// which is empty, so they are not available either. +#[test] +fn a_live_active_photo_does_not_stand_in_for_a_selection_that_is_gone() { + let mut s = Session::new(); + photos(&mut s, 2); + let late = s.catalog.alloc_photo_id(); + let p = Photo::new(late, Source::Demo { scene: 1 }, "late.jpg", "JPEG", 60, 40, "2026-02-01T10:00:00"); + s.commit("Add Photo", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + s.selection.ids = vec![late]; + s.selection.active = Some(PhotoId(1)); + assert!(crate::cmd::has_selection(&s).is_ok()); + run(&mut s, "edit.undo", json!({})); + assert!(s.selected().is_empty(), "the command would act on nothing"); + assert!(crate::cmd::has_selection(&s).is_err(), "so it is not available"); + // nothing selected but the active photo: it is the selection + s.selection.ids.clear(); + assert!(crate::cmd::has_selection(&s).is_ok()); +} + +#[test] +fn a_shown_album_that_only_changes_stays_shown() { + let mut s = Session::new(); + photos(&mut s, 3); + let folder = run(&mut s, "album.create", json!({"name": "Trips", "folder": true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "album.create", json!({"name": "Rome"}))["id"].as_u64().unwrap(); + show(&mut s, id); + s.selection.ids = vec![PhotoId(1)]; + run(&mut s, "album.addPhotos", json!({"id": id, "ids": [1]})); + run(&mut s, "album.rename", json!({"id": id, "name": "Roma"})); + run(&mut s, "album.move", json!({"id": id, "parent": folder})); + run(&mut s, "album.removePhotos", json!({"id": id, "ids": [1]})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.source, LibrarySource::Album(AlbumId(id))); + assert_eq!(s.source.label(&s.catalog), "Roma"); + assert_eq!(s.selection.ids, [PhotoId(1)]); +} + +#[test] +fn a_library_opens_on_all_photos_when_its_last_album_is_gone() { + /// Gone with the test, however it ends. + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let scratch = Scratch(std::env::temp_dir().join(format!("lc-view-reconcile-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&scratch.0); + let mut s = Session::new(); + s.open_library(&scratch.0, false).unwrap(); + photos(&mut s, 3); + let id = run(&mut s, "album.create", json!({"name": "Shown"}))["id"].as_u64().unwrap(); + show(&mut s, id); + s.save_view(); + // the view file still names the album; the library no longer has it + s.source = LibrarySource::All; + run(&mut s, "album.delete", json!({"id": id})); + let view = scratch.0.join("view.json"); + let saved = std::fs::read_to_string(&view).unwrap(); + assert!(saved.contains("album"), "{saved}"); + drop(s); + std::fs::write(&view, saved).unwrap(); + let mut back = Session::new(); + back.open_library(&scratch.0, false).unwrap(); + assert!(back.catalog.album(AlbumId(id)).is_none()); + shows_all(&mut back, "opened with a view of an album that is gone"); +} diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index 95915b74070..3e2fc2101aa 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -176,7 +176,9 @@ pub(super) fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Al crate::widgets::register(ui, "button:albumImport", menu.response.rect); } if !a.folder && !a.is_smart() { - let is_target = app.session.target_album == Some(a.id) || (app.session.target_album.is_none() && a.quick); + // looked up, as the row's "+" is: a target that is gone means the Quick Collection + let target = app.session.target_album.filter(|t| app.session.catalog.album(*t).is_some()); + let is_target = target == Some(a.id) || (target.is_none() && a.quick); if !is_target && ui.button(crate::i18n::tr("Set as Target Album (B adds to it)")).clicked() { let _ = app.run("album.setTarget", json!({"id": if a.quick { serde_json::Value::Null } else { json!(a.id.0) }})); } diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..a666ff741cd 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -157,6 +157,22 @@ the full count took about 14 s instead of about 23 s on a heavily loaded machine; the rest is the text rules of the albums themselves. The counts are the same as before, including for albums that loop through each other. +### Views that follow the library +- The grid goes back to All Photos whenever the album or smart album it shows goes away, by whatever way: + deleting it did already; undoing its creation, redoing its deletion or opening a library whose last view was of an + album since removed left an empty grid titled "Album". A filter that names such an album lets go of it (and does not + take it up again if the album comes back), a saved filter naming an album since deleted applies without it, and + `library.filter` refuses an album that doesn't exist. Opening another library starts with no filter, no target + album and no "previous photo", as after a restart: they named albums and photos of the library before. +- When an undo takes selected photos away, commands on the selection act on the photos that are left; when none is + left they are not available, so nothing is recorded and redo still brings the photos back. Add to Album used to + write a missing photo into the album, and rating the selection failed for all of it. +- A smart album saved from the view of an album is marked ⚠ when that album is deleted, instead of being + quietly empty. OK in Edit Smart Album, or Update Rules from Current Filter, saves its rules without the album that + is gone and clears the mark. +- Edit Smart Album ▸ OK on a smart album saved from the view of an album no longer drops the album: it used to + save the rules without it, and the smart album quietly matched the whole library. + ### Sharper resampling in HDR and panorama merges - Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a photo by half a pixel used to lose a third of its finest detail; now it keeps most of it, without halos around