LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Sidebar: Folders section for the folders the library's photos were imported from
Nathaniel Ledford82e827b9d966
diff --git a/crates/catalog/src/folders.rs b/crates/catalog/src/folders.rsnew file mode 100644index 000000000..3861fd5f1--- /dev/null+++ b/crates/catalog/src/folders.rs@@ -0,0 +1,231 @@+//! The library's folder tree: where on disk the imported photos live.+//!+//! 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.+//!+//! Folders above the imported ones that hold nothing themselves and lead to a single folder fold+//! into one row (`/Users/me/Pictures`) instead of a staircase of single-child levels; the row+//! stands for the deepest folder it names. A folder spelled two ways (`/` or `\`, repeated or+//! trailing separators, `.`) is one folder (see [`crate::query::folder_key`]).+//!+//! Each disk is a *volume*, a top-level row of its own: a drive letter (`D:`), a Windows share+//! (`//server/share`), a mounted disk or share (macOS `/Volumes/tokyo`, Linux `/media/me/usb`,+//! `/mnt/disk`, `/run/user/1000/gvfs/smb-share:…`, `/net/host`) or, for everything else, the+//! startup disk (`/`). Only the spelling of the stored paths tells them apart: no disk is+//! touched, so a share that is asleep or gone lists and counts like one that is there, and the+//! sidebar never waits on the network.+//!+//! Limits of reading only the stored spelling of a path: file names are compared as written+//! (Windows folds case, other systems do not), so on a case-insensitive disk `/Volumes/tokyo` and+//! `/Volumes/TOKYO` are two volumes here; and one place reached by two spellings+//! (`/Volumes/Macintosh HD/Users/me` and `/Users/me`, `/media/me/usb` and `/run/media/me/usb`) is+//! two rows. Each row is still consistent: choosing it shows exactly the photos it counts.+//!+//! This is the library's own view of its photos; browsing any folder on disk without importing+//! is Local's job (see [`crate::local`]).++use std::collections::{BTreeMap, HashMap};++use serde::Serialize;++use crate::query::{folder_key, folder_within, split_path};+use crate::{Catalog, Source};++/// Folder levels kept per photo. No real path comes near it; a deeper one is counted at its+/// ancestor this many levels down, which bounds the tree's depth (and so every walk of it)+/// whatever a catalog holds.+pub const MAX_DEPTH: usize = 64;++/// One row of the library's folder tree.+#[derive(Clone, Debug, PartialEq, Serialize)]+pub struct FolderNode {+ /// What the row says: the folder's name, or the whole run (`Users/me/Pictures`) of folded+ /// levels; for a volume, its name (`nas`, `D:`, `//server/share`, `/` for the startup disk).+ pub name: String,+ /// The folder the row stands for, written out from the names of the photos' paths (forward+ /// slashes, no verbatim prefix); hand it back to [`crate::Filter::library_folder`] to see its+ /// photos.+ pub path: String,+ /// Photos in this folder or any folder inside it.+ pub count: usize,+ /// Photos directly in this folder.+ pub own: usize,+ /// A disk rather than a folder in one; its `path` is where it is mounted.+ pub volume: bool,+ /// Whether choosing the row (`Filter::library_folder`) shows exactly its `count` photos. Not+ /// so for the startup disk and for folders that hold other disks (`/Volumes`, `/mnt`…): their+ /// path covers those disks' photos too, so choosing them is not offered.+ pub selectable: bool,+ pub children: Vec<FolderNode>,+}++/// A folder while the tree is being built (children by identity key).+struct Level {+ name: String,+ path: String,+ own: usize,+ volume: bool,+ children: Vec<String>,+}++/// Where a stored folder path lies: its volume and the folder names below it.+struct Placed {+ mount: String,+ volume: String,+ names: Vec<String>,+}++/// A gvfs mount's name made readable: `smb-share:server=tokyo,share=photos` → `photos on tokyo`;+/// any other (`sftp:host=nas`) as it is.+fn mount_name(n: &str) -> String {+ let field = |key: &str| {+ let rest = n.strip_prefix("smb-share:")?;+ rest.split(',').find_map(|kv| kv.strip_prefix(key)?.strip_prefix('=')).filter(|v| !v.is_empty())+ };+ match (field("share"), field("server")) {+ (Some(share), Some(server)) => format!("{share} on {server}"),+ _ => n.to_string(),+ }+}++/// The volume `dir` lies on and the folder names below it, read the way [`folder_key`] reads a+/// path (so a row and the filter that chooses it never disagree). `None` for a path that is not+/// absolute or names no share.+fn place(dir: &str) -> Option<Placed> {+ let sp = split_path(dir, false);+ let names: Vec<&str> = sp.parts.iter().map(String::as_str).collect();+ let named = |mount: String, volume: &str, used: usize| (mount, volume.to_string(), used);+ let (mount, volume, used) = if sp.prefix.starts_with("//") {+ // `//server/share`: a server alone (no share) is no place to keep photos+ if sp.prefix.ends_with('/') {+ return None;+ }+ named(sp.prefix.clone(), &sp.prefix, 0)+ } else if !sp.prefix.is_empty() {+ named(sp.prefix.clone(), &sp.prefix, 0)+ } else if sp.absolute {+ match names.as_slice() {+ ["Volumes", n, ..] => named(format!("/Volumes/{n}"), n, 2),+ ["run", "media", u, n, ..] => named(format!("/run/media/{u}/{n}"), n, 4),+ ["media", u, n, ..] => named(format!("/media/{u}/{n}"), n, 3),+ ["mnt", n, ..] => named(format!("/mnt/{n}"), n, 2),+ // Linux desktops mount network places per user, naming server and share+ ["run", "user", uid, "gvfs", n, ..] => named(format!("/run/user/{uid}/gvfs/{n}"), &mount_name(n), 5),+ // NFS automounts: Linux `/net/<host>`, macOS `/Network/Servers/<host>`+ ["net", host, ..] => named(format!("/net/{host}"), host, 2),+ ["Network", "Servers", host, ..] => named(format!("/Network/Servers/{host}"), host, 3),+ _ => named("/".to_string(), "/", 0),+ }+ } else {+ return None;+ };+ Some(Placed { mount, volume, names: names.iter().skip(used).take(MAX_DEPTH).map(|n| n.to_string()).collect() })+}++/// The disk or share (`/Volumes/nas`, `D:`, `/` for the startup disk) a file-backed photo is on,+/// from its stored path alone.+pub fn volume_of(p: &crate::Photo) -> Option<String> {+ let Source::File { path } = &p.source else { return None };+ let dir = path.rfind(['/', '\\']).and_then(|i| path.get(..i.max(1)))?;+ place(dir).map(|pl| folder_key(&pl.mount))+}++/// Whether `path` is a whole disk or share (`/`, `C:\`, `\\srv\share`, `/Volumes/nas`), not a+/// folder in one.+pub fn is_disk_root(path: &str) -> bool {+ place(path).is_some_and(|p| p.names.is_empty())+}++/// Whether `path` is the startup disk's root (`/`), whose path also covers every other disk.+pub fn is_startup_disk(path: &str) -> bool {+ place(path).is_some_and(|p| p.names.is_empty() && p.mount == "/")+}++/// A folder named by its last two names (`photos/travel`), so two folders called `travel` are+/// told apart; the path itself when it has no names (`/`).+pub fn folder_label(path: &str) -> String {+ let names: Vec<&str> = path.split(['/', '\\']).filter(|n| !n.is_empty()).collect();+ if names.is_empty() { path.to_string() } else { names.iter().skip(names.len().saturating_sub(2)).copied().collect::<Vec<_>>().join("/") }+}++impl Catalog {+ /// The library's volumes with their folders and photo counts: volumes by name+ /// (case-insensitive), each folder with its subfolders the same way.+ pub fn folder_tree(&self) -> Vec<FolderNode> {+ // photos per containing folder, as spelled (sorted, so the spelling that names a folder+ // never depends on hash order)+ let mut dirs: BTreeMap<&str, usize> = BTreeMap::new();+ for p in self.photos().filter(|p| p.in_library()) {+ if let Source::File { path } = &p.source+ && let Some(i) = path.rfind(['/', '\\'])+ // a photo straight in the root has an empty folder part: the root itself+ && let Some(dir) = path.get(..i.max(1))+ {+ *dirs.entry(dir).or_default() += 1;+ }+ }+ let mut levels: HashMap<String, Level> = HashMap::new();+ let mut roots: Vec<String> = Vec::new();+ for (dir, n) in dirs {+ let Some(placed) = place(dir) else { continue };+ let vkey = folder_key(&placed.mount);+ if !levels.contains_key(&vkey) {+ levels.insert(+ vkey.clone(),+ Level { name: placed.volume.clone(), path: placed.mount.clone(), own: 0, volume: true, children: Vec::new() },+ );+ roots.push(vkey.clone());+ }+ let mut prefix = if placed.mount == "/" { String::new() } else { placed.mount.clone() };+ let mut parent = vkey;+ for name in &placed.names {+ prefix.push('/');+ prefix.push_str(name);+ let key = folder_key(&prefix);+ if !levels.contains_key(&key) {+ levels.insert(key.clone(), Level { name: name.clone(), path: prefix.clone(), own: 0, volume: false, children: Vec::new() });+ if let Some(l) = levels.get_mut(&parent) {+ l.children.push(key.clone());+ }+ }+ parent = key;+ }+ if let Some(l) = levels.get_mut(&parent) {+ l.own += n;+ }+ }+ let mut tree: Vec<FolderNode> = roots.iter().filter_map(|k| build(k, &levels)).collect();+ sort(&mut tree);+ // a folder that holds another disk's mount covers that disk's photos too+ let mounts: Vec<String> = tree.iter().filter(|v| v.path != "/").map(|v| v.path.clone()).collect();+ mark_selectable(&mut tree, &mounts);+ tree+ }+}++/// The node for `key` with everything below it (at most [`MAX_DEPTH`] deep), folding a level+/// that holds nothing and leads to one folder into that folder (never a volume).+fn build(key: &str, levels: &HashMap<String, Level>) -> Option<FolderNode> {+ let l = levels.get(key)?;+ let mut children: Vec<FolderNode> = l.children.iter().filter_map(|k| build(k, levels)).collect();+ sort(&mut children);+ let count = l.own + children.iter().map(|c| c.count).sum::<usize>();+ if !l.volume && l.own == 0 && children.len() == 1 {+ let c = children.remove(0);+ return Some(FolderNode { name: format!("{}/{}", l.name, c.name), ..c });+ }+ Some(FolderNode { name: l.name.clone(), path: l.path.clone(), count, own: l.own, volume: l.volume, selectable: true, children })+}++fn mark_selectable(nodes: &mut [FolderNode], mounts: &[String]) {+ for n in nodes {+ n.selectable = !(n.volume && n.path == "/") && (n.volume || !mounts.iter().any(|m| folder_within(m, &n.path)));+ mark_selectable(&mut n.children, mounts);+ }+}++fn sort(v: &mut [FolderNode]) {+ v.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.name.cmp(&b.name)));+}diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rsindex 208a86d09..59d8c4a8f 100644--- a/crates/catalog/src/lib.rs+++ b/crates/catalog/src/lib.rs@@ -14,6 +14,7 @@#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]pub mod dates;+pub mod folders;pub mod journal;pub mod keywords;pub mod local;@@ -29,6 +30,7 @@ use std::collections::BTreeMap;use std::sync::Arc;pub use dates::{DateRun, GroupBy};+pub use folders::FolderNode;pub use journal::{Journal, LoadReport, PersistStats, SnapshotPolicy, SnapshotTiming};pub use keywords::KeywordNode;use lightcraft_develop::DevelopSettings;@@ -655,6 +657,8 @@ mod tests;#[cfg(test)]mod tests_background;#[cfg(test)]+mod tests_folders;+#[cfg(test)]mod tests_format_version;#[cfg(test)]mod tests_journal;diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rsindex d06e13700..6f02b2286 100644--- a/crates/catalog/src/query.rs+++ b/crates/catalog/src/query.rs@@ -37,6 +37,10 @@ pub struct Filter {pub deleted: bool,/// Capture date prefix (`2026`, `2026-04`, `2026-04-12`).pub date: Option<String>,+ /// A folder the library's photos were imported from: those photos and the ones imported from+ /// the folders inside it (see [`crate::folders`]). Photos only browsed in Local are never part+ /// of it, unlike [`Filter::folder`].+ pub library_folder: Option<String>,/// A keyword; hierarchical keywords match their children too (`travel` finds `travel|italy`).pub keyword: Option<String>,/// A person: photos with a named face region of this name (case-insensitive), as read from XMP.@@ -186,6 +190,7 @@ impl Filter {("camera", &self.camera),("lens", &self.lens),("date", &self.date),+ ("folder", &self.library_folder),("imported", &self.imported),] {if let Some(x) = val {@@ -213,6 +218,17 @@ impl Filter {}pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool {+ self.matches_in(p, cat, self.library_root().as_deref())+ }++ /// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice.+ fn library_root(&self) -> Option<String> {+ self.library_folder.as_deref().map(str::trim).filter(|d| !d.is_empty()).map(folder_key)+ }++ /// [`Filter::matches`] with the library folder already turned into its identity, so a query+ /// over a big library does that once, not once per photo.+ fn matches_in(&self, p: &Photo, cat: &Catalog, root: Option<&str>) -> bool {if p.deleted != self.deleted {return false;}@@ -285,6 +301,11 @@ impl Filter {{return false;}+ if let Some(root) = root+ && !(!p.local && crate::local::folder_of(p).is_some_and(|f| key_within(&f, root)))+ {+ return false;+ }if let Some(d) = &self.imported&& !p.imported.starts_with(d.as_str()){@@ -317,7 +338,8 @@ impl Filter {impl Catalog {/// Photos matching `filter`, in `sort` order (ties broken by id for stability).pub fn query(&self, filter: &Filter, sort: &Sort) -> Vec<PhotoId> {- let mut v: Vec<&Photo> = self.photos().map(|p| p.as_ref()).filter(|p| filter.matches(p, self)).collect();+ let root = filter.library_root();+ let mut v: Vec<&Photo> = self.photos().map(|p| p.as_ref()).filter(|p| filter.matches_in(p, self, root.as_deref())).collect();v.sort_by(|a, b| {let o = match sort.key {SortKey::CaptureDate => a.date().cmp(b.date()),@@ -384,7 +406,8 @@ impl Catalog {pub fn people_in(&self, filter: &Filter) -> Vec<Person> {let filter = Filter { person: None, ..filter.clone() };let mut m: std::collections::HashMap<String, (Person, f64)> = Default::default();- for p in self.photos().filter(|p| filter.matches(p, self)) {+ let root = filter.library_root();+ for p in self.photos().filter(|p| filter.matches_in(p, self, root.as_deref())) {let mut seen: Vec<String> = Vec::new();for r in p.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) {let Some(name) = r.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue };@@ -438,12 +461,18 @@ pub fn in_folder(path: &str, dir: &str, deep: bool) -> bool {!rest.is_empty() && (deep || !rest.contains(['/', '\\']))}-/// A folder path's identity, for telling whether two spellings name the same folder: `/` and-/// `\\` are both separators, repeated separators, `.` and a trailing separator are dropped,-/// `..` is resolved lexically, a Windows verbatim prefix (`\\?\`) is removed and the drive-/// letter lower-cased; on Windows (case-insensitive file names) the whole path is lower-cased.-/// No file-system access: the paths compared should already be absolute.-pub fn folder_key(path: &str) -> String {+/// A path read the way [`folder_key`] reads it: the part `..` can't climb above (`//server/share`,+/// `c:`; empty for `/` and relative paths), the names below it, and whether it is absolute.+pub(crate) struct SplitPath {+ pub prefix: String,+ pub parts: Vec<String>,+ pub absolute: bool,+}++/// Both separators, repeated separators (also between a server and its share), `.` and a+/// trailing separator dropped, `..` resolved lexically, a Windows verbatim prefix removed;+/// `lower_drive` lower-cases a drive letter (the identity does, a display name wants it as is).+pub(crate) fn split_path(path: &str, lower_drive: bool) -> SplitPath {let mut s = path.replace('\\', "/");if let Some(rest) = s.strip_prefix("//?/").or_else(|| s.strip_prefix("//./")) {s = match rest.strip_prefix("UNC/") {@@ -451,28 +480,39 @@ pub fn folder_key(path: &str) -> String {None => rest.to_string(),};}- // the part `..` can't climb above: `//server/share`, `c:` or `/`let (prefix, rest) = if let Some(unc) = s.strip_prefix("//").filter(|u| !u.is_empty() && !u.starts_with('/')) {- let mut it = unc.splitn(3, '/');- let (server, share, rest) = (it.next().unwrap_or(""), it.next().unwrap_or(""), it.next().unwrap_or(""));- (format!("//{server}/{share}"), rest.to_string())- } else if s.len() >= 2 && s.as_bytes()[1] == b':' && s.as_bytes()[0].is_ascii_alphabetic() {- (s[..2].to_ascii_lowercase(), s[2..].to_string())+ let mut segs = unc.split('/').filter(|x| !x.is_empty());+ let (server, share) = (segs.next().unwrap_or(""), segs.next().unwrap_or(""));+ (format!("//{server}/{share}"), segs.collect::<Vec<_>>().join("/"))+ } else if let (true, Some(drive), Some(rest)) = (matches!(s.as_bytes(), [a, b':', ..] if a.is_ascii_alphabetic()), s.get(..2), s.get(2..)) {+ (if lower_drive { drive.to_ascii_lowercase() } else { drive.to_string() }, rest.to_string())} else {(String::new(), s.clone())};let absolute = rest.starts_with('/') || !prefix.is_empty();- let mut parts: Vec<&str> = Vec::new();+ let mut parts: Vec<String> = Vec::new();for c in rest.split('/') {match c {"" | "." => {}- ".." if parts.last().is_some_and(|p| *p != "..") => {+ ".." if parts.last().is_some_and(|p| p != "..") => {parts.pop();}".." if absolute => {}- c => parts.push(c),+ c => parts.push(c.to_string()),}}+ SplitPath { prefix, parts, absolute }+}++/// A folder path's identity, for telling whether two spellings name the same folder: `/` and+/// `\\` are both separators, repeated separators, `.` and a trailing separator are dropped,+/// `..` is resolved lexically, a Windows verbatim prefix (`\\?\`) is removed and the drive+/// letter lower-cased; on Windows (case-insensitive file names) the whole path is lower-cased.+/// File names are otherwise compared as written, so on a case-insensitive disk elsewhere+/// (macOS, a Samba share) two spellings that differ in case are two folders here.+/// No file-system access: the paths compared should already be absolute.+pub fn folder_key(path: &str) -> String {+ let SplitPath { prefix, parts, absolute } = split_path(path, true);let key = if absolute { format!("{prefix}/{}", parts.join("/")) } else { parts.join("/") };if cfg!(windows) { key.to_lowercase() } else { key }}@@ -480,8 +520,18 @@ pub fn folder_key(path: &str) -> String {/// Whether `path` is folder `root` or lies somewhere inside it, however either is spelled/// (see [`folder_key`]).pub fn folder_within(path: &str, root: &str) -> bool {- let (p, r) = (folder_key(path), folder_key(root));- p == r || (p.starts_with(&r) && (r.ends_with('/') || p[r.len()..].starts_with('/')))+ key_within(&folder_key(path), &folder_key(root))+}++/// [`folder_within`] for two paths already turned into their [`folder_key`].+fn key_within(p: &str, r: &str) -> bool {+ // `.` or `a/..` name no folder: not "everything"+ if r.is_empty() {+ return false;+ }+ // a disk's root key ends in `/` (`c:/`, `//srv/share/`), a folder's does not: same folder+ let (p, r) = (p.trim_end_matches('/'), r.trim_end_matches('/'));+ p == r || p.strip_prefix(r).is_some_and(|rest| rest.starts_with('/'))}/// The kind of Photo Merge result a file is, from the name merges give it (`IMG_1-HDR.dng`,diff --git a/crates/catalog/src/tests_folders.rs b/crates/catalog/src/tests_folders.rsnew file mode 100644index 000000000..6c7c9ab7d--- /dev/null+++ b/crates/catalog/src/tests_folders.rs@@ -0,0 +1,331 @@+//! The library's folder tree: where the imported photos live on disk (see [`crate::folders`]).+//!+//! Scenarios, in the words of someone browsing their library:+//!+//! * Given photos imported from several folders, the tree lists those folders and no others,+//! each with how many photos it holds, under the disk (volume) they are on.+//! * A folder's count includes the folders inside it.+//! * Folders above the imported ones that hold nothing themselves fold into one row, until the+//! library branches.+//! * Photos only browsed in Local, deleted photos and demo scenes are not "imported from" anywhere.+//! * However a folder is spelled, it is one folder.+//! * Choosing a folder shows what was imported from it and from the folders inside it — exactly+//! as many photos as the row says.++use crate::*;++fn add(c: &mut Catalog, path: &str) -> PhotoId {+ add_with(c, path, |_| {})+}++fn add_with(c: &mut Catalog, path: &str, tweak: impl FnOnce(&mut Photo)) -> PhotoId {+ let id = c.alloc_photo_id();+ let name = path.rsplit(['/', '\\']).next().unwrap_or(path);+ let mut p = Photo::new(id, Source::File { path: path.into() }, name, "JPEG", 60, 40, "2026-01-01T10:00:00");+ tweak(&mut p);+ c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();+ id+}++fn library(paths: &[&str]) -> Catalog {+ let mut c = Catalog::new();+ paths.iter().for_each(|p| {+ add(&mut c, p);+ });+ c+}++/// `(name, count, own)` of each node, depth first.+fn outline(nodes: &[FolderNode]) -> Vec<(String, usize, usize)> {+ fn walk(n: &FolderNode, out: &mut Vec<(String, usize, usize)>) {+ out.push((n.name.clone(), n.count, n.own));+ n.children.iter().for_each(|c| walk(c, out));+ }+ let mut out = Vec::new();+ nodes.iter().for_each(|n| walk(n, &mut out));+ out+}++fn row(name: &str, count: usize, own: usize) -> (String, usize, usize) {+ (name.to_string(), count, own)+}++fn rows(paths: &[&str]) -> Vec<(String, usize, usize)> {+ outline(&library(paths).folder_tree())+}++#[test]+fn an_empty_library_has_no_folders() {+ assert!(Catalog::new().folder_tree().is_empty());+}++#[test]+fn only_folders_with_imported_photos_are_listed_with_their_counts() {+ let c = library(&["/pics/trip/a.jpg", "/pics/trip/b.jpg", "/pics/home/c.jpg"]);+ let tree = c.folder_tree();+ assert_eq!(outline(&tree), vec![row("/", 3, 0), row("pics", 3, 0), row("home", 1, 1), row("trip", 2, 2)]);+ assert!(tree[0].volume && !tree[0].children[0].volume);+ assert_eq!(tree[0].children[0].children[1].path, "/pics/trip", "a row knows its folder, for choosing it");+}++#[test]+fn a_folders_count_includes_the_folders_inside_it() {+ let r = rows(&["/pics/trip/a.jpg", "/pics/trip/day1/b.jpg", "/pics/trip/day1/c.jpg", "/pics/trip/day2/d.jpg"]);+ assert_eq!(r, vec![row("/", 4, 0), row("pics/trip", 4, 1), row("day1", 2, 2), row("day2", 1, 1)]);+}++#[test]+fn folders_that_hold_nothing_fold_into_one_row_until_the_library_branches() {+ let c = library(&["/Users/me/Pictures/2024/a.jpg", "/Users/me/Pictures/2025/b.jpg", "/Volumes/nas/photos/c.jpg"]);+ let tree = c.folder_tree();+ assert_eq!(+ outline(&tree),+ vec![row("/", 2, 0), row("Users/me/Pictures", 2, 0), row("2024", 1, 1), row("2025", 1, 1), row("nas", 1, 0), row("photos", 1, 1)]+ );+ assert_eq!(tree[0].children[0].path, "/Users/me/Pictures", "the folded row stands for the deepest folder it names");+}++#[test]+fn a_folder_with_photos_of_its_own_is_not_folded_into_its_child() {+ assert_eq!(rows(&["/pics/a.jpg", "/pics/trip/b.jpg"]), vec![row("/", 2, 0), row("pics", 2, 1), row("trip", 1, 1)]);+}++#[test]+fn browsed_deleted_and_demo_photos_are_not_imported_from_anywhere() {+ let mut c = Catalog::new();+ add(&mut c, "/pics/kept/a.jpg");+ add_with(&mut c, "/pics/browsed/b.jpg", |p| p.local = true);+ add_with(&mut c, "/pics/gone/c.jpg", |p| p.deleted = true);+ let id = c.alloc_photo_id();+ let demo = Photo::new(id, Source::Demo { scene: 1 }, "demo", "JPEG", 60, 40, "2026-01-01T10:00:00");+ c.apply(Op::AddPhoto { photo: Box::new(demo) }).unwrap();+ assert_eq!(outline(&c.folder_tree()), vec![row("/", 1, 0), row("pics/kept", 1, 1)]);+}++#[test]+fn however_a_folder_is_spelled_it_is_one_folder() {+ let r = rows(&["/pics/trip/a.jpg", "/pics//trip/./b.jpg", "/pics\\trip\\c.jpg", "/pics/x/../trip/d.jpg"]);+ assert_eq!(r, vec![row("/", 4, 0), row("pics/trip", 4, 4)]);+}++#[test]+fn each_disk_is_a_volume_of_its_own() {+ // macOS, Linux and Windows habits for where disks appear+ let r = rows(&["/Volumes/nas/p/1.jpg", "/media/me/usb/2.jpg", "/run/media/me/card/3.jpg", "/mnt/disk/4.jpg"]);+ assert_eq!(r, vec![row("card", 1, 1), row("disk", 1, 1), row("nas", 1, 0), row("p", 1, 1), row("usb", 1, 1)]);+ let r = rows(&["D:\\Photos\\2024\\a.jpg", "D:\\Photos\\2025\\b.jpg", "C:\\x\\c.jpg"]);+ assert_eq!(r, vec![row("C:", 1, 0), row("x", 1, 1), row("D:", 2, 0), row("Photos", 2, 0), row("2024", 1, 1), row("2025", 1, 1)]);+}++#[test]+fn a_network_share_is_a_volume_and_two_spellings_are_one() {+ let r = rows(&["\\\\srv\\s1\\a\\1.jpg", "\\\\srv\\s2\\b\\2.jpg"]);+ assert_eq!(r, vec![row("//srv/s1", 1, 0), row("a", 1, 1), row("//srv/s2", 1, 0), row("b", 1, 1)]);+ // the verbatim form Windows APIs give is the same share+ let r = rows(&["\\\\?\\UNC\\srv\\s1\\a\\1.jpg", "\\\\srv\\s1\\a\\2.jpg"]);+ assert_eq!(r, vec![row("//srv/s1", 2, 0), row("a", 2, 2)]);+}++#[test]+fn a_samba_share_mounted_on_a_mac_is_a_volume_named_after_the_share() {+ // Finder mounts every share under /Volumes, and a second mount of the same share gets a suffix+ let r = rows(&["/Volumes/tokyo/Photos/2024/a.jpg", "/Volumes/tokyo/Photos/2025/b.jpg", "/Volumes/tokyo-1/old/c.jpg", "/Volumes/東京 NAS/d.jpg"]);+ assert_eq!(+ r,+ vec![+ row("tokyo", 2, 0),+ row("Photos", 2, 0),+ row("2024", 1, 1),+ row("2025", 1, 1),+ row("tokyo-1", 1, 0),+ row("old", 1, 1),+ row("東京 NAS", 1, 1)+ ]+ );+ let tree = library(&["/Volumes/tokyo/Photos/a.jpg"]).folder_tree();+ assert_eq!((tree[0].path.as_str(), tree[0].volume), ("/Volumes/tokyo", true), "choosing the share shows everything on it");+}++#[test]+fn shares_the_other_systems_mount_are_volumes_too() {+ // Linux desktops: gvfs mounts per user, with the server and share in the mount's name+ let gvfs = "/run/user/1000/gvfs/smb-share:server=tokyo,share=photos";+ let r = rows(&[&format!("{gvfs}/2024/a.jpg"), "/run/user/1000/gvfs/sftp:host=nas/b.jpg"]);+ assert_eq!(r, vec![row("photos on tokyo", 1, 0), row("2024", 1, 1), row("sftp:host=nas", 1, 1)]);+ // NFS automounts: Linux /net/<host>, macOS /Network/Servers/<host>+ let r = rows(&["/net/tokyo/export/a.jpg", "/Network/Servers/osaka/vol/b.jpg"]);+ assert_eq!(r, vec![row("osaka", 1, 0), row("vol", 1, 1), row("tokyo", 1, 0), row("export", 1, 1)]);+ // Windows: a share by name or by address, the WSL file system, a mapped drive+ let r = rows(&[r"\\tokyo.local\photos\a.jpg", r"\\192.168.1.5\scans\b.jpg", r"\\wsl$\Ubuntu\home\me\c.jpg", r"Z:\d.jpg"]);+ assert_eq!(+ r,+ vec![row("//192.168.1.5/scans", 1, 1), row("//tokyo.local/photos", 1, 1), row("//wsl$/Ubuntu", 1, 0), row("home/me", 1, 1), row("Z:", 1, 1)]+ );+}++#[test]+fn a_share_that_is_not_mounted_costs_nothing() {+ // the tree is made from the catalog's own records: it never looks at a disk, so a share that+ // is asleep or gone lists (and counts) exactly like one that is there+ let c = library(&["/Volumes/definitely-not-mounted/a/b.jpg", r"\\unreachable.invalid\share\c.jpg"]);+ let tree = c.folder_tree();+ assert_eq!(tree.iter().map(|n| n.count).sum::<usize>(), 2);+}++#[test]+fn a_photo_in_the_root_of_a_disk_counts_for_the_disk() {+ assert_eq!(rows(&["/x.jpg", "/d/y.jpg"]), vec![row("/", 2, 1), row("d", 1, 1)]);+ assert_eq!(rows(&["C:\\x.jpg"]), vec![row("C:", 1, 1)]);+}++#[test]+fn photos_with_no_folder_are_left_out() {+ assert!(rows(&["x.jpg", ""]).is_empty());+}++#[test]+fn folders_are_listed_by_name_ignoring_case() {+ let names: Vec<String> = rows(&["/p/b/1.jpg", "/p/A/2.jpg", "/p/c/3.jpg"]).into_iter().skip(2).map(|r| r.0).collect();+ assert_eq!(names, ["A", "b", "c"]);+}++#[test]+fn absurdly_deep_paths_neither_crash_nor_lose_photos() {+ let deep = format!("/{}/a.jpg", vec!["d"; 5000].join("/"));+ let tree = library(&[&deep]).folder_tree();+ assert_eq!(tree.iter().map(|n| n.count).sum::<usize>(), 1);+ assert!(outline(&tree).len() <= crate::folders::MAX_DEPTH + 2);+}++#[test]+fn choosing_a_folder_shows_what_was_imported_from_it_and_below() {+ let mut c = Catalog::new();+ let trip = add(&mut c, "/pics/trip/a.jpg");+ let day = add(&mut c, "/pics/trip/day1/b.jpg");+ let sibling = add(&mut c, "/pics/trip2/c.jpg"); // shares the name's start, not the folder+ let browsed = add_with(&mut c, "/pics/trip/d.jpg", |p| p.local = true);+ let f = Filter { library_folder: Some("/pics//trip/".into()), ..Default::default() };+ let shown = |id: PhotoId| f.matches(c.photo(id).unwrap(), &c);+ assert!(shown(trip) && shown(day));+ assert!(!shown(sibling), "/pics/trip2 is another folder");+ assert!(!shown(browsed), "browsed photos are not part of the library's folders");+ assert_eq!(f.describe(), "folder /pics//trip/");+}++#[test]+fn recently_deleted_shows_the_deleted_photos_of_the_chosen_folder() {+ let mut c = Catalog::new();+ let gone = add_with(&mut c, "/pics/trip/a.jpg", |p| p.deleted = true);+ let kept = add(&mut c, "/pics/trip/b.jpg");+ let f = Filter { library_folder: Some("/pics/trip".into()), deleted: true, ..Default::default() };+ assert!(f.matches(c.photo(gone).unwrap(), &c));+ assert!(!f.matches(c.photo(kept).unwrap(), &c));+}++#[test]+fn an_empty_folder_choice_is_no_choice() {+ let c = library(&["/pics/a.jpg"]);+ let f = Filter { library_folder: Some(" ".into()), ..Default::default() };+ assert_eq!(c.query(&f, &Sort::default()).len(), 1);+}++#[test]+fn every_row_shows_exactly_as_many_photos_as_it_says() {+ let c = library(&[+ "/Users/me/Pictures/2024/a.jpg",+ "/Users/me/Pictures/2024/b.jpg",+ "/Users/me/Pictures/2025/c.jpg",+ "/Users/me/Pictures/d.jpg",+ "/Volumes/nas/photos/e.jpg",+ "/Volumes/nas/f.jpg",+ "/x.jpg",+ "/a/../b/g.jpg",+ "D:\\Photos\\2024\\h.jpg",+ "d:/Photos/i.jpg",+ "\\\\srv\\s1\\a\\j.jpg",+ "\\\\?\\UNC\\srv\\s2\\k.jpg",+ "/pics/trip/l.jpg",+ "/pics/trip2/m.jpg",+ "/Volumes/tokyo/Photos/2024/n.jpg",+ "/Volumes/tokyo/o.jpg",+ "/run/user/1000/gvfs/smb-share:server=tokyo,share=photos/p.jpg",+ "/net/osaka/export/q.jpg",+ r"\\wsl$\Ubuntu\home\me\r.jpg",+ // odd spellings the tree and the filter must read the same way+ "//server/share/../other/1.jpg",+ "//server/share/ok/2.jpg",+ "//a b//A/f.jpg",+ r"\\wsl$\Ubuntu\..\a\1.jpg",+ // a folder that holds other disks as well as photos of its own+ "/Volumes/1.jpg",+ "/mnt/2.jpg",+ "/mnt/disk/3.jpg",+ ]);+ fn check(c: &Catalog, nodes: &[FolderNode], seen: &mut usize) {+ for n in nodes {+ // the startup volume's row only opens: its path "/" would cover every other disk+ if n.selectable {+ let f = Filter { library_folder: Some(n.path.clone()), ..Default::default() };+ assert_eq!(c.query(&f, &Sort::default()).len(), n.count, "{} ({})", n.name, n.path);+ *seen += 1;+ }+ check(c, &n.children, seen);+ }+ }+ let mut seen = 0;+ check(&c, &c.folder_tree(), &mut seen);+ assert!(seen > 10, "{seen} rows checked");+}++fn find<'a>(nodes: &'a [FolderNode], path: &str) -> Option<&'a FolderNode> {+ nodes.iter().find_map(|n| if n.path == path { Some(n) } else { find(&n.children, path) })+}++#[test]+fn a_row_that_would_cover_other_disks_is_not_offered_for_choosing() {+ let tree = library(&["/Users/me/a.jpg", "/Volumes/1.jpg", "/Volumes/tokyo/x.jpg", "/mnt/2.jpg"]).folder_tree();+ let sel = |p: &str| find(&tree, p).map(|n| n.selectable);+ assert_eq!(sel("/"), Some(false), "the startup disk's path covers every disk");+ assert_eq!(sel("/Volumes"), Some(false), "it holds the tokyo disk");+ assert_eq!(sel("/Volumes/tokyo"), Some(true));+ assert_eq!(sel("/Users/me"), Some(true));+ assert_eq!(sel("/mnt"), Some(true), "no disk is mounted below it in this library");+}++#[test]+fn the_tree_and_the_filter_read_odd_spellings_the_same_way() {+ // `..` cannot climb above a share, and repeated separators between server and share are one+ let tree = library(&["//server/share/../other/1.jpg", "//a b//A/f.jpg"]).folder_tree();+ assert_eq!(outline(&tree), vec![row("//a b/A", 1, 1), row("//server/share", 1, 0), row("other", 1, 1)]);+}++#[test]+fn a_path_that_names_no_folder_chooses_nothing() {+ let c = library(&["/pics/a.jpg", "C:\\b\\c.jpg"]);+ for dot in [".", "./", "a/..", "../.."] {+ let f = Filter { library_folder: Some(dot.into()), ..Default::default() };+ assert_eq!(c.query(&f, &Sort::default()).len(), 0, "{dot:?} is no folder, not everything");+ }+}++#[test]+fn a_folder_is_labelled_by_its_last_two_names() {+ use crate::folders::folder_label;+ assert_eq!(folder_label("/Volumes/tokyo/photos/travel"), "photos/travel");+ assert_eq!(folder_label("/Volumes/tokyo/"), "Volumes/tokyo");+ assert_eq!(folder_label(r"C:\Photos\2024"), "Photos/2024");+ assert_eq!(folder_label("/"), "/");+ assert_eq!(folder_label(""), "");+}++#[test]+fn disk_roots_are_told_from_folders() {+ use crate::folders::{is_disk_root, is_startup_disk};+ for p in ["/", "C:", "C:\\", r"\\?\C:\", r"\\srv\share", "/Volumes/nas", "/mnt/disk", "/net/host"] {+ assert!(is_disk_root(p), "{p}");+ }+ for p in ["/Volumes", "/Users", "C:\\Photos", r"\\srv\share\x", "/Volumes/nas/p", "."] {+ assert!(!is_disk_root(p), "{p}");+ }+ assert!(is_startup_disk("/") && is_startup_disk("//") && !is_startup_disk("/Volumes/nas") && !is_startup_disk("C:"));+}diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rsindex a8a9b448e..338dff699 100644--- a/crates/engine/src/cmd/browse.rs+++ b/crates/engine/src/cmd/browse.rs@@ -251,6 +251,17 @@ pub(crate) fn rename_folder_on_disk(from: &str, to: &str) -> std::result::Result/// After a folder moved from `from` to `to`: a browsed folder at or below it follows.pub(crate) fn follow_folder(s: &mut Session, from: &str, to: &str) {+ // a chosen library folder at or below it follows too (compared the way the filter does, by+ // folder identity, so a differently spelled choice is not widened to the folder itself)+ if let Some(chosen) = s.filter.library_folder.clone() {+ let (ck, fk) = (lightcraft_catalog::query::folder_key(&chosen), lightcraft_catalog::query::folder_key(from));+ if !fk.is_empty()+ && let Some(rest) = ck.strip_prefix(fk.as_str()).filter(|r| r.is_empty() || r.starts_with('/') || fk.ends_with('/'))+ {+ let rest = rest.trim_start_matches('/');+ s.filter.library_folder = Some(if rest.is_empty() { to.to_string() } else { format!("{}/{rest}", to.trim_end_matches(['/', '\\'])) });+ }+ }if let Some(b) = &mut s.browse&& let Ok(rel) = Path::new(&b.path).strip_prefix(from){diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rsindex 57632ea82..688d84b35 100644--- a/crates/engine/src/cmd/library.rs+++ b/crates/engine/src/cmd/library.rs@@ -1,7 +1,7 @@//! Library commands: view source, filter/sort, selection, ratings/flags/labels, rotate, delete,//! metadata, albums, import.-use lightcraft_catalog::{Album, AlbumId, ColorLabel, CopyrightStatus, Flag, GroupBy, Op, PhotoId, Sort, SortKey};+use lightcraft_catalog::{Album, AlbumId, ColorLabel, CopyrightStatus, Filter, Flag, GroupBy, Op, PhotoId, Sort, SortKey};use serde_json::{Value, json};use super::{CommandSpec, always, bad, bool_or, cmd, has_active, has_selection, ok, str_param};@@ -282,7 +282,7 @@ pub fn specs() -> Vec<CommandSpec> {"Filter",[],None,- "partial Filter: {text?, rating?, ratingOp?: atLeast|exactly|atMost, flag?: pick|reject|none|null, label?, kind?, merged?: hdr|panorama|hdrPanorama|any, edited?, date?, keyword?, person?, camera?}",+ "partial Filter: {text?, rating?, ratingOp?: atLeast|exactly|atMost, flag?: pick|reject|none|null, label?, kind?, merged?: hdr|panorama|hdrPanorama|any, edited?, date?, libraryFolder?: a path from library.folders, keyword?, person?, camera?}",always,|s, p| {let mut v = serde_json::to_value(&s.filter).unwrap_or_default();@@ -291,6 +291,54 @@ pub fn specs() -> Vec<CommandSpec> {Ok(json!({"count": s.visible().len()}))}),+ cmd!(+ query "library.folders",+ "Library Folders",+ [],+ None,+ "{} → [{name, path, count, own, children}] the folders the library's photos were imported from, with photo counts (subfolders included in `count`); pass a `path` to library.filter as `libraryFolder`",+ always,+ |s, _| Ok(serde_json::to_value(s.catalog.folder_tree()).unwrap_or_default())+ ),+ cmd!(+ "library.removeFolder",+ "Remove Folder from Library",+ [],+ None,+ "{path, disk?: bool} — move the library photos imported from this folder (and the folders inside it) to Recently Deleted; one undo step, no file is touched. A whole disk or share (`/Volumes/nas`, `C:\\`, `\\\\srv\\share`) goes only with `disk: true`, the startup disk never → {removed}",+ always,+ |s, p| {+ const C: &str = "library.removeFolder";+ let path = str_param(p, "path").map(str::trim).filter(|d| !d.is_empty()).ok_or_else(|| bad(C, "missing `path`"))?;+ if lightcraft_catalog::query::folder_key(path).is_empty() {+ return Err(bad(C, format!("{path}: not a folder")));+ }+ if lightcraft_catalog::folders::is_startup_disk(path) {+ return Err(bad(C, "choose a folder, not the whole startup disk"));+ }+ if lightcraft_catalog::folders::is_disk_root(path) && !bool_or(p, "disk", false) {+ return Err(bad(C, format!("{path} is a whole disk or share: pass `disk: true` to remove everything on it")));+ }+ let f = Filter { library_folder: Some(path.to_string()), ..Default::default() };+ let ids = s.catalog.query(&f, &Sort::default());+ if ids.is_empty() {+ return Err(bad(C, format!("{path}: no photo in the library was imported from it")));+ }+ let disks: std::collections::BTreeSet<String> =+ ids.iter().filter_map(|id| s.catalog.photo(*id)).filter_map(|p| lightcraft_catalog::folders::volume_of(p)).collect();+ if disks.len() > 1 && !bool_or(p, "disk", false) {+ return Err(bad(C, format!("{path} holds photos of {} disks: pass `disk: true` to remove them all", disks.len())));+ }+ let ops = ids.iter().map(|id| Op::SetDeleted { id: *id, deleted: true }).collect();+ s.commit("Remove Folder from Library", Op::Batch { ops })?;+ if s.filter.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) {+ s.filter.library_folder = None;+ }+ let vis = s.visible_cloned();+ s.selection = vis.first().map(|f| Selection::single(*f)).unwrap_or_default();+ Ok(json!({"removed": ids.len()}))+ }+ ),cmd!("library.clearFilter", "Clear Filters", ["View"], None, "{}", always, |s, _| {s.filter = Default::default();Ok(json!({"count": s.visible().len()}))diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex ec39222a4..cbbbbd639 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -709,6 +709,8 @@ mod tests_color;#[cfg(test)]mod tests_export;#[cfg(test)]+mod tests_folders;+#[cfg(test)]mod tests_forget_local;#[cfg(test)]mod tests_import;diff --git a/crates/engine/src/tests_folders.rs b/crates/engine/src/tests_folders.rsnew file mode 100644index 000000000..887870b59--- /dev/null+++ b/crates/engine/src/tests_folders.rs@@ -0,0 +1,232 @@+//! Exploring the library by folder: `library.folders` lists where the imported photos live and+//! `library.filter {libraryFolder}` shows one folder's photos (see `lightcraft_catalog::folders`);+//! `library.removeFolder` takes a folder's photos out of the library.+//!+//! * Given photos imported from two folders, an agent can list them with counts, then choose one+//! and see exactly its photos; the filter shows as a chip that clears just that choice.+//! * A path that is not a library folder shows nothing rather than everything.+//! * Removing a folder from the library moves its photos to Recently Deleted (one undo step) and+//! leaves every file where it is.+//! * Renaming or moving a folder on disk keeps the chosen folder chosen.++use lightcraft_catalog::{Op, Photo, Source};+use serde_json::json;++use crate::{LibrarySource, Session, filter_chips};++fn add(s: &mut Session, path: &str) {+ let id = s.catalog.alloc_photo_id();+ let p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00");+ s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();+}++/// A scratch folder that goes away with the test, however it ends.+struct Scratch(std::path::PathBuf);++impl Scratch {+ fn new(tag: &str) -> Scratch {+ let dir = std::env::temp_dir().join(format!("lc-folders-{tag}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ Scratch(dir)+ }+ fn path(&self, rel: &str) -> String {+ self.0.join(rel).to_string_lossy().to_string()+ }+}++impl Drop for Scratch {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}++fn session() -> Session {+ let mut s = Session::new();+ for path in ["/pics/trip/a.jpg", "/pics/trip/b.jpg", "/pics/home/c.jpg"] {+ add(&mut s, path);+ }+ s+}++#[test]+fn the_folders_command_lists_where_the_photos_were_imported_from() {+ let mut s = session();+ let r = s.execute("library.folders", &json!({})).unwrap();+ assert_eq!((r[0]["name"].as_str(), r[0]["volume"].as_bool(), r[0]["count"].as_u64()), (Some("/"), Some(true), Some(3)));+ let pics = &r[0]["children"][0];+ assert_eq!(pics["name"], "pics");+ let kids: Vec<(&str, u64)> =+ pics["children"].as_array().unwrap().iter().map(|c| (c["name"].as_str().unwrap(), c["count"].as_u64().unwrap())).collect();+ assert_eq!(kids, [("home", 1), ("trip", 2)]);+}++#[test]+fn choosing_a_folder_shows_its_photos_and_a_chip_that_clears_it() {+ let mut s = session();+ assert_eq!(s.visible().len(), 3);+ let r = s.execute("library.filter", &json!({"libraryFolder": "/pics/trip"})).unwrap();+ assert_eq!(r["count"], 2);+ let chips = filter_chips(&s.filter, &s.catalog);+ assert_eq!(chips.len(), 1);+ assert_eq!(chips[0].label, "Folder: pics/trip", "two names, so two folders called trip are told apart");+ s.execute("library.filter", &chips[0].clear).unwrap();+ assert_eq!(s.visible().len(), 3, "clearing the chip shows everything again");+}++#[test]+fn a_path_that_is_not_a_library_folder_shows_nothing() {+ let mut s = session();+ let r = s.execute("library.filter", &json!({"libraryFolder": "/elsewhere"})).unwrap();+ assert_eq!(r["count"], 0);+}++#[test]+fn removing_a_folder_moves_its_photos_to_recently_deleted_and_undo_brings_them_back() {+ let mut s = session();+ let r = s.execute("library.removeFolder", &json!({"path": "/pics//trip/"})).unwrap();+ assert_eq!(r["removed"], 2);+ assert_eq!(s.visible().len(), 1, "only /pics/home is left");+ let tree = s.execute("library.folders", &json!({})).unwrap();+ assert_eq!(tree[0]["count"], 1);+ s.source = LibrarySource::RecentlyDeleted;+ assert_eq!(s.visible().len(), 2, "they wait in Recently Deleted");+ s.source = LibrarySource::All;+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.visible().len(), 3, "one undo step");+}++#[test]+fn removing_a_folder_that_holds_nothing_or_a_whole_disk_is_refused() {+ let mut s = session();+ assert!(s.execute("library.removeFolder", &json!({"path": "/elsewhere"})).is_err());+ assert!(s.execute("library.removeFolder", &json!({"path": "/"})).is_err(), "choose a folder, not everything");+ assert!(s.execute("library.removeFolder", &json!({"path": " "})).is_err());+ assert!(s.execute("library.removeFolder", &json!({})).is_err());+ assert_eq!(s.visible().len(), 3, "nothing changed");+}++#[test]+fn removing_a_folder_leaves_browsed_and_already_deleted_photos_alone() {+ let mut s = session();+ for (path, local, deleted) in [("/pics/trip/browsed.jpg", true, false), ("/pics/trip/gone.jpg", false, true)] {+ let id = s.catalog.alloc_photo_id();+ let mut p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00");+ (p.local, p.deleted) = (local, deleted);+ s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();+ }+ let r = s.execute("library.removeFolder", &json!({"path": "/pics/trip"})).unwrap();+ assert_eq!(r["removed"], 2, "only the two library photos of the folder");+ let state: Vec<(bool, bool)> = s.catalog.photos().filter(|p| p.local || p.deleted).map(|p| (p.local, p.deleted)).collect();+ assert!(state.contains(&(true, false)) && state.contains(&(false, true)), "browsed stays browsed, the old deletion stays: {state:?}");+}++#[test]+fn removing_the_folder_that_is_chosen_clears_the_choice_but_a_parent_stays() {+ let mut s = session();+ s.execute("library.filter", &json!({"libraryFolder": "/pics/trip"})).unwrap();+ s.execute("library.removeFolder", &json!({"path": "/pics/trip"})).unwrap();+ assert_eq!(s.filter.library_folder, None, "no empty grid under a chip for a folder that is gone");+ let mut s = session();+ s.execute("library.filter", &json!({"libraryFolder": "/pics"})).unwrap();+ s.execute("library.removeFolder", &json!({"path": "/pics/trip"})).unwrap();+ assert_eq!(s.filter.library_folder.as_deref(), Some("/pics"));+}++#[test]+fn a_path_that_names_no_folder_removes_nothing() {+ let mut s = session();+ for path in [".", "./", "a/..", "../..", "x/../.."] {+ assert!(s.execute("library.removeFolder", &json!({"path": path})).is_err(), "{path:?}");+ }+ assert_eq!(s.visible().len(), 3);+}++#[test]+fn a_whole_disk_goes_only_when_asked_for_by_name_and_never_the_startup_disk() {+ let mut s = Session::new();+ for p in ["/Volumes/nas/a/1.jpg", "/Volumes/nas/2.jpg", "/Users/me/3.jpg", r"C:\x\4.jpg", r"\\srv\share\5.jpg"] {+ add(&mut s, p);+ }+ for path in ["/Volumes/nas", "C:", "C:\\", r"\\?\C:\", "C:\\..", r"\\srv\share"] {+ assert!(s.execute("library.removeFolder", &json!({"path": path})).is_err(), "{path:?} is a whole disk");+ }+ for path in ["/", "//"] {+ assert!(s.execute("library.removeFolder", &json!({"path": path, "disk": true})).is_err(), "{path:?}: never the startup disk");+ }+ assert_eq!(s.visible().len(), 5, "nothing changed");+ let r = s.execute("library.removeFolder", &json!({"path": "/Volumes/nas", "disk": true})).unwrap();+ assert_eq!(r["removed"], 2, "everything on the nas, nothing elsewhere");+ assert_eq!(s.visible().len(), 3);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.visible().len(), 5);+}++#[test]+fn a_folder_that_spans_several_disks_is_removed_only_when_asked_for_by_name() {+ let mut s = Session::new();+ for p in ["/Volumes/nas/a/1.jpg", "/Volumes/tokyo/2.jpg", "/Volumes/3.jpg"] {+ add(&mut s, p);+ }+ assert!(s.execute("library.removeFolder", &json!({"path": "/Volumes"})).is_err(), "it would take two disks' photos at once");+ assert_eq!(s.visible().len(), 3);+ let r = s.execute("library.removeFolder", &json!({"path": "/Volumes", "disk": true})).unwrap();+ assert_eq!(r["removed"], 3);+}++#[test]+fn the_folder_filter_takes_only_a_text_path() {+ let mut s = session();+ assert!(s.execute("library.filter", &json!({"libraryFolder": 5})).is_err());+ assert_eq!(s.filter.library_folder, None, "refused, nothing changed");+ s.execute("library.filter", &json!({"libraryFolder": " "})).unwrap();+ assert_eq!(s.visible().len(), 3, "a blank path is no choice");+ s.execute("library.filter", &json!({"libraryFolder": "."})).unwrap();+ assert_eq!(s.visible().len(), 0, "a path that names no folder shows nothing, not everything");+}++#[test]+fn a_renamed_folder_stays_the_chosen_one_and_undo_follows_it_back() {+ let dir = Scratch::new("rename");+ std::fs::create_dir_all(dir.0.join("trip/day1")).unwrap();+ let (trip, renamed) = (dir.path("trip"), dir.path("holiday"));+ let mut s = Session::new();+ add(&mut s, &format!("{trip}/a.jpg"));+ add(&mut s, &format!("{trip}/day1/b.jpg"));+ s.execute("library.filter", &json!({"libraryFolder": trip})).unwrap();+ assert_eq!(s.visible().len(), 2);+ s.execute("folder.rename", &json!({"path": trip, "name": "holiday"})).unwrap();+ assert_eq!(s.filter.library_folder.as_deref(), Some(renamed.as_str()), "the choice follows the folder");+ assert_eq!(s.visible().len(), 2, "and still shows its photos");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.filter.library_folder.as_deref(), Some(trip.as_str()));+ assert_eq!(s.visible().len(), 2);+}++#[test]+fn a_moved_folder_keeps_a_chosen_subfolder_chosen() {+ let dir = Scratch::new("move");+ std::fs::create_dir_all(dir.0.join("trip/day1")).unwrap();+ std::fs::create_dir_all(dir.0.join("archive")).unwrap();+ let (day1, moved) = (dir.path("trip/day1"), dir.path("archive/trip/day1"));+ let mut s = Session::new();+ add(&mut s, &format!("{day1}/b.jpg"));+ s.execute("library.filter", &json!({"libraryFolder": day1})).unwrap();+ s.execute("folder.move", &json!({"path": dir.path("trip"), "into": dir.path("archive")})).unwrap();+ assert_eq!(s.filter.library_folder.as_deref(), Some(moved.as_str()), "the subfolder follows its parent");+ assert_eq!(s.visible().len(), 1);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.filter.library_folder.as_deref(), Some(day1.as_str()));+}++#[test]+fn following_a_folder_reads_both_spellings_the_same_way() {+ // the choice was typed with a `..` in it; the folder that moved was not+ let mut s = Session::new();+ s.filter.library_folder = Some("/a/x/../b/sub".into());+ crate::cmd::browse::follow_folder(&mut s, "/a/b", "/a/c");+ assert_eq!(s.filter.library_folder.as_deref(), Some("/a/c/sub"), "a subfolder stays a subfolder, never widens to its parent");+ s.filter.library_folder = Some("/elsewhere/b".into());+ crate::cmd::browse::follow_folder(&mut s, "/a/b", "/a/c");+ assert_eq!(s.filter.library_folder.as_deref(), Some("/elsewhere/b"), "other folders are left alone");+}diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rsindex 757adfe94..1b0f0ca42 100644--- a/crates/engine/src/view.rs+++ b/crates/engine/src/view.rs@@ -173,6 +173,11 @@ pub fn filter_chips(f: &Filter, cat: &Catalog) -> Vec<FilterChip> {if let Some(d) = &f.date {add(format!("Date: {}", date_label(d)), json!({"date": Null}));}+ if let Some(d) = f.library_folder.as_deref().filter(|d| !d.trim().is_empty()) {+ // the last two names, so two folders called "Pictures" are told apart+ let name = lightcraft_catalog::folders::folder_label(d);+ add(format!("Folder: {name}"), json!({"libraryFolder": Null}));+ }if let Some(d) = &f.imported {add(format!("Imported: {}", date_label(d)), json!({"imported": Null}));}diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.jsonindex 1944d7b6a..5a7d7a115 100644--- a/crates/ui-egui/locales/ja-formats.json+++ b/crates/ui-egui/locales/ja-formats.json@@ -118,5 +118,6 @@"{verb} {n} Photo{}": "{n}枚を{verb}{:.0}","{weekday}, {day}": "{day}日({weekday})","{weekday}, {day} {month} {year}": "{year}年{month}月{day}日({weekday})",- "{year}": "{year}年"+ "{year}": "{year}年",+ "Remove “{name}” and its {count} photo{} from the library?": "「{name}」と写真{count}枚をライブラリから除去しますか?{:.0}"}diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.jsonindex ca2089af2..d2376d647 100644--- a/crates/ui-egui/locales/ja.json+++ b/crates/ui-egui/locales/ja.json@@ -1029,5 +1029,13 @@"Friday": "金曜日","Saturday": "土曜日","Sunday": "日曜日",- "Unknown Date": "日付不明"+ "Unknown Date": "日付不明",+ "Remove Folder from Library": "フォルダをライブラリから除去",+ "Remove from Library…": "ライブラリから除去…",+ "This Computer": "このコンピュータ",+ "includes the folders inside it": "内側のフォルダを含む",+ "They move to Recently Deleted and can be restored; no file on disk is touched.": "「最近削除した写真」に移動し、復元できます。ディスク上のファイルには手を加えません",+ "Moves the photos imported from this folder to Recently Deleted; no file is touched": "このフォルダから読み込んだ写真を「最近削除した写真」に移動します。ファイルには手を加えません",+ "Remove Disk from Library…": "ディスクをライブラリから除去…",+ "Moves every photo imported from this disk to Recently Deleted; no file is touched": "このディスクから読み込んだすべての写真を「最近削除した写真」に移動します。ファイルには手を加えません"}diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.jsonindex 50b0f2abf..596056875 100644--- a/crates/ui-egui/locales/pt-br-formats.json+++ b/crates/ui-egui/locales/pt-br-formats.json@@ -61,6 +61,7 @@"Reading photos… {done} of {total}": "Lendo fotos… {done} de {total}","Reading photos… {} of {}": "Lendo fotos… {} de {}","Redo {}": "Refazer {}",+ "Remove “{name}” and its {count} photo{} from the library?": "Remover “{name}” e {count} foto{} da biblioteca?","Remove “{}” from Favorites": "Remover “{}” dos favoritos","Rename {n} Photos…": "Renomear {n} fotos…","Rename “{name}”": "Renomear “{name}”",diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.jsonindex 503b2edac..3b2b3b8d4 100644--- a/crates/ui-egui/locales/pt-br.json+++ b/crates/ui-egui/locales/pt-br.json@@ -681,6 +681,8 @@"Move to": "Mover para","Move to Group": "Mover para grupo","Move: the files are moved to the folder below; each original (and its XMP sidecar) is removed from the source only after its copy is verified. Duplicates and files that fail stay where they are.": "Mover: os arquivos são movidos para a pasta abaixo; cada original (e seu sidecar XMP) é removido da origem somente após a cópia ser verificada. Duplicatas e arquivos que falham permanecem onde estão.",+ "Moves every photo imported from this disk to Recently Deleted; no file is touched": "Move todas as fotos importadas deste disco para Excluídos recentemente; nenhum arquivo é alterado",+ "Moves the photos imported from this folder to Recently Deleted; no file is touched": "Move as fotos importadas desta pasta para Excluídos recentemente; nenhum arquivo é alterado","Muted": "Suave","Muted Film": "Filme suave","My Photos": "Minhas fotos",@@ -900,8 +902,11 @@"Remove (H)": "Remover (H)","Remove CA": "Remover AC","Remove Chromatic Aberration": "Remover aberração cromática",+ "Remove Disk from Library…": "Remover disco da biblioteca…",+ "Remove Folder from Library": "Remover pasta da biblioteca","Remove from Album": "Remover do álbum","Remove from Favorites": "Remover dos favoritos",+ "Remove from Library…": "Remover da biblioteca…","Remove from Local": "Remover de Local","Remove from Photo": "Remover da foto","Remove from Selected Photos": "Remover das fotos selecionadas",@@ -1147,7 +1152,9 @@"The photo has these settings": "A foto tem estas configurações","Theme": "Tema","They can be restored from Recently Deleted until it is emptied.": "Elas podem ser restauradas em Excluídos recentemente até que ele seja esvaziado.",+ "They move to Recently Deleted and can be restored; no file on disk is touched.": "Elas vão para Excluídos recentemente e podem ser restauradas; nenhum arquivo no disco é alterado.","Thirds": "Terços",+ "This Computer": "Este computador","This folder is not available (drive disconnected?). Smart previews are not built or used until it is back or you choose another folder.": "Esta pasta não está disponível (unidade desconectada?). As pré-visualizações inteligentes não são geradas nem usadas até ela voltar ou você escolher outra pasta.","This photo can't be opened": "Não foi possível abrir esta foto","Threshold": "Limite",@@ -1251,6 +1258,7 @@"Zoom to page level": "Zoom no nível da página","and": "e","comma, separated": "separado por vírgulas",+ "includes the folders inside it": "inclui as pastas dentro dela","memory only": "somente memória","none": "nenhum","not available here": "não disponível aqui",diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.jsonindex c3713eb18..e4ae48f4b 100644--- a/crates/ui-egui/locales/zh-hans-formats.json+++ b/crates/ui-egui/locales/zh-hans-formats.json@@ -118,5 +118,6 @@"{month}": "{month}月","{month} {year}": "{year}年{month}月","{weekday}, {day}": "{day}日 {weekday}",- "{weekday}, {day} {month} {year}": "{year}年{month}月{day}日 {weekday}"+ "{weekday}, {day} {month} {year}": "{year}年{month}月{day}日 {weekday}",+ "Remove “{name}” and its {count} photo{} from the library?": "要将“{name}”及其 {count} 张照片从图库中移除吗?{:.0}"}diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.jsonindex 2090461a4..9f411f3cc 100644--- a/crates/ui-egui/locales/zh-hans.json+++ b/crates/ui-egui/locales/zh-hans.json@@ -1246,5 +1246,13 @@"this photo": "这张照片","日本語": "日本語","繁體中文(台灣)": "繁體中文(台灣)",- "In Recently Deleted": "在“最近删除”中"+ "In Recently Deleted": "在“最近删除”中",+ "Remove Folder from Library": "从图库中移除文件夹",+ "Remove from Library…": "从图库中移除…",+ "This Computer": "此电脑",+ "includes the folders inside it": "包含其中的文件夹",+ "They move to Recently Deleted and can be restored; no file on disk is touched.": "它们会移到“最近删除”,可以恢复;磁盘上的文件不会被改动。",+ "Moves the photos imported from this folder to Recently Deleted; no file is touched": "将从此文件夹导入的照片移到“最近删除”;不会改动任何文件",+ "Remove Disk from Library…": "从图库中移除磁盘…",+ "Moves every photo imported from this disk to Recently Deleted; no file is touched": "将从此磁盘导入的所有照片移到“最近删除”;不会改动任何文件"}diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.jsonindex 816936c0f..1c1266c00 100644--- a/crates/ui-egui/locales/zh-hant-formats.json+++ b/crates/ui-egui/locales/zh-hant-formats.json@@ -118,5 +118,6 @@"… and {more} more": "…以及另外 {more} 個"," ({} in Recently Deleted)": "(其中 {} 張在「最近刪除」中)","Already in the library: {} photo{} selected in All Photos": "已在照片庫中:已在「所有照片」中選取 {} 張照片{:.0}",- "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "已在照片庫的「最近刪除」中:已選取 {} 張照片{:.0} · 按右鍵 ▸ 還原,或永久刪除後重新匯入"+ "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "已在照片庫的「最近刪除」中:已選取 {} 張照片{:.0} · 按右鍵 ▸ 還原,或永久刪除後重新匯入",+ "Remove “{name}” and its {count} photo{} from the library?": "要將「{name}」及其 {count} 張照片從照片庫移除嗎?{:.0}"}diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.jsonindex db538f485..863de2db1 100644--- a/crates/ui-egui/locales/zh-hant.json+++ b/crates/ui-egui/locales/zh-hant.json@@ -1246,5 +1246,13 @@"this photo": "這張照片","日本語": "日本語","繁體中文(台灣)": "繁體中文(台灣)",- "In Recently Deleted": "在「最近刪除」中"+ "In Recently Deleted": "在「最近刪除」中",+ "Remove Folder from Library": "從照片庫移除資料夾",+ "Remove from Library…": "從照片庫移除…",+ "This Computer": "這部電腦",+ "includes the folders inside it": "包含其中的資料夾",+ "They move to Recently Deleted and can be restored; no file on disk is touched.": "它們會移至「最近刪除」,可以還原;磁碟上的檔案不會被更動。",+ "Moves the photos imported from this folder to Recently Deleted; no file is touched": "將從此資料夾匯入的照片移至「最近刪除」;不會更動任何檔案",+ "Remove Disk from Library…": "從照片庫移除磁碟…",+ "Moves every photo imported from this disk to Recently Deleted; no file is touched": "將從此磁碟匯入的所有照片移至「最近刪除」;不會更動任何檔案"}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex b7f4d6d6d..a0a3cec1f 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -890,6 +890,7 @@ mod drop_tests {#[derive(Default)]pub struct Caches {keyword_tree: Option<(u64, std::sync::Arc<Vec<lightcraft_catalog::KeywordNode>>)>,+ folder_tree: Option<(u64, std::sync::Arc<Vec<lightcraft_catalog::FolderNode>>)>,people: Option<(u64, lightcraft_catalog::Filter, std::sync::Arc<Vec<lightcraft_catalog::Person>>)>,suggestions: Option<(u64, std::sync::Arc<Vec<String>>)>,counts: Option<(u64, LibraryCounts)>,@@ -926,6 +927,17 @@ pub(crate) fn key_of(parts: impl std::hash::Hash) -> u64 {}impl Caches {+ /// The folders the library's photos were imported from.+ pub fn folder_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc<Vec<lightcraft_catalog::FolderNode>> {+ match &self.folder_tree {+ Some((r, t)) if *r == cat.revision => t.clone(),+ _ => {+ let t = std::sync::Arc::new(cat.folder_tree());+ self.folder_tree = Some((cat.revision, t.clone()));+ t+ }+ }+ }/// The library's keyword tree.pub fn keyword_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc<Vec<lightcraft_catalog::KeywordNode>> {match &self.keyword_tree {diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rsindex 91ffb1c99..cfcc476fa 100644--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@ -97,6 +97,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {Dialog::Merge { opts } => opts.title(),Dialog::Settings { .. } => "Settings",Dialog::ConfirmDelete { .. } => "Delete Photos",+ Dialog::RemoveFolder { .. } => "Remove Folder from Library",Dialog::SamModel { .. } => "Download the SAM 3 Model?",Dialog::About => "About LightCraft",Dialog::Shortcuts => "Keyboard Shortcuts",@@ -710,6 +711,19 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {ui.label(crate::i18n::tr_format!("Move {what} to Recently Deleted?", what = what));ui.label(egui::RichText::new(crate::i18n::tr("They can be restored from Recently Deleted until it is emptied.")).color(t.text_dim));}+ Dialog::RemoveFolder { name, count, path, .. } => {+ ui.label(crate::i18n::tr_format!(+ "Remove “{name}” and its {count} photo{} from the library?",+ if *count == 1 { "" } else { "s" },+ name = name,+ count = count+ ));+ ui.label(egui::RichText::new(path.as_str()).color(t.text_dim));+ ui.label(+ egui::RichText::new(crate::i18n::tr("They move to Recently Deleted and can be restored; no file on disk is touched."))+ .color(t.text_dim),+ );+ }Dialog::About => {ui.set_min_width(680.0);let tab_id = egui::Id::new("about_tab");@@ -817,6 +831,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {}Dialog::Merge { .. } => "Merge",Dialog::ConfirmDelete { .. } => "Delete",+ Dialog::RemoveFolder { .. } => "Remove",Dialog::SamModel { then: Some(_), .. } if sam_installed => "Continue",Dialog::SamModel { .. } if sam_installed || sam_running || sam_nowhere => "",Dialog::SamModel { error, .. } if error.is_some() || sam_failed => "Try Again",@@ -1030,6 +1045,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_jsoDialog::Merge { opts } => crate::merge::start_final(app, opts),Dialog::Import { opts } => crate::import::start(app, opts),Dialog::ConfirmDelete { .. } => app.run("photo.delete", json!({})),+ Dialog::RemoveFolder { path, disk, .. } => app.run("library.removeFolder", json!({"path": path, "disk": disk})),Dialog::About | Dialog::Shortcuts | Dialog::Settings { .. } => Ok(serde_json::Value::Null),}}diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rsindex f69b487f3..884d346a0 100644--- a/crates/ui-egui/src/panels/left.rs+++ b/crates/ui-egui/src/panels/left.rs@@ -1,7 +1,7 @@//! The left "My Photos" panel: library sources, albums tree, and date groups.use egui::{Align2, Rect, Sense, pos2, vec2};-use lightcraft_catalog::{Album, AlbumId, KeywordNode};+use lightcraft_catalog::{Album, AlbumId, FolderNode, KeywordNode};use lightcraft_engine::LibrarySource;use serde_json::json;@@ -19,14 +19,30 @@ fn row(count: Option<usize>,selected: bool,indent: f32,+) -> egui::Response {+ row_named(app, ui, id, icon, label, None, count, selected, indent)+}++/// [`row`] whose spoken name is `spoken` when the painted `label` is a shortened form of it.+fn row_named(+ app: &mut LightcraftApp,+ ui: &mut egui::Ui,+ id: &str,+ icon: Icon,+ label: &str,+ spoken: Option<&str>,+ count: Option<usize>,+ selected: bool,+ indent: f32,) -> egui::Response {let label = if matches!(id, "all" | "recentlyAdded" | "picks" | "missing" | "recentlyDeleted") { crate::i18n::tr(label) } else { label };let t = Tokens::get(ui.ctx());let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 29.0), Sense::click());register(ui.ctx(), format!("source:{id}"), r);+ let said = spoken.unwrap_or(label);let name = match count {- Some(n) => crate::i18n::tr_format!("{label}, {n} photos", label = label, n = n),- None => label.to_string(),+ Some(n) => crate::i18n::tr_format!("{label}, {n} photos", label = said, n = n),+ None => said.to_string(),};resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &name));let inner = r.shrink2(vec2(8.0, 0.0));@@ -158,6 +174,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {}}}+ folders_section(app, ui);keywords_section(app, ui);ui.add_space(10.0);if row(app, ui, "recentlyDeleted", Icon::Trash, "Recently Deleted", Some(deleted), src == LibrarySource::RecentlyDeleted, 0.0).clicked() {@@ -715,6 +732,199 @@ fn is_within(app: &LightcraftApp, id: lightcraft_catalog::AlbumId, ancestor: ligfalse}+/// "Folders": where on disk the library's photos were imported from, with photo counts (see+/// `lightcraft_catalog::folders`). A click shows the photos imported from that folder and the+/// folders inside it, the triangle opens a level. Only folders holding imported photos are+/// listed; every folder on disk is under Local.+fn folders_section(app: &mut LightcraftApp, ui: &mut egui::Ui) {+ let tree = app.caches.folder_tree(&app.session.catalog);+ if tree.is_empty() {+ return;+ }+ ui.add_space(10.0);+ if sidebar_section_header(app, ui, "folders", "Folders").1 {+ reveal_chosen(app, ui, &tree);+ folder_rows(app, ui, &tree, 0.0);+ }+}++/// `text` shortened to fit `max` (as `width` measures it): leading folders drop first+/// (`Users/me/Pictures/Lightroom` → `…/Pictures/Lightroom`) so the end of a path, which says the+/// most, stays; a single name still too long loses its end (`2024-06-12 Tri…`: folders tend to+/// differ at the start). Cuts fall on characters. The result is never empty.+fn elide_head(text: &str, max: f32, width: impl Fn(&str) -> f32) -> String {+ if width(text) <= max {+ return text.to_string();+ }+ let mut rest = text;+ while let Some(i) = rest.find('/') {+ rest = rest.get(i + 1..).unwrap_or("");+ let cand = format!("…/{rest}");+ if width(&cand) <= max {+ return cand;+ }+ }+ let n = rest.chars().count();+ for keep in (1..n).rev() {+ let cand: String = rest.chars().take(keep).chain(std::iter::once('…')).collect();+ if width(&cand) <= max {+ return cand;+ }+ }+ "…".to_string()+}++/// Whenever the chosen folder changes (a click, an agent, a rename or its undo), open the rows+/// above it so it is on screen; folding one by hand afterwards sticks until the choice changes.+fn reveal_chosen(app: &LightcraftApp, ui: &egui::Ui, tree: &[FolderNode]) {+ let chosen = app.session.filter.library_folder.clone().filter(|c| !lightcraft_catalog::query::folder_key(c).is_empty());+ let seen = egui::Id::new("libfolder-revealed");+ let now = chosen.as_deref().map(lightcraft_catalog::query::folder_key);+ if ui.data(|d| d.get_temp::<Option<String>>(seen)) == Some(now.clone()) {+ return;+ }+ ui.data_mut(|d| d.insert_temp(seen, now));+ let Some(chosen) = chosen else { return };+ fn open_above(ui: &egui::Ui, nodes: &[FolderNode], chosen: &str) {+ for n in nodes {+ if lightcraft_catalog::query::folder_within(chosen, &n.path) && !same_folder(chosen, &n.path) {+ let key = lightcraft_catalog::query::folder_key(&n.path);+ ui.data_mut(|d| d.insert_temp(egui::Id::new(("libfolder-open", key)), true));+ open_above(ui, &n.children, chosen);+ }+ }+ }+ open_above(ui, tree, &chosen);+}++fn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[FolderNode], indent: f32) {+ let t = Tokens::get(ui.ctx());+ for n in nodes {+ let key = lightcraft_catalog::query::folder_key(&n.path);+ let open_id = egui::Id::new(("libfolder-open", key.clone()));+ // a disk starts open: its folders are what the section is for+ let mut open: bool = ui.data(|d| d.get_temp(open_id)).unwrap_or(n.volume);+ // a row whose path would cover other disks' photos too only opens and closes+ let selectable = n.selectable;+ let sel = selectable && app.session.filter.library_folder.as_deref().is_some_and(|f| same_folder(f, &n.path));+ let name = if selectable { n.name.clone() } else { crate::i18n::tr("This Computer").to_string() };+ // room for the name: between the icon and the count+ let font = t.font(13.5);+ let count_w =+ if app.ui.show_counts { ui.painter().layout_no_wrap(n.count.to_string(), t.font(12.5), egui::Color32::WHITE).size().x } else { 0.0 };+ let room = ui.available_width() - 42.0 - indent - count_w - 28.0;+ let label = elide_head(&name, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), egui::Color32::WHITE).size().x);+ let resp = row_named(app, ui, &format!("libfolder:{}", n.path), Icon::Folder, &label, Some(&name), Some(n.count), sel, indent);+ let mut toggled = false;+ if !n.children.is_empty() {+ // disclosure triangle left of the icon+ let c = pos2(resp.rect.left() + 10.0 + indent, resp.rect.center().y);+ let tri = Rect::from_center_size(c, vec2(14.0, 14.0));+ let tr = ui.interact(tri, egui::Id::new(("libfolder-tri", key)), Sense::click());+ register(ui.ctx(), format!("libraryFolderToggle:{}", n.path), tri);+ let col = if tr.hovered() { t.text } else { t.text_dim };+ let pts = if open {+ vec![c + vec2(-4.0, -2.0), c + vec2(4.0, -2.0), c + vec2(0.0, 3.0)]+ } else {+ vec![c + vec2(-2.0, -4.0), c + vec2(3.0, 0.0), c + vec2(-2.0, 4.0)]+ };+ ui.painter().add(egui::Shape::convex_polygon(pts, col, egui::Stroke::NONE));+ toggled = tr.clicked();+ // the triangle sits on the row and takes its clicks: the menu opens from it too+ row_menu(app, &tr, n);+ }+ let tip = if n.children.is_empty() { n.path.clone() } else { format!("{} ({})", n.path, crate::i18n::tr("includes the folders inside it")) };+ let resp = resp.on_hover_text(tip);+ if resp.clicked() && !toggled {+ if selectable {+ // the library's folder, not a mix with the Local folder being browsed+ if app.session.source == LibrarySource::Folder {+ let _ = app.run("library.source", json!({"kind": "all"}));+ }+ let v = if sel { serde_json::Value::Null } else { json!(n.path) };+ let _ = app.run("library.filter", json!({"libraryFolder": v}));+ } else {+ toggled = true;+ }+ }+ if toggled {+ open = !open;+ ui.data_mut(|d| d.insert_temp(open_id, open));+ }+ row_menu(app, &resp, n);+ if open && !n.children.is_empty() {+ folder_rows(app, ui, &n.children, indent + 16.0);+ }+ }+}++/// The context menu of a Folders row: a folder's own, a disk's (remove it), none for the+/// startup disk.+fn row_menu(app: &mut LightcraftApp, resp: &egui::Response, n: &FolderNode) {+ if !n.volume {+ folder_menu_for_library(app, resp, n);+ } else if n.path != "/" {+ resp.context_menu(|ui| {+ if ui+ .button(crate::i18n::tr("Remove Disk from Library…"))+ .on_hover_text(crate::i18n::tr("Moves every photo imported from this disk to Recently Deleted; no file is touched"))+ .clicked()+ {+ app.ui.dialog = Some(crate::state::Dialog::RemoveFolder { path: n.path.clone(), name: n.name.clone(), count: n.count, disk: true });+ ui.close();+ }+ });+ }+}++/// The context menu of a folder row: the folder's disk actions (the same as Local's, photos+/// follow) and taking its photos out of the library.+fn folder_menu_for_library(app: &mut LightcraftApp, resp: &egui::Response, n: &FolderNode) {+ let path = n.path.as_str();+ let name = std::path::Path::new(path).file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());+ // what dialogs call it: the last two names, so same-named folders are told apart+ let label = lightcraft_catalog::folders::folder_label(path);+ resp.context_menu(|ui| {+ if ui.button(crate::i18n::tr("Rename Folder…")).clicked() {+ app.ui.dialog = Some(crate::state::Dialog::TextPrompt {+ title: crate::i18n::tr_format!("Rename “{name}”", name = label),+ hint: "Folder name (renamed on disk; its photos follow)".into(),+ value: name.clone(),+ command: "folder.rename".into(),+ params: json!({"path": path}),+ key: "name".into(),+ });+ ui.close();+ }+ if app.services.pick_folder.is_some() && ui.button(crate::i18n::tr("Move Folder To…")).clicked() {+ let into = app.services.pick_folder.as_mut().and_then(|f| f());+ if let Some(into) = into {+ match app.run("folder.move", json!({"path": path, "into": into})) {+ Ok(r) => app.toast(ui.ctx(), format!("Moved; {} photo(s) relinked", r["relinked"])),+ Err(e) => app.toast(ui.ctx(), e),+ }+ }+ ui.close();+ }+ if app.services.reveal.is_some()+ && ui.button(crate::i18n::tr("Show in Finder")).clicked()+ && let Some(f) = app.services.reveal.as_mut()+ {+ let _ = f(path);+ ui.close();+ }+ ui.separator();+ if ui+ .button(crate::i18n::tr("Remove from Library…"))+ .on_hover_text(crate::i18n::tr("Moves the photos imported from this folder to Recently Deleted; no file is touched"))+ .clicked()+ {+ app.ui.dialog = Some(crate::state::Dialog::RemoveFolder { path: path.to_string(), name: label.clone(), count: n.count, disk: false });+ ui.close();+ }+ });+}+/// "Keywords": the library's keyword tree with photo counts (`a|b|c` keywords nest). A click/// filters the grid by the keyword (children included), the triangle opens a level, and the/// context menu renames, merges or deletes the keyword across the library.@@ -786,7 +996,35 @@ fn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[KeywordNode#[cfg(test)]mod tests {- use super::local_places;+ use super::{elide_head, local_places};++ /// Width = characters, so a limit of 12 is "12 characters".+ fn fit(text: &str, max: usize) -> String {+ elide_head(text, max as f32, |s| s.chars().count() as f32)+ }++ #[test]+ fn a_label_that_fits_is_left_alone() {+ assert_eq!(fit("/Users/me/Pictures", 18), "/Users/me/Pictures");+ }++ #[test]+ fn a_long_path_loses_its_leading_folders_not_its_end() {+ assert_eq!(fit("/Users/me/Pictures/Lightroom", 20), "…/Pictures/Lightroom");+ assert_eq!(fit("/Users/me/Pictures/Lightroom", 12), "…/Lightroom");+ }++ #[test]+ fn a_single_name_too_long_is_cut_at_the_end() {+ assert_eq!(fit("2024-summer-holiday", 8), "2024-su…");+ assert_eq!(fit("2024-summer-holiday", 1), "…");+ assert_eq!(fit("2024-summer-holiday", 0), "…");+ }++ #[test]+ fn multibyte_names_are_cut_on_character_boundaries() {+ assert_eq!(fit("/写真/夏休み旅行の記録", 6), "夏休み旅行…");+ }fn names(v: &[(String, String)]) -> Vec<&str> {v.iter().map(|(n, _)| n.as_str()).collect()diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 9d4df8592..ecf412d24 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -533,6 +533,15 @@ pub enum Dialog {ConfirmDelete {count: usize,},+ /// Confirm taking a folder's photos out of the library (`library.removeFolder`).+ RemoveFolder {+ path: String,+ /// What the question calls it (a folder's last two names, a disk's name).+ name: String,+ count: usize,+ /// A whole disk or share (`library.removeFolder` takes it only on request).+ disk: bool,+ },About,Shortcuts,}diff --git a/crates/ui-egui/src/tests_panels.rs b/crates/ui-egui/src/tests_panels.rsindex a289e2ee2..e5134290e 100644--- a/crates/ui-egui/src/tests_panels.rs+++ b/crates/ui-egui/src/tests_panels.rs@@ -199,3 +199,190 @@ fn sidebar_sections_collapse_and_remember_it() {click(&mut h, "icon:albumNew");assert!(!h.app.ui.sidebar_section_collapsed("albums"), "the plus does not fold Albums");}++/// A headless app over a library of file-backed photos that exist only in the catalog.+fn folders_app(paths: &[&str]) -> Headless {+ use lightcraft_catalog::{Op, Photo, Source};+ let mut session = lightcraft_engine::Session::new();+ for path in paths {+ let id = session.catalog.alloc_photo_id();+ let p = Photo::new(id, Source::File { path: (*path).into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00");+ session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();+ }+ let app = LightcraftApp::new(session, Services { png: None, ..Default::default() });+ let mut h = Headless::new(app, [1400.0, 900.0], 1.0);+ let r = h.request("ui.set", json!({"view": "photoGrid", "leftPanel": true}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.settle(SETTLE);+ h+}++fn has(h: &Headless, id: &str) -> bool {+ h.app.widgets.iter().any(|(w, _)| w == id)+}++fn click(h: &mut Headless, id: &str) {+ let r = h.request("ui.clickWidget", json!({"id": id}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ h.step();+}++/// Photos imported from two folders: the sidebar's Folders section lists them, choosing one+/// narrows the grid to its photos, and choosing it again shows everything (like By Date).+#[test]+fn folders_section_lists_where_photos_were_imported_from_and_narrows_the_grid() {+ let mut h = folders_app(&["/pics/trip/a.jpg", "/pics/trip/b.jpg", "/pics/home/c.jpg"]);+ // the disk's row starts open; the folders inside a folder stay folded until it is opened+ assert!(has(&h, "source:libfolder:/pics"), "the Folders section lists the library's folders");+ assert!(!has(&h, "source:libfolder:/pics/trip"));+ click(&mut h, "libraryFolderToggle:/pics");+ assert!(has(&h, "source:libfolder:/pics/trip") && has(&h, "source:libfolder:/pics/home"));+ assert_eq!(h.app.session.visible().len(), 3);+ click(&mut h, "source:libfolder:/pics/trip");+ assert_eq!(h.app.session.visible().len(), 2, "only the photos imported from that folder");+ assert_eq!(h.app.session.filter.library_folder.as_deref(), Some("/pics/trip"));+ click(&mut h, "source:libfolder:/pics/trip");+ assert_eq!(h.app.session.visible().len(), 3, "choosing it again shows everything");+ // the section folds like the others+ click(&mut h, "sidebarSection:folders");+ assert!(!has(&h, "source:libfolder:/pics"), "folded");+ click(&mut h, "sidebarSection:folders");+ assert!(has(&h, "source:libfolder:/pics"));+}++/// Each disk is a row of its own; the startup disk's row only opens and closes, another disk's+/// row also chooses everything on that disk.+#[test]+fn disks_are_rows_of_their_own() {+ let mut h = folders_app(&["/Users/me/a.jpg", "/Volumes/nas/p/b.jpg", "/Volumes/nas/c.jpg"]);+ assert!(has(&h, "source:libfolder:/") && has(&h, "source:libfolder:/Volumes/nas"), "both disks are listed");+ assert!(has(&h, "source:libfolder:/Volumes/nas/p"), "an open disk shows its folders");+ click(&mut h, "source:libfolder:/");+ assert_eq!(h.app.session.filter.library_folder, None, "the startup disk's path would cover every disk");+ assert!(!has(&h, "source:libfolder:/Users/me"), "a click on it folds it instead");+ click(&mut h, "source:libfolder:/");+ assert!(has(&h, "source:libfolder:/Users/me"));+ click(&mut h, "source:libfolder:/Volumes/nas");+ assert_eq!(h.app.session.visible().len(), 2, "everything on the nas");+}++/// Choosing a folder while Local is the source shows the library's folder, not a mix.+#[test]+fn choosing_a_library_folder_leaves_a_local_folder_view() {+ let mut h = folders_app(&["/pics/trip/a.jpg", "/pics/home/b.jpg"]);+ h.app.session.source = lightcraft_engine::LibrarySource::Folder;+ click(&mut h, "libraryFolderToggle:/pics");+ click(&mut h, "source:libfolder:/pics/trip");+ assert_eq!(h.app.session.source, lightcraft_engine::LibrarySource::All);+ assert_eq!(h.app.session.visible().len(), 1);+}++/// Removing a folder from the library asks first, then moves its photos to Recently Deleted.+#[test]+fn removing_a_folder_from_the_library_asks_first() {+ use crate::state::Dialog;+ let mut h = folders_app(&["/pics/trip/a.jpg", "/pics/trip/b.jpg", "/pics/home/c.jpg"]);+ h.app.ui.dialog = Some(Dialog::RemoveFolder { path: "/pics/trip".into(), name: "trip".into(), count: 2, disk: false });+ h.step();+ assert_eq!(h.app.session.visible().len(), 3, "nothing happens until it is confirmed");+ let r = h.request("ui.dialog.confirm", json!({}), T);+ assert_eq!(r["ok"], true, "{r}");+ assert_eq!(h.app.session.visible().len(), 1, "the photos left the library");+ assert_eq!(h.app.ui.dialog, None);+}++fn popup_open(h: &Headless) -> bool {+ egui::Popup::is_any_open(&h.view.ctx)+}++fn right_click(h: &mut Headless, id: &str) {+ let c = widget(h, id).center();+ let r = h.request("ui.click", json!({"x": c.x, "y": c.y, "button": "right"}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ h.step();+}++/// A folder row that holds other disks as well would show their photos too: it only opens.+#[test]+fn a_folder_that_holds_other_disks_only_opens() {+ let mut h = folders_app(&["/Volumes/1.jpg", "/Volumes/tokyo/x.jpg"]);+ assert!(has(&h, "source:libfolder:/Volumes"));+ click(&mut h, "source:libfolder:/Volumes");+ assert_eq!(h.app.session.filter.library_folder, None, "choosing it would show the tokyo disk too");+ click(&mut h, "source:libfolder:/Volumes/tokyo");+ assert_eq!(h.app.session.visible().len(), 1, "a disk's own row does choose");+}++/// Whatever sets the chosen folder (a click, an agent, a rename, undo), its row is on screen.+#[test]+fn the_chosen_folder_is_always_in_view() {+ let mut h = folders_app(&["/pics/trip/day1/a.jpg", "/pics/trip/b.jpg", "/pics/home/c.jpg"]);+ assert!(!has(&h, "source:libfolder:/pics/trip/day1"), "folded to begin with");+ h.app.session.filter.library_folder = Some("/pics/trip/day1".into());+ h.step();+ h.step();+ assert!(has(&h, "source:libfolder:/pics/trip/day1"), "the rows above it opened");+ // folding a parent by hand sticks until the choice changes+ click(&mut h, "libraryFolderToggle:/pics/trip");+ assert!(!has(&h, "source:libfolder:/pics/trip/day1"));+}++#[test]+fn a_renamed_folder_keeps_its_place_in_the_tree() {+ let base = std::env::temp_dir().join(format!("lc-ui-rename-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ std::fs::create_dir_all(base.join("pics/trip")).unwrap();+ std::fs::create_dir_all(base.join("pics/home")).unwrap();+ let b = base.to_string_lossy().to_string();+ let mut h = folders_app(&[&format!("{b}/pics/trip/a.jpg"), &format!("{b}/pics/home/b.jpg")]);+ h.app.session.filter.library_folder = Some(format!("{b}/pics/trip"));+ h.step();+ h.step();+ assert!(has(&h, &format!("source:libfolder:{b}/pics/trip")));+ let r = h.request("engine.execute", json!({"command": "folder.rename", "params": {"path": format!("{b}/pics"), "name": "pics2"}}), T);+ assert_eq!(r["ok"], true, "{r}");+ h.step();+ h.step();+ assert!(has(&h, &format!("source:libfolder:{b}/pics2/trip")), "the chosen folder is still on screen after the rename");+ let _ = std::fs::remove_dir_all(&base);+}++/// The menu opens from anywhere on a folder row, the disclosure triangle included; a disk row+/// has its own, the startup disk none.+#[test]+fn right_click_opens_a_folders_menu_from_the_triangle_too() {+ let mut h = folders_app(&["/pics/trip/a.jpg", "/pics/home/b.jpg", "/Volumes/nas/c.jpg"]);+ click(&mut h, "libraryFolderToggle:/pics");+ right_click(&mut h, "source:libfolder:/pics/trip");+ assert!(popup_open(&h), "on the row");+ h.request("ui.key", json!({"key": "escape"}), T);+ h.step();+ h.step();+ assert!(!popup_open(&h));+ right_click(&mut h, "libraryFolderToggle:/pics");+ assert!(popup_open(&h), "on the triangle");+ h.request("ui.key", json!({"key": "escape"}), T);+ h.step();+ h.step();+ right_click(&mut h, "source:libfolder:/Volumes/nas");+ assert!(popup_open(&h), "a disk row offers removing the disk");+ h.request("ui.key", json!({"key": "escape"}), T);+ h.step();+ h.step();+ right_click(&mut h, "source:libfolder:/");+ assert!(!popup_open(&h), "the startup disk offers nothing");+}++#[test]+fn removing_a_disk_from_the_library_asks_first() {+ use crate::state::Dialog;+ let mut h = folders_app(&["/Volumes/nas/a/1.jpg", "/Volumes/nas/2.jpg", "/Users/me/3.jpg"]);+ h.app.ui.dialog = Some(Dialog::RemoveFolder { path: "/Volumes/nas".into(), name: "nas".into(), count: 2, disk: true });+ h.step();+ assert_eq!(h.app.session.visible().len(), 3);+ let r = h.request("ui.dialog.confirm", json!({}), T);+ assert_eq!(r["ok"], true, "{r}");+ assert_eq!(h.app.session.visible().len(), 1, "everything on that disk left the library");+}diff --git a/docs/parity.md b/docs/parity.mdindex d5a31ea9c..23582ca34 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -47,10 +47,10 @@ and prints the summary; `cargo xtask parity --write` refreshes the summary table| X. Cross-cutting behaviours (BEHAV) | 17 | 4 | 1 | 1 | 8/8 (100%) | 6/8 (75%) || Y. Menus | 81 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) || Z. Keyboard shortcuts (desktop) | 74 | 3 | 3 | 1 | 49/52 (94%) | 22/23 (96%) |-| Lightroom Classic extras | 31 | 10 | 39 | 9 | — | 21/22 (95%) |-| **Total** | 389 | 34 | 86 | 37 | 194/200 (97%) | 139/149 (93%) |+| Lightroom Classic extras | 32 | 10 | 39 | 9 | — | 22/23 (96%) |+| **Total** | 390 | 34 | 86 | 37 | 194/200 (97%) | 140/150 (93%) |-Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **79.8%** of 509 in-scope rows — P0 98.5% of 200 · P1 95.6% of 149 · P2 41.6% of 160.+Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **79.8%** of 510 in-scope rows — P0 98.5% of 200 · P1 95.7% of 150 · P2 41.6% of 160.<!-- /parity:summary -->## Top gaps@@ -718,6 +718,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-| LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) || LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning; no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`) || LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) |+| LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `crates/catalog/src/folders.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests_panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/<host>`), NFS (`/Network/Servers/<host>`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); levels that hold nothing and lead to one folder fold into one row (`Users/me/Pictures`); long names are cut at the end with the full path in the tooltip; click chooses a folder and the folders inside it (click again clears; chip “Folder: pics/trip”), and its row is always opened into view, also after a rename or move and their undo. A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked, as in Local) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row offers Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); creating a folder and moving photos between folders are not here || LRC-LIB-COLLECTIONS | Collections & sets | P1 | ✅ | `cmd:album.create`, `cmd:album.createSmart`, `cmd:album.toggleTarget`, `cmd:album.setTarget`, `cmd:album.clearQuick` | albums + folders (sets), smart albums (rule editor; rules incl. File Path — the whole string, either separator, case-insensitive), Quick Collection and target album (B in the grids adds / removes the selection; album menu ▸ Set as Target Album; the target is marked +) || LRC-LIB-SMARTCOLL | Smart-collection rules | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:album.ruleFields`, `cmd:dialog.smartAlbum`, `crates/catalog/src/rules.rs`, `crates/ui-egui/src/panels/rules_editor.rs` | rule editor: match all / any / none, nested groups (⌥+ or + Group), 30 fields (rating, flag, label, type, edits, keywords, any text, filename, file path, format, title, caption, camera, lens, location, creator, copyright, copyright status, capture / import / edit date, ISO, aperture, focal length, megapixels, GPS, virtual copy, album) with text / number / date / in-the-last operators; live match count; also usable as a library filter (`ruleSet`) || LRC-LIB-PUBLISH | Publish services | P2 | ⬜ | | |