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
87 changes: 77 additions & 10 deletions crates/catalog/src/folders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
//!
//! A *folder* here is a folder holding at least one photo of the library (imported, not deleted,
//! not merely browsed in Local; demo scenes have no folder). The tree lists those folders and the
//! ones above them, never a folder that holds nothing of the library, with how many photos each
//! holds — its subfolders included, like a year in By Date counts its months.
//! ones above them, with how many photos each holds — its subfolders included, like a year in By
//! Date counts its months. The folders made through LightCraft are listed too, empty or not, with
//! the folders above them (see below); no other folder that holds nothing of the library is.
//!
//! Every folder is a row of its own, the ones above the imported photos included
//! (`/Users` → `me` → `Pictures`), so a row is exactly the folder it names. A folder spelled two
Expand All @@ -24,10 +25,17 @@
//! two rows. Each row is still consistent: choosing it shows exactly the photos it counts.
//!
//! A folder is otherwise only where photos are, but the library can also keep a
//! [`FolderRecord`] about it (its colour label), stored under the folder's identity
//! ([`crate::query::folder_key`]). A record follows its folder when the folder is renamed or moved
//! here ([`Catalog::folder_records_follow`]); one about a folder that no longer holds a photo is
//! kept (undo can bring the photos back) and shows again when the folder does.
//! [`FolderRecord`] about it (its colour label, and whether it was made through LightCraft),
//! stored under the folder's identity ([`crate::query::folder_key`]). A folder made through
//! LightCraft has a row (count 0) from the start and for good: it is one row before and after it
//! gains photos, and it stays when they leave. If it is renamed or deleted outside LightCraft its
//! row stays, like any folder of the library whose files are missing: choosing it shows nothing.
//! Undoing its creation removes it, and so does Remove from Library ([`Catalog::folders_unmade_ops`];
//! undo brings it back). The row spells the folder as it was made, or as its move or rename put
//! it (the record's key alone would be lower case on Windows). A record follows its folder
//! when the folder is renamed or moved here ([`Catalog::folder_records_follow`]); one about a
//! folder that no longer holds a photo is kept (undo can bring the photos back) and shows again
//! when the folder does.
//!
//! This is the library's own view of its photos; browsing any folder on disk without importing
//! is Local's job (see [`crate::local`]).
Expand Down Expand Up @@ -77,12 +85,18 @@ pub struct FolderRecord {
/// A colour label, as a photo has one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<ColorLabel>,
/// Where the folder is, as it was spelled when it was made through LightCraft
/// (`folder.create`), if it was: it has a row in the tree before it holds a photo, and keeps
/// it after the photos are moved elsewhere. Kept as spelled so the row's path has the folder's
/// own letter case (the record's key is lower case on Windows).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub made: Option<String>,
}

impl FolderRecord {
/// Whether the record says nothing (and so is not kept).
pub fn is_empty(&self) -> bool {
self.label.is_none()
self.label.is_none() && self.made.is_none()
}
}

Expand Down Expand Up @@ -201,6 +215,46 @@ impl Catalog {
Op::SetFolderRecord { folder: path.to_string(), record: Some(record) }
}

/// The made folders (see [`FolderRecord::made`]) at or inside folder `path`: on the disk
/// `path` is on, or on any disk with `all_disks` (a folder above disks, `/Volumes`, holds
/// none of their made folders, as it holds none of their photos).
fn made_within<'a>(&'a self, path: &str, all_disks: bool) -> impl Iterator<Item = (&'a String, &'a FolderRecord)> {
let root = record_key(path);
let mount = place(path).map(|p| folder_key(&p.mount));
self.folder_records.iter().filter(move |(k, r)| {
let Some(spelled) = &r.made else { return false };
root.as_deref().is_some_and(|root| key_within(k, root)) && (all_disks || place(spelled).map(|p| folder_key(&p.mount)) == mount)
})
}

/// Whether folder `path` or a folder inside it was made through LightCraft: the tree lists
/// `path` as a row then, with or without photos.
pub fn holds_made_folder(&self, path: &str) -> bool {
self.made_within(path, false).next().is_some()
}

/// The ops that make the library forget that folder `path` and the folders inside it were
/// made through LightCraft (their rows then show only while they hold photos, like any other
/// folder); a label stays. `all_disks`: also those on other disks (a whole folder of disks
/// removed from the library). Empty when none was made.
pub fn folders_unmade_ops(&self, path: &str, all_disks: bool) -> Vec<Op> {
self.made_within(path, all_disks)
.map(|(k, r)| {
let record = FolderRecord { made: None, ..r.clone() };
Op::SetFolderRecord { folder: k.clone(), record: Some(record) }
})
.collect()
}

/// The op that records folder `path` as made through LightCraft, so the tree lists it before
/// it holds a photo, spelled as `path` is. Its inverse (undo) forgets it again. Applying it
/// checks the path.
pub fn folder_made_op(&self, path: &str) -> Op {
let mut record = self.folder_record(path).cloned().unwrap_or_default();
record.made = Some(path.to_string());
Op::SetFolderRecord { folder: path.to_string(), record: Some(record) }
}

/// The ops that carry the records of folder `from` and the folders inside it over to `to`
/// (the same place below it), for a folder renamed or moved on disk: commit them with the
/// photos' relinks so undo puts both back. Records already at or below `to` are left from a
Expand All @@ -220,7 +274,9 @@ impl Catalog {

fn folder_records_carried(&self, from: &str, to: &str, clear_destination: bool) -> Vec<Op> {
let (Some(root), Some(dest)) = (record_key(from), record_key(to)) else { return Vec::new() };
if root == dest {
// (the same identity under another spelling, a rename of case only on Windows, still
// rewrites the spelling a made folder is listed under)
if root == dest && (from == to || !self.holds_made_folder(from)) {
return Vec::new();
}
// a folder located below itself: what is already at or below `to` belongs to the folders
Expand All @@ -236,7 +292,15 @@ impl Catalog {
let rest = folder_rest(k, &root)?;
let base = dest.trim_end_matches('/');
let path = if rest.is_empty() { dest.clone() } else { format!("{base}/{}", rest.join("/")) };
Some((folder_key(&path), r.clone()))
let mut record = r.clone();
// the spelling a made folder is listed under follows too, as `to` spells its place
if let Some(spelled) = &r.made
&& let Some(rest) = folder_rest(spelled, from)
{
let base = to.trim_end_matches(['/', '\\']);
record.made = Some(if rest.is_empty() { base.to_string() } else { format!("{base}/{}", rest.join("/")) });
}
Some((folder_key(&path), record))
})
.collect();
// what was known at the old place goes, and so does what is left at the new one (also
Expand Down Expand Up @@ -264,7 +328,10 @@ impl Catalog {
}
let mut levels: HashMap<String, Level> = HashMap::new();
let mut roots: Vec<String> = Vec::new();
for (dir, n) in dirs {
// folders made through LightCraft count 0 until photos arrive; read after the photos' own
// spellings, so a folder that has photos is named as they spell it
let made = self.folder_records.values().filter_map(|r| r.made.as_deref());
for (dir, n) in dirs.into_iter().chain(made.map(|spelled| (spelled, 0))) {
let Some(placed) = place(dir) else { continue };
let vkey = folder_key(&placed.mount);
if !levels.contains_key(&vkey) {
Expand Down
3 changes: 2 additions & 1 deletion crates/catalog/src/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
//! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` |
//! | 12 | history steps and versions share segmentation grids (#2154) | `Catalog.grids`, `SegMask.grid` |
//! | 13 | Lens Blur | `DevelopSettings.lens_blur`, `Mask.adjust.lens_blur` |
//! | 14 | folders made in LightCraft keep their row | `FolderRecord.made` |
//!
//! Rules:
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
Expand All @@ -89,7 +90,7 @@ pub const LOG: &str = "catalog.log";
const FORMAT: &str = "lightcraft-catalog";
/// The catalog format this build writes (and the newest it reads). See the module docs →
/// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added.
pub const VERSION: u32 = 13;
pub const VERSION: u32 = 14;

/// When [`Journal::wants_snapshot`] says it's time to compact the log.
#[derive(Clone, Copy, Debug)]
Expand Down
132 changes: 131 additions & 1 deletion crates/catalog/src/tests_folder_records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ fn a_path_that_names_no_folder_is_refused() {
let mut c = library();
let before = c.to_snapshot();
for bad in ["", "relative/trip", ".", "a/.."] {
let op = Op::SetFolderRecord { folder: bad.into(), record: Some(FolderRecord { label: Some(ColorLabel::Red) }) };
let op = Op::SetFolderRecord { folder: bad.into(), record: Some(FolderRecord { label: Some(ColorLabel::Red), made: None }) };
assert!(c.apply(op).is_err(), "{bad:?} names no folder");
}
assert_eq!(c.to_snapshot(), before);
Expand Down Expand Up @@ -254,3 +254,133 @@ fn a_library_saved_before_folder_records_opens_without_any() {
let reopened = Catalog::from_snapshot(&old).unwrap();
assert_eq!(reopened.folder_record("/pics/trip"), None);
}

/// The rows of the tree as `(path, count, own)`, depth first.
fn tree_rows(c: &Catalog) -> Vec<(String, usize, usize)> {
fn walk(n: &FolderNode, out: &mut Vec<(String, usize, usize)>) {
out.push((n.path.clone(), n.count, n.own));
n.children.iter().for_each(|c| walk(c, out));
}
let mut out = Vec::new();
c.folder_tree().iter().for_each(|n| walk(n, &mut out));
out
}

#[test]
fn a_made_folder_is_a_row_with_no_photos_that_undo_takes_away() {
let mut c = library();
let before = c.to_snapshot();
let op = c.folder_made_op("/pics/new");
let undo = c.apply(op).unwrap();
assert!(c.holds_made_folder("/pics//new/"), "however it is spelled");
assert!(tree_rows(&c).contains(&("/pics/new".to_string(), 0, 0)));
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before, "undo leaves nothing behind");
assert!(!tree_rows(&c).iter().any(|r| r.0 == "/pics/new"));
}

#[test]
fn a_made_folder_is_one_row_before_and_after_it_gains_photos() {
let mut c = library();
let op = c.folder_made_op("/pics/new");
c.apply(op).unwrap();
add(&mut c, "/pics//new/x.jpg");
let rows: Vec<_> = tree_rows(&c).into_iter().filter(|r| r.0.ends_with("/new")).collect();
assert_eq!(rows.len(), 1, "{rows:?}");
assert_eq!((rows[0].1, rows[0].2), (1, 1));
}

#[test]
fn a_made_folder_in_a_folder_with_no_photos_of_its_own_nests_there_and_adds_nothing_to_the_counts() {
let mut c = library();
let op = c.folder_made_op("/pics/trip/day9");
c.apply(op).unwrap();
let rows = tree_rows(&c);
let at = |p: &str| rows.iter().position(|r| r.0 == p).unwrap_or_else(|| panic!("{p}: {rows:?}"));
assert!(at("/pics/trip") < at("/pics/trip/day9"), "below its parent");
assert_eq!(rows[at("/pics/trip")].1, 2, "the parent counts photos only");
assert_eq!(rows[at("/pics/trip/day9")].1, 0);
}

#[test]
fn a_made_folder_on_a_disk_the_library_has_no_photo_on_is_listed_under_that_disk() {
let mut c = library();
let op = c.folder_made_op("/Volumes/spare/new");
c.apply(op).unwrap();
let rows = tree_rows(&c);
assert!(rows.contains(&("/Volumes/spare".to_string(), 0, 0)) && rows.contains(&("/Volumes/spare/new".to_string(), 0, 0)), "{rows:?}");
}

#[test]
fn the_made_flag_follows_a_moved_folder_and_keeps_the_label_it_has() {
let mut c = library();
let op = c.folder_made_op("/pics/new");
c.apply(op).unwrap();
label(&mut c, "/pics/new", Some(ColorLabel::Red));
label(&mut c, "/pics/new", None);
assert!(c.holds_made_folder("/pics/new"), "taking the label off keeps the folder's record");
let ops = c.folder_records_follow("/pics/new", "/archive/new");
c.apply(Op::Batch { ops }).unwrap();
assert!(!c.holds_made_folder("/pics/new") && c.holds_made_folder("/archive/new"));
let spelled = c.folder_record("/archive/new").and_then(|r| r.made.clone());
assert_eq!(spelled.as_deref(), Some("/archive/new"), "the row is spelled where the folder now is");
}

#[test]
fn a_made_folders_spelling_follows_a_rename_that_keeps_its_identity() {
// (on Windows `new` → `New` is one folder: keys are lower case; here a spelling that reads the same)
let mut c = library();
let op = c.folder_made_op("/pics/new");
c.apply(op).unwrap();
let ops = c.folder_records_follow("/pics/new", "/pics/./new");
assert!(!ops.is_empty());
c.apply(Op::Batch { ops }).unwrap();
assert_eq!(c.folder_record("/pics/new").and_then(|r| r.made.clone()).as_deref(), Some("/pics/./new"));
assert!(c.folder_records_follow("/pics/./new", "/pics/./new").is_empty(), "the same path again changes nothing");
}

#[test]
fn a_folder_above_disks_holds_none_of_their_made_folders() {
let mut c = library();
let op = c.folder_made_op("/Volumes/spare/new");
c.apply(op).unwrap();
assert!(c.holds_made_folder("/Volumes/spare") && c.holds_made_folder("/Volumes/spare/new"));
assert!(!c.holds_made_folder("/Volumes"), "what covers other disks is not offered for choosing or scanning");
assert!(c.folders_unmade_ops("/Volumes", false).is_empty());
assert_eq!(c.folders_unmade_ops("/Volumes", true).len(), 1, "removing a whole folder of disks forgets theirs too");
}

#[test]
fn a_made_folder_survives_closing_and_reopening_and_an_older_record_reads_as_not_made() {
let mut c = library();
let op = c.folder_made_op("/pics/new");
c.apply(op).unwrap();
let reopened = Catalog::from_snapshot(&c.to_snapshot()).unwrap();
assert!(reopened.holds_made_folder("/pics/new"));
assert!(tree_rows(&reopened).contains(&("/pics/new".to_string(), 0, 0)));
// a record saved by a build that knew only the label has no `made`, and an unmade one is
// saved just so
let json = serde_json::to_string(&FolderRecord { label: Some(ColorLabel::Red), made: None }).unwrap();
assert!(!json.contains("made"), "{json}");
let old: FolderRecord = serde_json::from_str(&json).unwrap();
assert!(old.made.is_none() && !old.is_empty());
}

#[test]
fn forgetting_made_folders_keeps_a_label_and_undo_restores_the_record() {
let mut c = library();
for p in ["/pics/new", "/pics/new/inner", "/pics/newer"] {
let op = c.folder_made_op(p);
c.apply(op).unwrap();
}
label(&mut c, "/pics/new", Some(ColorLabel::Blue));
let before = c.to_snapshot();
let ops = c.folders_unmade_ops("/pics/new", false);
let undo = c.apply(Op::Batch { ops }).unwrap();
assert!(!c.holds_made_folder("/pics/new") && !c.holds_made_folder("/pics/new/inner"));
assert!(c.holds_made_folder("/pics/newer"), "a neighbor whose name starts the same stays");
assert_eq!(c.folder_color_label("/pics/new"), Some(ColorLabel::Blue));
assert!(c.folders_unmade_ops("/pics/trip", false).is_empty());
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
}
44 changes: 42 additions & 2 deletions crates/catalog/src/tests_format_version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,46 @@ fn v6_preview_only_photo_loads_unstamped_and_is_upgraded() {
assert_eq!(snapshot_version(&m), u64::from(VERSION));
}

/// A library of format `from` with a folder label (a record without `made`) opens as it was and is
/// rewritten in the current format; a folder made afterwards is saved with it. A build of format
/// `from` then refuses the library by the rule `newer_snapshot_is_refused_untouched` tests.
fn folder_records_library_is_upgraded(from: u32) {
let (mut base, _, _) = legacy_parts();
let op = base.folder_label_op("/p", Some(ColorLabel::Red));
base.apply(op).unwrap();
let m = MemStore::new();
m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":{from},\"seq\":3,\"catalog\":{}}}\n", base.to_snapshot()).into_bytes());
m.set(LOG, Vec::new());
let (mut j, mut c, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!(r.upgraded_from, Some(from));
assert_eq!(snapshot_version(&m), u64::from(VERSION));
assert_eq!(c.folder_color_label("/p"), Some(ColorLabel::Red));
assert!(!c.holds_made_folder("/p"), "no folder was made in a v{from} library");
let made = c.folder_made_op("/p/new");
c.apply(made.clone()).unwrap();
j.append(&[made]).unwrap();
j.snapshot(&c).unwrap();
drop(j);
let (_, reopened, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!(r.upgraded_from, None);
assert!(reopened.holds_made_folder("/p/new"));
assert_eq!(reopened.folder_color_label("/p"), Some(ColorLabel::Red));
// a build of format `from` refuses a snapshot above it
assert!(snapshot_version(&m) > u64::from(from));
}

#[test]
fn v12_library_with_folder_records_is_upgraded_and_the_new_format_is_refused_by_older_builds() {
folder_records_library_is_upgraded(12);
}

/// Format 13 is what `main` wrote before `FolderRecord.made` (Lens Blur): such a library has no
/// `made`, and must still be upgraded, not read as current.
#[test]
fn v13_library_written_without_made_is_upgraded_and_the_new_format_is_refused_by_older_builds() {
folder_records_library_is_upgraded(13);
}

#[test]
fn versionless_log_only_library_is_upgraded() {
let mut c = Catalog::new();
Expand Down Expand Up @@ -238,9 +278,9 @@ fn op_variants_are_versioned() {
Op::SetHistoryCursor { .. } => 8,
}
}
/// v13: Lens Blur in develop settings and mask adjustments (v12: `Catalog.grids` and `SegMask.grid`; v11: `EmbeddedLens.source`;
/// v14: `FolderRecord.made` (v13: Lens Blur in develop settings and mask adjustments; v12: `Catalog.grids` and `SegMask.grid`; v11: `EmbeddedLens.source`;
/// v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
const NEWEST_FIELDS: u32 = 13;
const NEWEST_FIELDS: u32 = 14;
let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None });
assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version");
}
Loading
Loading