mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-30 10:17:11 +01:00
Merge pull request #2599 from francoisgn/feat/issue-2592-lightroom-backup-zip
LRC-LIB-CATALOG-IMPORT: import Lightroom catalog backup zips directly (#2592)
This commit is contained in:
19 files changed
+1011
-31
No files matched your search
Generated
+1
@@ -3744,6 +3744,7 @@ dependencies = [
|
||||
"ab_glyph",
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"crc32fast",
|
||||
"fs4",
|
||||
"harfrust 0.13.3",
|
||||
"jxl-oxide",
|
||||
|
||||
@@ -49,7 +49,7 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
|
||||
pick_lightroom_catalog: Some(Box::new(|| {
|
||||
file_dialog()
|
||||
.set_title(lightcraft_ui_egui::i18n::tr("Import Lightroom Catalog"))
|
||||
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat"])
|
||||
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat", "zip"])
|
||||
.pick_file()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
})),
|
||||
|
||||
@@ -29,6 +29,8 @@ lightcraft-meta = { workspace = true }
|
||||
lightcraft-lensdb = { workspace = true }
|
||||
lightcraft-faces = { workspace = true }
|
||||
miniz_oxide = { workspace = true }
|
||||
# CRC-32 of a catalog unpacked from a Lightroom backup zip (lightroom_backup.rs).
|
||||
crc32fast = { workspace = true }
|
||||
lightcraft-merge = { workspace = true }
|
||||
lightcraft-geocode = { workspace = true }
|
||||
lightcraft-slideshow = { workspace = true }
|
||||
|
||||
@@ -1302,10 +1302,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}),
|
||||
// ---- import
|
||||
cmd!(query "library.inspectLightroom", "Inspect Lightroom Catalog", [], None,
|
||||
"{path: .lrcat} → {photos, collections, missing, warnings}; read-only, no Lightroom required",
|
||||
always, |_, p| {
|
||||
"{path: .lrcat, or a Lightroom catalog backup .zip} → {photos, collections, missing, warnings}; read-only, no Lightroom required",
|
||||
always, |s, p| {
|
||||
let path = str_param(p,"path").ok_or_else(|| bad("library.inspectLightroom","missing path"))?;
|
||||
let data = crate::lightroom_catalog::read(std::path::Path::new(path)).map_err(|e| bad("library.inspectLightroom",e))?;
|
||||
let (cancel, total, done) = Default::default();
|
||||
let temp = crate::lightroom_catalog::backup_temp_root(s);
|
||||
let data = crate::lightroom_catalog::read_source(std::path::Path::new(path), temp.as_deref(), &cancel, &total, &done)
|
||||
.map_err(|e| bad("library.inspectLightroom",e))?;
|
||||
Ok(json!({"photos":data.photos.len(),"collections":data.collections.iter().filter(|r|r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0)==0.0).count(),"missing":data.photos.iter().filter(|p| !p.original_is_file()).map(|p|&p.path).collect::<Vec<_>>(),"warnings":data.warnings,"skipped":data.skipped}))
|
||||
}),
|
||||
cmd!(
|
||||
@@ -1313,7 +1316,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Lightroom Catalog",
|
||||
[],
|
||||
None,
|
||||
"{path: .lrcat, updateExisting?: false}; direct import of paths, ratings, flags, metadata, keywords, collections, virtual copies & mapped edits. Archives source settings/history first. Existing edited photos are preserved unless updateExisting=true; source catalog is read-only.",
|
||||
"{path: .lrcat, or a Lightroom catalog backup .zip (unpacked to a temporary folder in the library, removed after reading; the zip is not changed), updateExisting?: false}; direct import of paths, ratings, flags, metadata, keywords, collections, virtual copies & mapped edits. Archives source settings/history first. Existing edited photos are preserved unless updateExisting=true; source catalog is read-only.",
|
||||
always,
|
||||
|s, p| {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("library.importLightroom", "missing path"))?;
|
||||
|
||||
@@ -51,6 +51,7 @@ pub mod lens_profiles;
|
||||
pub mod lensfun_download;
|
||||
pub mod library;
|
||||
mod lightroom_archive;
|
||||
pub mod lightroom_backup;
|
||||
pub mod lightroom_catalog;
|
||||
pub mod lightroom_folder;
|
||||
pub mod lightroom_job;
|
||||
|
||||
@@ -519,6 +519,8 @@ mod tests {
|
||||
fn data(source: String) -> CatalogImport {
|
||||
CatalogImport {
|
||||
source,
|
||||
catalog_id: None,
|
||||
catalog_path: None,
|
||||
photos: Vec::new(),
|
||||
collections: Vec::new(),
|
||||
members: Vec::new(),
|
||||
@@ -543,6 +545,8 @@ mod tests {
|
||||
};
|
||||
CatalogImport {
|
||||
source: "source.lrcat".into(),
|
||||
catalog_id: None,
|
||||
catalog_path: None,
|
||||
photos: vec![photo],
|
||||
collections: vec![BTreeMap::from([("name".into(), serde_json::json!("Keepers"))])],
|
||||
members: vec![BTreeMap::from([("image".into(), serde_json::json!(7))])],
|
||||
|
||||
@@ -0,0 +1,558 @@
|
||||
//! Lightroom Classic catalog backups (issue #2592): `Backups/YYYY-MM-DD HHMM/<name>.zip`, which
|
||||
//! holds the catalog `<name>.lrcat` (and, since Classic 12, a small `<name>.lrcat-data/` folder that
|
||||
//! the import does not need). Someone who has left Lightroom may have nothing else: the import takes
|
||||
//! the zip as it is.
|
||||
//!
|
||||
//! The catalog entry is inflated by streaming into a private folder ([`Extracted`]), read from
|
||||
//! there like any `.lrcat`, and the folder is removed when the [`Extracted`] guard is dropped (after
|
||||
//! the read, on an error and on cancel alike). The zip itself is only read. The folder is made under
|
||||
//! the open library's `Interop/` when there is one (the library's disk, not a RAM-backed `/tmp`),
|
||||
//! else under [`std::env::temp_dir`]; a folder left by a crash (`lc-lrbackup-*`, older than a day)
|
||||
//! is removed by the next extraction there.
|
||||
//!
|
||||
//! Written from the ZIP application note (PKWARE APPNOTE.TXT 6.3: end of central directory,
|
||||
//! ZIP64 end record and locator, central directory headers, local headers, the ZIP64 extra field
|
||||
//! 0x0001) and RFC 1951 (deflate, inflated by `miniz_oxide`); no third-party zip code was used.
|
||||
//! Every size and offset comes from the file and is checked before use.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
/// The largest catalog a backup may unpack to: the SQLite reader's cap on a database file.
|
||||
pub const MAX_CATALOG_BYTES: u64 = 16 << 30;
|
||||
/// The most central directory entries looked at (a Lightroom backup has one to four).
|
||||
const MAX_ENTRIES: u64 = 4096;
|
||||
/// The largest central directory read (names of `MAX_ENTRIES` entries fit easily).
|
||||
const MAX_DIRECTORY_BYTES: u64 = 4 << 20;
|
||||
/// Prefix of the private extraction folders, so leftovers can be found.
|
||||
const PREFIX: &str = "lc-lrbackup-";
|
||||
/// Leftover folders older than this are removed (one still being read is never this old).
|
||||
const STALE_SECS: u64 = 24 * 60 * 60;
|
||||
/// Bytes read from the zip and written to the catalog per step.
|
||||
const CHUNK: usize = 1 << 20;
|
||||
|
||||
/// Whether `path` names a Lightroom catalog backup: a `.zip` file (any case).
|
||||
pub fn is_backup(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip"))
|
||||
}
|
||||
|
||||
/// Where the catalog in a backup lived, for resolving the paths it records relative to itself, and
|
||||
/// whether that is known: `<catalog folder>/Backups/<date>/<name>.zip` (Lightroom's default
|
||||
/// layout) → `<catalog folder>/<name>.lrcat`, known; a zip anywhere else (a backup folder of the
|
||||
/// person's choosing, a zip moved away) → the `.lrcat` next to it, a guess that is only used to
|
||||
/// resolve paths, never to recognise the catalog.
|
||||
pub fn original_catalog(zip: &Path, entry: &str) -> (PathBuf, bool) {
|
||||
let name = Path::new(entry).file_name().map_or_else(|| PathBuf::from("catalog.lrcat"), PathBuf::from);
|
||||
let dated = zip.parent();
|
||||
let backups = dated.and_then(Path::parent);
|
||||
match backups {
|
||||
Some(b) if b.file_name().is_some_and(|n| n.eq_ignore_ascii_case("backups")) => (b.parent().unwrap_or(b).join(name), true),
|
||||
_ => (dated.map_or_else(|| name.clone(), |d| d.join(&name)), false),
|
||||
}
|
||||
}
|
||||
|
||||
/// A catalog unpacked from a backup; its private folder is removed when this is dropped.
|
||||
#[derive(Debug)]
|
||||
pub struct Extracted {
|
||||
dir: PathBuf,
|
||||
/// The unpacked `.lrcat`.
|
||||
pub catalog: PathBuf,
|
||||
/// The catalog's name inside the zip.
|
||||
pub entry: String,
|
||||
}
|
||||
|
||||
impl Drop for Extracted {
|
||||
/// Removes the private folder and the catalog in it; a failure is logged, not raised (drop can't fail).
|
||||
fn drop(&mut self) {
|
||||
if let Err(e) = std::fs::remove_dir_all(&self.dir)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
log::warn!("Lightroom backup: could not remove {}: {e}", self.dir.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One file in the zip's central directory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct Entry {
|
||||
name: String,
|
||||
method: u16,
|
||||
crc: u32,
|
||||
compressed: u64,
|
||||
size: u64,
|
||||
local: u64,
|
||||
}
|
||||
|
||||
/// The little-endian `u16` at `at` in `b`, or `None` past its end.
|
||||
fn u16_at(b: &[u8], at: usize) -> Option<u16> {
|
||||
let s = b.get(at..at.checked_add(2)?)?;
|
||||
Some(u16::from_le_bytes([s[0], s[1]]))
|
||||
}
|
||||
|
||||
/// The little-endian `u32` at `at` in `b`, or `None` past its end.
|
||||
fn u32_at(b: &[u8], at: usize) -> Option<u32> {
|
||||
let s = b.get(at..at.checked_add(4)?)?;
|
||||
Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
|
||||
}
|
||||
|
||||
/// The little-endian `u64` at `at` in `b`, or `None` past its end.
|
||||
fn u64_at(b: &[u8], at: usize) -> Option<u64> {
|
||||
let s = b.get(at..at.checked_add(8)?)?;
|
||||
let mut a = [0u8; 8];
|
||||
a.copy_from_slice(s);
|
||||
Some(u64::from_le_bytes(a))
|
||||
}
|
||||
|
||||
/// `len` bytes of `f` from offset `at`; a length that doesn't fit memory or a short read is an error.
|
||||
fn read_at(f: &mut File, at: u64, len: u64) -> Result<Vec<u8>, String> {
|
||||
let len = usize::try_from(len).map_err(|_| "zip record too large".to_string())?;
|
||||
f.seek(SeekFrom::Start(at)).map_err(|e| e.to_string())?;
|
||||
let mut buf = vec![0u8; len];
|
||||
f.read_exact(&mut buf).map_err(|e| format!("truncated zip: {e}"))?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// The central directory's entries (offset and count from the end record, or its ZIP64 record).
|
||||
fn entries(f: &mut File) -> Result<Vec<Entry>, String> {
|
||||
let len = f.metadata().map_err(|e| e.to_string())?.len();
|
||||
// end of central directory: 22 bytes plus a comment of up to 64 KiB
|
||||
let tail_len = len.min(22 + 65_535);
|
||||
let tail_at = len - tail_len;
|
||||
let tail = read_at(f, tail_at, tail_len)?;
|
||||
let eocd = (0..tail.len().saturating_sub(21)).rev().find(|&i| tail.get(i..).is_some_and(|b| b.starts_with(b"PK\x05\x06")));
|
||||
let Some(eocd) = eocd else { return Err("not a zip file (no end of central directory)".into()) };
|
||||
let bad = || "damaged zip (end of central directory)".to_string();
|
||||
let mut count = u64::from(u16_at(&tail, eocd + 10).ok_or_else(bad)?);
|
||||
let mut dir_len = u64::from(u32_at(&tail, eocd + 12).ok_or_else(bad)?);
|
||||
let mut dir_at = u64::from(u32_at(&tail, eocd + 16).ok_or_else(bad)?);
|
||||
// ZIP64: a locator just before the end record points at the ZIP64 end record
|
||||
if (count == 0xFFFF || dir_len == 0xFFFF_FFFF || dir_at == 0xFFFF_FFFF)
|
||||
&& let Some(loc) = eocd.checked_sub(20)
|
||||
&& tail.get(loc..).is_some_and(|b| b.starts_with(b"PK\x06\x07"))
|
||||
{
|
||||
let rec_at = u64_at(&tail, loc + 8).ok_or_else(bad)?;
|
||||
let rec = read_at(f, rec_at, 56)?;
|
||||
if !rec.starts_with(b"PK\x06\x06") {
|
||||
return Err("damaged zip (ZIP64 end record)".into());
|
||||
}
|
||||
count = u64_at(&rec, 32).ok_or_else(bad)?;
|
||||
dir_len = u64_at(&rec, 40).ok_or_else(bad)?;
|
||||
dir_at = u64_at(&rec, 48).ok_or_else(bad)?;
|
||||
}
|
||||
if count > MAX_ENTRIES || dir_len > MAX_DIRECTORY_BYTES || dir_at.checked_add(dir_len).is_none_or(|end| end > len) {
|
||||
return Err("damaged zip (central directory out of range)".into());
|
||||
}
|
||||
let dir = read_at(f, dir_at, dir_len)?;
|
||||
let mut out = Vec::new();
|
||||
let mut at = 0usize;
|
||||
let bad = || "damaged zip (central directory)".to_string();
|
||||
for _ in 0..count {
|
||||
if !dir.get(at..).is_some_and(|b| b.starts_with(b"PK\x01\x02")) {
|
||||
return Err(bad());
|
||||
}
|
||||
let method = u16_at(&dir, at + 10).ok_or_else(bad)?;
|
||||
let crc = u32_at(&dir, at + 16).ok_or_else(bad)?;
|
||||
let mut compressed = u64::from(u32_at(&dir, at + 20).ok_or_else(bad)?);
|
||||
let mut size = u64::from(u32_at(&dir, at + 24).ok_or_else(bad)?);
|
||||
let name_len = usize::from(u16_at(&dir, at + 28).ok_or_else(bad)?);
|
||||
let extra_len = usize::from(u16_at(&dir, at + 30).ok_or_else(bad)?);
|
||||
let comment_len = usize::from(u16_at(&dir, at + 32).ok_or_else(bad)?);
|
||||
let mut local = u64::from(u32_at(&dir, at + 42).ok_or_else(bad)?);
|
||||
let name_at = at + 46;
|
||||
let name_end = name_at.checked_add(name_len).ok_or_else(bad)?;
|
||||
let name = String::from_utf8_lossy(dir.get(name_at..name_end).ok_or_else(bad)?).replace('\\', "/");
|
||||
let extra = dir.get(name_end..name_end.checked_add(extra_len).ok_or_else(bad)?).ok_or_else(bad)?;
|
||||
// ZIP64 extra field: the 64-bit values, in this order, of those set to 0xFFFFFFFF
|
||||
let mut e = 0usize;
|
||||
while e + 4 <= extra.len() {
|
||||
let (id, len) = (u16_at(extra, e).ok_or_else(bad)?, usize::from(u16_at(extra, e + 2).ok_or_else(bad)?));
|
||||
let body = extra.get(e + 4..e + 4 + len).ok_or_else(bad)?;
|
||||
if id == 0x0001 {
|
||||
let mut v = 0usize;
|
||||
for field in [&mut size, &mut compressed, &mut local] {
|
||||
if *field == 0xFFFF_FFFF {
|
||||
*field = u64_at(body, v).ok_or_else(bad)?;
|
||||
v += 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
e += 4 + len;
|
||||
}
|
||||
at = name_end.checked_add(extra_len).and_then(|x| x.checked_add(comment_len)).ok_or_else(bad)?;
|
||||
out.push(Entry { name, method, crc, compressed, size, local });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The backup's catalog entry: the one `*.lrcat` file in the zip, outside macOS resource forks.
|
||||
fn catalog_entry(entries: &[Entry]) -> Result<&Entry, String> {
|
||||
let mut found = entries.iter().filter(|e| {
|
||||
let lower = e.name.to_lowercase();
|
||||
lower.ends_with(".lrcat") && !lower.split('/').any(|p| p == "__macosx" || p.starts_with("._"))
|
||||
});
|
||||
match (found.next(), found.next()) {
|
||||
(Some(e), None) => Ok(e),
|
||||
(None, _) => Err("this zip holds no Lightroom catalog (.lrcat)".into()),
|
||||
(Some(_), Some(_)) => Err("this zip holds more than one Lightroom catalog (.lrcat); unzip it and import one".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the zip at `path` holds exactly one Lightroom catalog, by its central directory only
|
||||
/// (nothing is unpacked). Any read error means no.
|
||||
pub fn holds_catalog(path: &Path) -> bool {
|
||||
File::open(path).ok().and_then(|mut f| entries(&mut f).ok()).is_some_and(|all| catalog_entry(&all).is_ok())
|
||||
}
|
||||
|
||||
/// Remove `lc-lrbackup-*` folders in `root` left by an earlier run that ended without cleaning up.
|
||||
fn sweep(root: &Path) {
|
||||
let Ok(dir) = std::fs::read_dir(root) else { return };
|
||||
for entry in dir.take(10_000).flatten() {
|
||||
if !entry.file_name().to_str().is_some_and(|n| n.starts_with(PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
// only a real folder of ours: `DirEntry::metadata` doesn't follow a link (Unix), and a link named
|
||||
// like one is skipped explicitly rather than relying on `remove_dir_all` removing just the link
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
let stale = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age.as_secs() > STALE_SECS);
|
||||
if meta.is_dir()
|
||||
&& !meta.file_type().is_symlink()
|
||||
&& stale
|
||||
&& let Err(e) = std::fs::remove_dir_all(entry.path())
|
||||
{
|
||||
log::warn!("Lightroom backup: could not remove the leftover {}: {e}", entry.path().display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse a known shortage; an unavailable space reading is left to normal write-error handling.
|
||||
fn check_space(root: &Path, needed: u64, available: Option<u64>) -> Result<(), String> {
|
||||
if let Some(available) = available
|
||||
&& needed > available
|
||||
{
|
||||
return Err(format!("not enough free space in {} to unpack this catalog ({} bytes needed, {} available)", root.display(), needed, available));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Unpack the catalog of the backup `zip` into a new private folder under `root`, checking its
|
||||
/// size and CRC-32. Stops with an error when `cancel` is set; the folder is removed then too.
|
||||
pub fn extract(zip: &Path, root: &Path, cancel: &AtomicBool) -> Result<Extracted, String> {
|
||||
let mut f = File::open(zip).map_err(|e| format!("{}: {e}", zip.display()))?;
|
||||
let all = entries(&mut f)?;
|
||||
let entry = catalog_entry(&all)?.clone();
|
||||
if entry.size > MAX_CATALOG_BYTES {
|
||||
return Err(format!("the catalog in this backup unpacks to {} GB, more than LightCraft reads", entry.size >> 30));
|
||||
}
|
||||
std::fs::create_dir_all(root).map_err(|e| format!("{}: {e}", root.display()))?;
|
||||
check_space(root, entry.size, crate::disk_space::read(root).map(|space| space.available))?;
|
||||
sweep(root);
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
|
||||
let dir = root.join(format!("{PREFIX}{}-{stamp}", std::process::id()));
|
||||
// owner-only from the start on Unix (a catalog holds the person's paths and metadata)
|
||||
#[cfg(unix)]
|
||||
let builder = {
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
||||
builder
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let builder = std::fs::DirBuilder::new();
|
||||
builder.create(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
// a fixed name, not the zip's: an entry named `NUL.lrcat` or `a:b.lrcat` would be a device or an
|
||||
// alternate data stream on Windows. The guard exists before the first byte is written: every
|
||||
// early return below cleans up.
|
||||
let out = Extracted { catalog: dir.join("catalog.lrcat"), dir, entry: entry.name.clone() };
|
||||
let local = read_at(&mut f, entry.local, 30)?;
|
||||
if !local.starts_with(b"PK\x03\x04") {
|
||||
return Err("damaged zip (local header)".into());
|
||||
}
|
||||
let bad = || "damaged zip (local header)".to_string();
|
||||
let skip = u64::from(u16_at(&local, 26).ok_or_else(bad)?) + u64::from(u16_at(&local, 28).ok_or_else(bad)?);
|
||||
let data_at = entry.local.checked_add(30 + skip).ok_or_else(bad)?;
|
||||
f.seek(SeekFrom::Start(data_at)).map_err(|e| e.to_string())?;
|
||||
let mut input = f.take(entry.compressed);
|
||||
// created new: a file or a link already in its place is an error, never written through
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&out.catalog).map_err(|e| format!("{}: {e}", out.catalog.display()))?;
|
||||
let mut writer = std::io::BufWriter::with_capacity(CHUNK, file);
|
||||
let mut crc = crc32fast::Hasher::new();
|
||||
let mut written = 0u64;
|
||||
let mut write = |bytes: &[u8], written: &mut u64| -> Result<(), String> {
|
||||
*written = written.saturating_add(bytes.len() as u64);
|
||||
if *written > entry.size {
|
||||
return Err("damaged zip (the catalog is longer than the zip says)".into());
|
||||
}
|
||||
crc.update(bytes);
|
||||
writer.write_all(bytes).map_err(|e| format!("writing {}: {e}", out.catalog.display()))
|
||||
};
|
||||
let mut buf = vec![0u8; CHUNK];
|
||||
match entry.method {
|
||||
0 => loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
let n = input.read(&mut buf).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
write(buf.get(..n).unwrap_or_default(), &mut written)?;
|
||||
},
|
||||
8 => {
|
||||
use miniz_oxide::inflate::stream::{InflateState, inflate};
|
||||
use miniz_oxide::{DataFormat, MZFlush, MZStatus};
|
||||
let mut state = InflateState::new_boxed(DataFormat::Raw);
|
||||
let mut out_buf = vec![0u8; CHUNK];
|
||||
let (mut start, mut end) = (0usize, 0usize);
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
if start == end {
|
||||
end = input.read(&mut buf).map_err(|e| e.to_string())?;
|
||||
start = 0;
|
||||
}
|
||||
let flush = if end == 0 { MZFlush::Finish } else { MZFlush::None };
|
||||
let r = inflate(&mut state, buf.get(start..end).unwrap_or_default(), &mut out_buf, flush);
|
||||
start = start.saturating_add(r.bytes_consumed).min(end);
|
||||
write(out_buf.get(..r.bytes_written).unwrap_or_default(), &mut written)?;
|
||||
match r.status {
|
||||
Ok(MZStatus::StreamEnd) => break,
|
||||
Ok(_) => {}
|
||||
// no progress with all input given: the stream is cut short
|
||||
Err(miniz_oxide::MZError::Buf) if end == 0 && r.bytes_written == 0 => return Err("damaged zip (the catalog is cut short)".into()),
|
||||
Err(miniz_oxide::MZError::Buf) => {}
|
||||
Err(e) => return Err(format!("damaged zip (deflate: {e:?})")),
|
||||
}
|
||||
if r.bytes_consumed == 0 && r.bytes_written == 0 && start < end {
|
||||
return Err("damaged zip (the catalog's data does not inflate)".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
m => return Err(format!("this zip uses compression method {m}, which LightCraft does not read; unzip it and import the .lrcat")),
|
||||
}
|
||||
writer.flush().map_err(|e| format!("writing {}: {e}", out.catalog.display()))?;
|
||||
drop(writer);
|
||||
if written != entry.size {
|
||||
return Err("damaged zip (the catalog is shorter than the zip says)".into());
|
||||
}
|
||||
if crc.finalize() != entry.crc {
|
||||
return Err("damaged zip (the catalog's checksum does not match)".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
#[test]
|
||||
fn free_space_check_refuses_known_shortage() {
|
||||
let root = std::path::Path::new("library");
|
||||
assert!(super::check_space(root, 11, Some(10)).unwrap_err().contains("not enough free space"));
|
||||
assert!(super::check_space(root, 10, Some(10)).is_ok());
|
||||
assert!(super::check_space(root, 11, None).is_ok());
|
||||
}
|
||||
use super::*;
|
||||
|
||||
/// A zip of `files` (name, bytes), each stored or deflated; `zip64` writes ZIP64 records and
|
||||
/// extra fields (with the 32-bit fields set to 0xFFFFFFFF) as large archives do.
|
||||
pub(crate) fn zip(files: &[(&str, &[u8])], deflate: bool, zip64: bool) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut central = Vec::new();
|
||||
for (name, data) in files {
|
||||
let body = if deflate { miniz_oxide::deflate::compress_to_vec(data, 6) } else { data.to_vec() };
|
||||
let crc = crc32fast::hash(data);
|
||||
let local = out.len() as u64;
|
||||
let method: u16 = if deflate { 8 } else { 0 };
|
||||
let big = |v: u64| if zip64 { 0xFFFF_FFFFu32 } else { v as u32 };
|
||||
let mut extra = Vec::new();
|
||||
if zip64 {
|
||||
extra.extend_from_slice(&1u16.to_le_bytes());
|
||||
extra.extend_from_slice(&24u16.to_le_bytes());
|
||||
extra.extend_from_slice(&(data.len() as u64).to_le_bytes());
|
||||
extra.extend_from_slice(&(body.len() as u64).to_le_bytes());
|
||||
extra.extend_from_slice(&local.to_le_bytes());
|
||||
}
|
||||
out.extend_from_slice(b"PK\x03\x04");
|
||||
out.extend_from_slice(&[20, 0, 0, 0]);
|
||||
out.extend_from_slice(&method.to_le_bytes());
|
||||
out.extend_from_slice(&[0; 4]);
|
||||
out.extend_from_slice(&crc.to_le_bytes());
|
||||
out.extend_from_slice(&big(body.len() as u64).to_le_bytes());
|
||||
out.extend_from_slice(&big(data.len() as u64).to_le_bytes());
|
||||
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(name.as_bytes());
|
||||
out.extend_from_slice(&body);
|
||||
central.extend_from_slice(b"PK\x01\x02");
|
||||
central.extend_from_slice(&[45, 0, 45, 0, 0, 0]);
|
||||
central.extend_from_slice(&method.to_le_bytes());
|
||||
central.extend_from_slice(&[0; 4]);
|
||||
central.extend_from_slice(&crc.to_le_bytes());
|
||||
central.extend_from_slice(&big(body.len() as u64).to_le_bytes());
|
||||
central.extend_from_slice(&big(data.len() as u64).to_le_bytes());
|
||||
central.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
||||
central.extend_from_slice(&(extra.len() as u16).to_le_bytes());
|
||||
// comment length, disk number, internal attributes, external attributes
|
||||
central.extend_from_slice(&[0; 6]);
|
||||
central.extend_from_slice(&0u32.to_le_bytes());
|
||||
central.extend_from_slice(&big(local).to_le_bytes());
|
||||
central.extend_from_slice(name.as_bytes());
|
||||
central.extend_from_slice(&extra);
|
||||
}
|
||||
let dir_at = out.len() as u64;
|
||||
out.extend_from_slice(¢ral);
|
||||
let count = files.len() as u64;
|
||||
if zip64 {
|
||||
let rec_at = out.len() as u64;
|
||||
out.extend_from_slice(b"PK\x06\x06");
|
||||
out.extend_from_slice(&44u64.to_le_bytes());
|
||||
out.extend_from_slice(&[45, 0, 45, 0]);
|
||||
out.extend_from_slice(&[0; 8]);
|
||||
out.extend_from_slice(&count.to_le_bytes());
|
||||
out.extend_from_slice(&count.to_le_bytes());
|
||||
out.extend_from_slice(&(central.len() as u64).to_le_bytes());
|
||||
out.extend_from_slice(&dir_at.to_le_bytes());
|
||||
out.extend_from_slice(b"PK\x06\x07");
|
||||
out.extend_from_slice(&0u32.to_le_bytes());
|
||||
out.extend_from_slice(&rec_at.to_le_bytes());
|
||||
out.extend_from_slice(&1u32.to_le_bytes());
|
||||
}
|
||||
out.extend_from_slice(b"PK\x05\x06");
|
||||
out.extend_from_slice(&[0; 4]);
|
||||
let c16 = if zip64 { 0xFFFF } else { count as u16 };
|
||||
out.extend_from_slice(&c16.to_le_bytes());
|
||||
out.extend_from_slice(&c16.to_le_bytes());
|
||||
out.extend_from_slice(&(if zip64 { 0xFFFF_FFFF } else { central.len() as u32 }).to_le_bytes());
|
||||
out.extend_from_slice(&(if zip64 { 0xFFFF_FFFF } else { dir_at as u32 }).to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A fresh, empty folder for one test.
|
||||
fn temp(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("lc-lrbackup-test-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// The private extraction folders still in `root`.
|
||||
fn leftovers(root: &Path) -> Vec<String> {
|
||||
let Ok(dir) = std::fs::read_dir(root) else { return Vec::new() };
|
||||
dir.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.starts_with(PREFIX)).collect()
|
||||
}
|
||||
|
||||
/// Stored, deflated and ZIP64 backups give back the catalog byte for byte, under the fixed name, and leave nothing.
|
||||
#[test]
|
||||
fn stored_deflated_and_zip64_backups_unpack_their_catalog_and_clean_up() {
|
||||
let catalog: Vec<u8> = (0..300_000u32).flat_map(|i| (i % 251).to_le_bytes()).collect();
|
||||
for (deflate, zip64) in [(false, false), (true, false), (true, true), (false, true)] {
|
||||
let dir = temp(&format!("ok-{deflate}-{zip64}"));
|
||||
let path = dir.join("Cat.zip");
|
||||
let files: [(&str, &[u8]); 3] = [("Cat.lrcat", &catalog), ("Cat.lrcat-data/CURRENT", b"MANIFEST-1\n"), ("__MACOSX/._Cat.lrcat", b"x")];
|
||||
std::fs::write(&path, zip(&files, deflate, zip64)).unwrap();
|
||||
let root = dir.join("tmp");
|
||||
let got = extract(&path, &root, &AtomicBool::new(false)).unwrap();
|
||||
assert_eq!(std::fs::read(&got.catalog).unwrap(), catalog, "deflate {deflate} zip64 {zip64}");
|
||||
assert_eq!(got.entry, "Cat.lrcat");
|
||||
assert_eq!(got.catalog.file_name().unwrap(), "catalog.lrcat", "a fixed name, never the zip's");
|
||||
drop(got);
|
||||
assert!(leftovers(&root).is_empty(), "the private folder is removed");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Not a zip, empty, no or two catalogs, cut short, bad CRC, or cancelled: an error, and no folder left.
|
||||
#[test]
|
||||
fn damaged_or_wrong_zips_are_errors_and_leave_nothing_behind() {
|
||||
let dir = temp("bad");
|
||||
let root = dir.join("tmp");
|
||||
let catalog = vec![7u8; 100_000];
|
||||
let good = zip(&[("Cat.lrcat", &catalog)], true, false);
|
||||
let cases: Vec<(&str, Vec<u8>)> = vec![
|
||||
("not a zip", b"SQLite format 3\0".to_vec()),
|
||||
("empty", Vec::new()),
|
||||
("no catalog", zip(&[("notes.txt", b"hi")], false, false)),
|
||||
("two catalogs", zip(&[("A.lrcat", b"a"), ("B.lrcat", b"b")], false, false)),
|
||||
("cut short", good.get(..good.len() / 2).unwrap().to_vec()),
|
||||
("bad crc", {
|
||||
let mut z = good.clone();
|
||||
// flip one byte of the deflated data (after the 30-byte local header and the name)
|
||||
z[30 + 9 + 10] ^= 0xFF;
|
||||
z
|
||||
}),
|
||||
];
|
||||
for (what, bytes) in cases {
|
||||
let path = dir.join("x.zip");
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
assert!(extract(&path, &root, &AtomicBool::new(false)).is_err(), "{what} must fail");
|
||||
if root.exists() {
|
||||
assert!(leftovers(&root).is_empty(), "{what} left a folder");
|
||||
}
|
||||
}
|
||||
std::fs::write(dir.join("x.zip"), &good).unwrap();
|
||||
assert!(extract(&dir.join("x.zip"), &root, &AtomicBool::new(true)).is_err(), "cancel stops");
|
||||
assert!(leftovers(&root).is_empty(), "cancel cleans up");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A ZIP64 size of 1 TB is refused before anything is written.
|
||||
#[test]
|
||||
fn a_zip_that_lies_about_the_catalog_size_is_refused() {
|
||||
let dir = temp("size");
|
||||
let mut z = zip(&[("Cat.lrcat", &[1u8; 1000])], true, true);
|
||||
// the ZIP64 extra field's uncompressed size: 1 TB
|
||||
let at = z.windows(4).rposition(|w| w == [1, 0, 24, 0]).unwrap() + 4;
|
||||
z[at..at + 8].copy_from_slice(&(1u64 << 40).to_le_bytes());
|
||||
std::fs::write(dir.join("x.zip"), &z).unwrap();
|
||||
let err = extract(&dir.join("x.zip"), &dir.join("tmp"), &AtomicBool::new(false)).unwrap_err();
|
||||
assert!(err.contains("more than LightCraft reads"), "{err}");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A day-old leftover folder is removed; a recent one (another import still reading) is kept.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn stale_leftovers_are_swept_and_recent_ones_kept() {
|
||||
let root = temp("sweep");
|
||||
let old = root.join(format!("{PREFIX}1-1"));
|
||||
let recent = root.join(format!("{PREFIX}2-2"));
|
||||
std::fs::create_dir_all(&old).unwrap();
|
||||
std::fs::create_dir_all(&recent).unwrap();
|
||||
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(STALE_SECS + 60);
|
||||
File::open(&old).unwrap().set_modified(past).unwrap();
|
||||
sweep(&root);
|
||||
assert!(!old.exists() && recent.exists());
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
/// Paths relative to the catalog resolve from where Lightroom kept it, not from the zip.
|
||||
#[test]
|
||||
fn the_original_catalog_is_two_folders_above_a_dated_backup() {
|
||||
let zip = Path::new("/p/Lightroom/Backups/2023-11-07 0900/Cat-v13.zip");
|
||||
assert_eq!(original_catalog(zip, "Cat-v13.lrcat"), (PathBuf::from("/p/Lightroom/Cat-v13.lrcat"), true));
|
||||
// a backup folder of the person's choosing: a guess for paths, not an identity
|
||||
assert_eq!(original_catalog(Path::new("/elsewhere/Cat.zip"), "sub/Cat.lrcat"), (PathBuf::from("/elsewhere/Cat.lrcat"), false));
|
||||
let chosen = Path::new("/Volumes/Ext/LR Backups/2026-10-22 1200/Cat.zip");
|
||||
assert!(!original_catalog(chosen, "Cat.lrcat").1);
|
||||
assert!(is_backup(Path::new("a/B.ZIP")) && !is_backup(Path::new("a/B.lrcat")));
|
||||
}
|
||||
|
||||
/// Folder detection counts a zip only when its directory lists exactly one catalog.
|
||||
#[test]
|
||||
fn only_a_zip_with_one_catalog_holds_one() {
|
||||
let dir = temp("holds");
|
||||
let cases: [(&str, Vec<u8>, bool); 4] = [
|
||||
("one.zip", zip(&[("Cat.lrcat", b"x"), ("Cat.lrcat-data/CURRENT", b"y")], true, false), true),
|
||||
("none.zip", zip(&[("photo.jpg", b"x")], false, false), false),
|
||||
("two.zip", zip(&[("A.lrcat", b"a"), ("B.lrcat", b"b")], false, false), false),
|
||||
("junk.zip", b"PK".to_vec(), false),
|
||||
];
|
||||
for (name, bytes, want) in cases {
|
||||
std::fs::write(dir.join(name), bytes).unwrap();
|
||||
assert_eq!(holds_catalog(&dir.join(name)), want, "{name}");
|
||||
}
|
||||
assert!(!holds_catalog(&dir.join("absent.zip")));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,15 @@ impl Reader {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The catalog's `Adobe_storeProviderID` (a UUID), kept by Lightroom in its backups; `None`
|
||||
/// when the table or the value is missing or doesn't look like an id.
|
||||
fn catalog_id(&self) -> Option<String> {
|
||||
let rows = self.table("Adobe_variablesTable", false).ok()?;
|
||||
let row = rows.iter().find(|r| text(r, "name") == "Adobe_storeProviderID")?;
|
||||
let id = text(row, "value").trim();
|
||||
(!id.is_empty() && id.len() <= 128 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then(|| id.to_string())
|
||||
}
|
||||
|
||||
fn optional_table(&self, name: &str, warnings: &mut Vec<String>) -> Result<Vec<Row>, String> {
|
||||
match self.table(name, false) {
|
||||
Ok(rows) => Ok(rows),
|
||||
@@ -176,6 +185,16 @@ impl CatalogPhoto {
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct CatalogImport {
|
||||
pub source: String,
|
||||
/// The catalog's own id (`Adobe_storeProviderID` in `Adobe_variablesTable`), the same in the
|
||||
/// catalog and in every backup of it, so a backup's collections match those of an earlier import
|
||||
/// of the catalog (issue #2592). `None` when the catalog has none.
|
||||
#[serde(default)]
|
||||
pub catalog_id: Option<String>,
|
||||
/// Where the catalog was when it isn't `source`: for a backup zip, the `.lrcat` it was backed up
|
||||
/// from. Collections imported by earlier releases are keyed on that path, so a backup still finds
|
||||
/// them. `None` when the catalog was read where it is.
|
||||
#[serde(default)]
|
||||
pub catalog_path: Option<String>,
|
||||
pub photos: Vec<CatalogPhoto>,
|
||||
pub collections: Vec<Row>,
|
||||
pub members: Vec<Row>,
|
||||
@@ -215,6 +234,11 @@ pub enum SkipReason {
|
||||
pub(crate) struct ImportIndex {
|
||||
pub(crate) photos: BTreeMap<String, u64>,
|
||||
pub(crate) collections: BTreeMap<String, u64>,
|
||||
/// The catalog id (`Adobe_storeProviderID`) each collection key was recorded for, when the
|
||||
/// import had one: a path key of one catalog never matches another catalog that later sits at
|
||||
/// the same path. Keys without an owner (earlier releases, catalogs without an id) match any.
|
||||
#[serde(default)]
|
||||
pub(crate) collection_owners: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
pub(crate) fn load_index(path: Option<&Path>) -> crate::Result<ImportIndex> {
|
||||
@@ -246,7 +270,12 @@ pub(crate) struct AppliedImport {
|
||||
}
|
||||
|
||||
fn identity(data: &CatalogImport, photo: &CatalogPhoto) -> String {
|
||||
if photo.uuid.is_empty() { format!("{}:{}", key(&data.source), photo.source_id) } else { photo.uuid.clone() }
|
||||
// (a backup's photos are recognised by the catalog it was made from, as the catalog's own are)
|
||||
if photo.uuid.is_empty() {
|
||||
format!("{}:{}", key(data.catalog_path.as_deref().unwrap_or(&data.source)), photo.source_id)
|
||||
} else {
|
||||
photo.uuid.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(data: &CatalogImport) -> Result<(), String> {
|
||||
@@ -440,10 +469,47 @@ pub fn read(path: &Path) -> Result<CatalogImport, String> {
|
||||
/// stopping when `cancel` is set. Images whose catalog records are incomplete are left out and
|
||||
/// listed in [`CatalogImport::skipped`] instead of failing the read.
|
||||
pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, done: &AtomicUsize) -> Result<CatalogImport, String> {
|
||||
read_source(path, None, cancel, total, done)
|
||||
}
|
||||
|
||||
/// Where a Lightroom backup's catalog is unpacked while it is read: the open library's `Interop/`
|
||||
/// folder (on the library's disk), or `None` for the system's temporary folder.
|
||||
pub fn backup_temp_root(s: &crate::Session) -> Option<PathBuf> {
|
||||
s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop"))
|
||||
}
|
||||
|
||||
/// [`read_with_progress`] of a catalog or of a Lightroom catalog backup (`.zip`, issue #2592): a
|
||||
/// backup's catalog is unpacked into a private folder under `temp_root` (else the system's temporary
|
||||
/// folder), read, and removed again ([`crate::lightroom_backup`]). Paths the catalog records
|
||||
/// relative to itself are taken from where the catalog was before it was backed up.
|
||||
pub fn read_source(
|
||||
path: &Path,
|
||||
temp_root: Option<&Path>,
|
||||
cancel: &AtomicBool,
|
||||
total: &AtomicUsize,
|
||||
done: &AtomicUsize,
|
||||
) -> Result<CatalogImport, String> {
|
||||
// 13 catalog tables plus one validation stage; ImportJob adds one unit per original path.
|
||||
total.store(14, Ordering::Relaxed);
|
||||
done.store(0, Ordering::Relaxed);
|
||||
ensure_read_active(cancel)?;
|
||||
if crate::lightroom_backup::is_backup(path) {
|
||||
let root = temp_root.map_or_else(std::env::temp_dir, Path::to_path_buf);
|
||||
let extracted = crate::lightroom_backup::extract(path, &root, cancel)?;
|
||||
let (document, known) = crate::lightroom_backup::original_catalog(path, &extracted.entry);
|
||||
let mut data = read_file(&extracted.catalog, &document, path, cancel, done)?;
|
||||
if !known {
|
||||
// only a guess: it resolves relative paths, but never names the catalog
|
||||
data.catalog_path = None;
|
||||
}
|
||||
return Ok(data);
|
||||
}
|
||||
read_file(path, path, path, cancel, done)
|
||||
}
|
||||
|
||||
/// Read the catalog file `path`, resolving the paths it records with `document` as the catalog's
|
||||
/// place and reporting `source` as where it came from.
|
||||
fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, done: &AtomicUsize) -> Result<CatalogImport, String> {
|
||||
let before = std::fs::metadata(path).map_err(|e| e.to_string())?;
|
||||
let wal_path = PathBuf::from(format!("{}-wal", path.display()));
|
||||
let wal_before = std::fs::metadata(&wal_path).ok().map(|m| (m.len(), m.modified().ok()));
|
||||
@@ -529,7 +595,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
|
||||
root_ids.sort_unstable();
|
||||
for (id, root) in root_ids.iter().filter_map(|id| Some((*id, roots.get(id)?))) {
|
||||
let absolute = text(root, "absolutePath");
|
||||
let resolved = match relocated_root(absolute, text(root, "relativePathFromCatalog"), path) {
|
||||
let resolved = match relocated_root(absolute, text(root, "relativePathFromCatalog"), document) {
|
||||
Some(found) => {
|
||||
let found = found.to_string_lossy().to_string();
|
||||
warnings.push(format!("root folder {}: {absolute} not found; using {found} (relative to the catalog)", text(root, "name")));
|
||||
@@ -537,7 +603,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
|
||||
}
|
||||
None => absolute.to_string(),
|
||||
};
|
||||
if let Err(crate::doc_path::NotFollowed::Refused(why)) = crate::doc_path::resolve(&resolved, Some(path)) {
|
||||
if let Err(crate::doc_path::NotFollowed::Refused(why)) = crate::doc_path::resolve(&resolved, Some(document)) {
|
||||
warnings
|
||||
.push(format!("root folder {}: {resolved} is not opened: {why}; its photos are listed as missing and not added", text(root, "name")));
|
||||
refused_roots.insert(id);
|
||||
@@ -547,7 +613,9 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
|
||||
let mut history = group(optional_table("Adobe_libraryImageDevelopHistoryStep", &mut warnings)?);
|
||||
let mut snapshots = group(optional_table("Adobe_libraryImageDevelopSnapshot", &mut warnings)?);
|
||||
let mut out = CatalogImport {
|
||||
source: path.to_string_lossy().into(),
|
||||
source: source.to_string_lossy().into(),
|
||||
catalog_id: reader.catalog_id(),
|
||||
catalog_path: (document != source).then(|| document.to_string_lossy().into()),
|
||||
photos: Vec::new(),
|
||||
collections: optional_table("AgLibraryCollection", &mut warnings)?,
|
||||
members: optional_table("AgLibraryCollectionImage", &mut warnings)?,
|
||||
@@ -584,7 +652,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
|
||||
orphans.insert(id);
|
||||
continue;
|
||||
}
|
||||
let (photo_path, original) = original_path(root_path, folder_path, name, path);
|
||||
let (photo_path, original) = original_path(root_path, folder_path, name, document);
|
||||
if let Original::Refused(why) = &original
|
||||
&& !refused_roots.contains(&root_id)
|
||||
{
|
||||
@@ -1006,14 +1074,34 @@ fn stage_collections(
|
||||
if number(collection, "systemOnly") != 0 {
|
||||
continue;
|
||||
}
|
||||
let collection_key = format!("{}:{}", key(&data.source), number(collection, "id_local"));
|
||||
let indexed = index
|
||||
.collections
|
||||
.get(&collection_key)
|
||||
.copied()
|
||||
// keyed on the catalog's own id (the same in its backups); imports made before that was
|
||||
// read are keyed on the catalog's path, and are still found by it, also from a backup (the
|
||||
// path of the catalog it was backed up from)
|
||||
let path_key = format!("{}:{}", key(&data.source), number(collection, "id_local"));
|
||||
let original_key = data.catalog_path.as_ref().map(|p| format!("{}:{}", key(p), number(collection, "id_local")));
|
||||
let collection_key = data.catalog_id.as_ref().map_or_else(|| path_key.clone(), |c| format!("lrcat:{c}:{}", number(collection, "id_local")));
|
||||
// A path can be reused by a different catalog. Without an ID we cannot prove that an
|
||||
// owned path key belongs to this input, so refuse instead of silently mixing albums.
|
||||
if data.catalog_id.is_none()
|
||||
&& [Some(&path_key), original_key.as_ref()].into_iter().flatten().any(|k| index.collection_owners.contains_key(k))
|
||||
{
|
||||
return Err(error(
|
||||
"the Lightroom catalog has no stable identity and its path was previously associated with a catalog; cannot safely match collections",
|
||||
));
|
||||
}
|
||||
// a key recorded for another catalog (by its id) is not this one, whatever its path
|
||||
let mine = |k: &String| match (data.catalog_id.as_ref(), index.collection_owners.get(k)) {
|
||||
(Some(c), Some(owner)) => owner == c,
|
||||
_ => true,
|
||||
};
|
||||
let id = [Some(&collection_key), Some(&path_key), original_key.as_ref()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|k| mine(k))
|
||||
.filter_map(|k| index.collections.get(k).copied())
|
||||
.map(lightcraft_catalog::AlbumId)
|
||||
.filter(|id| s.catalog.album(*id).is_some() && !assigned.contains(id));
|
||||
let id = match indexed {
|
||||
.find(|id| s.catalog.album(*id).is_some() && !assigned.contains(id));
|
||||
let id = match id {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
let id = s.catalog.alloc_album_id();
|
||||
@@ -1027,7 +1115,16 @@ fn stage_collections(
|
||||
}
|
||||
};
|
||||
assigned.insert(id);
|
||||
index.collections.insert(collection_key, id.0);
|
||||
// recorded under its id and the live catalog's path (a backup's: the catalog it was made
|
||||
// from), so a later import of the same catalog finds it in either order; a zip's own path
|
||||
// is not kept when the catalog's is known (every dated backup has a new one)
|
||||
let path_kept = if data.catalog_path.is_some() { None } else { Some(path_key) };
|
||||
for k in [Some(collection_key), path_kept, original_key].into_iter().flatten() {
|
||||
if let Some(c) = &data.catalog_id {
|
||||
index.collection_owners.insert(k.clone(), c.clone());
|
||||
}
|
||||
index.collections.insert(k, id.0);
|
||||
}
|
||||
albums.insert(number(collection, "id_local"), id);
|
||||
}
|
||||
let parents: HashMap<_, _> = rows.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect();
|
||||
|
||||
@@ -24,6 +24,8 @@ fn sample() -> CatalogImport {
|
||||
photo.image.insert("captureTime".into(), json!("2024-01-16T12:34:56"));
|
||||
CatalogImport {
|
||||
source: "test.lrcat".into(),
|
||||
catalog_id: None,
|
||||
catalog_path: None,
|
||||
photos: vec![copy, photo],
|
||||
collections: vec![
|
||||
row(json!({"id_local":9,"name":"Travel","creationId":"collection.group"})),
|
||||
@@ -1088,6 +1090,178 @@ fn wal_checksums_cover_commits_without_materializing_historical_databases() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #2592: a catalog in Lightroom's backup layout (`Backups/<date>/<name>.zip`), with one
|
||||
/// collection and the catalog's own id.
|
||||
fn backup_fixture(root: &Path, catalog_id: &str) -> (PathBuf, PathBuf) {
|
||||
use SqlValue::{Integer as I, Null as N, Text as T};
|
||||
let mut tables: Vec<(&str, &str, Vec<Vec<SqlValue>>)> = one_row(photo_tables(("/catalog/", "")));
|
||||
tables.push((
|
||||
"AgLibraryCollection",
|
||||
"id_local INTEGER PRIMARY KEY, creationId, name, parent, systemOnly",
|
||||
vec![vec![N, T("com.adobe.ag.library.collection".into()), T("Keepers".into()), N, I(0)]],
|
||||
));
|
||||
tables.push(("AgLibraryCollectionImage", "id_local INTEGER PRIMARY KEY, collection, image", vec![vec![N, I(1), I(1)]]));
|
||||
tables.push((
|
||||
"Adobe_variablesTable",
|
||||
"id_local INTEGER PRIMARY KEY, id_global, name, type, value",
|
||||
vec![vec![N, T("v1".into()), T("Adobe_storeProviderID".into()), N, T(catalog_id.into())]],
|
||||
));
|
||||
let bytes = native_catalog_rows(&tables, None);
|
||||
let folder = root.join("Lightroom");
|
||||
let dated = folder.join("Backups").join("2023-11-07 0900");
|
||||
std::fs::create_dir_all(&dated).unwrap();
|
||||
let live = folder.join("Cat.lrcat");
|
||||
std::fs::write(&live, &bytes).unwrap();
|
||||
let zip = dated.join("Cat.zip");
|
||||
let files: [(&str, &[u8]); 2] = [("Cat.lrcat", &bytes), ("Cat.lrcat-data/CURRENT", b"MANIFEST-000005\n")];
|
||||
std::fs::write(&zip, crate::lightroom_backup::tests::zip(&files, true, false)).unwrap();
|
||||
(live, zip)
|
||||
}
|
||||
|
||||
/// How many albums the library has.
|
||||
fn albums(s: &crate::Session) -> usize {
|
||||
s.catalog.albums().count()
|
||||
}
|
||||
|
||||
/// The zip imports the same photos and collections as its catalog, with the zip as source, no temp files and the zip unchanged.
|
||||
#[test]
|
||||
fn a_backup_zip_imports_like_its_catalog_and_leaves_no_temporary_files() {
|
||||
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-zip-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
|
||||
let zip_before = std::fs::read(&zip).unwrap();
|
||||
let from_zip = read(&zip).unwrap();
|
||||
let from_live = read(&live).unwrap();
|
||||
assert_eq!(from_zip.source, zip.to_string_lossy(), "the zip is the import's source");
|
||||
assert_eq!(from_zip.catalog_id.as_deref(), Some("968AF29B-EEE2-481E-8AF9-55DD82965F49"));
|
||||
assert_eq!((from_zip.photos.len(), from_zip.collections.len()), (from_live.photos.len(), from_live.collections.len()));
|
||||
assert_eq!(from_zip.photos[0].path, from_live.photos[0].path);
|
||||
// the live catalog is gone (Lightroom uninstalled): the backup alone imports into a library
|
||||
std::fs::remove_file(&live).unwrap();
|
||||
let lib = root.join("Library");
|
||||
let mut s = crate::Session::new();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
let report = import(&mut s, &zip, false).unwrap();
|
||||
assert_eq!((report["photos"].as_u64(), report["collections"].as_u64()), (Some(1), Some(1)));
|
||||
assert_eq!(report["source"], json!(zip.to_string_lossy()));
|
||||
assert_eq!(albums(&s), 1);
|
||||
let interop: Vec<_> = std::fs::read_dir(lib.join("Interop")).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
|
||||
assert!(!interop.iter().any(|n| n.starts_with("lc-lrbackup-")), "the unpacked catalog is removed: {interop:?}");
|
||||
assert_eq!(std::fs::read(&zip).unwrap(), zip_before, "the backup is only read");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Issue #2606: the backup of an imported catalog matches its collections by the catalog id.
|
||||
#[test]
|
||||
fn importing_a_backup_after_its_catalog_adds_no_album_twice() {
|
||||
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-twice-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
|
||||
let mut s = crate::Session::new();
|
||||
s.open_library(root.join("Library"), false).unwrap();
|
||||
import(&mut s, &live, false).unwrap();
|
||||
assert_eq!(albums(&s), 1);
|
||||
let again = import(&mut s, &zip, false).unwrap();
|
||||
assert_eq!(again["imported"], 0, "the photos are matched by their Lightroom id");
|
||||
assert_eq!(albums(&s), 1, "the collections are matched by the catalog's id, not its path");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A backup of a catalog that an earlier release imported (collections keyed on the live
|
||||
/// `.lrcat` path, no catalog id) finds those albums through the path it was backed up from.
|
||||
#[test]
|
||||
fn a_backup_finds_collections_an_earlier_release_keyed_on_the_live_catalog_path() {
|
||||
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-legacy-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
|
||||
let mut s = crate::Session::new();
|
||||
s.open_library(root.join("Library"), false).unwrap();
|
||||
// an earlier release: the live catalog imported without its id (path keys only)
|
||||
let mut old = read(&live).unwrap();
|
||||
old.catalog_id = None;
|
||||
apply(&mut s, old, false).unwrap();
|
||||
assert_eq!(albums(&s), 1);
|
||||
let backup = read(&zip).unwrap();
|
||||
assert_eq!(backup.catalog_path.as_deref(), Some(live.to_string_lossy().as_ref()), "where the zip's catalog was");
|
||||
apply(&mut s, backup, false).unwrap();
|
||||
assert_eq!(albums(&s), 1, "the backup finds the albums keyed on the live catalog's path");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Issue #2606, the other order: a backup without a catalog id imported first, then the live
|
||||
/// catalog (no id either) finds the same albums through the live path the backup recorded.
|
||||
#[test]
|
||||
fn the_live_catalog_after_a_backup_without_an_id_adds_no_album_twice() {
|
||||
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-noid-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
|
||||
let mut s = crate::Session::new();
|
||||
s.open_library(root.join("Library"), false).unwrap();
|
||||
let mut backup = read(&zip).unwrap();
|
||||
backup.catalog_id = None;
|
||||
apply(&mut s, backup, false).unwrap();
|
||||
assert_eq!(albums(&s), 1);
|
||||
let mut current = read(&live).unwrap();
|
||||
current.catalog_id = None;
|
||||
apply(&mut s, current, false).unwrap();
|
||||
assert_eq!(albums(&s), 1, "the live catalog finds the albums the backup imported");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Issue #2606, the reviewer's second order: a backup with an id, then the live catalog read
|
||||
/// without one, is rejected rather than risk matching a different catalog at the same path.
|
||||
#[test]
|
||||
fn the_live_catalog_without_an_id_after_a_backup_with_one_adds_no_album_twice() {
|
||||
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-idthennone-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
|
||||
let mut s = crate::Session::new();
|
||||
s.open_library(root.join("Library"), false).unwrap();
|
||||
apply(&mut s, read(&zip).unwrap(), false).unwrap();
|
||||
let mut current = read(&live).unwrap();
|
||||
current.catalog_id = None;
|
||||
let err = apply(&mut s, current, false).unwrap_err();
|
||||
assert!(err.to_string().contains("no stable identity"));
|
||||
assert_eq!(albums(&s), 1, "an ambiguous path must not change albums");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Two different catalogs (different ids) that sat at the same path, one after the other (a
|
||||
/// new computer's default location, a catalog recreated), keep their own albums even with the
|
||||
/// same collection `id_local`.
|
||||
#[test]
|
||||
fn two_catalogs_at_the_same_path_keep_their_own_albums() {
|
||||
let root = std::env::temp_dir().join(format!("lightcraft-lrcat-samepath-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let (live, _) = backup_fixture(&root, "AAAAAAAA-0000-0000-0000-000000000001");
|
||||
let mut s = crate::Session::new();
|
||||
s.open_library(root.join("Library"), false).unwrap();
|
||||
apply(&mut s, read(&live).unwrap(), false).unwrap();
|
||||
// another catalog, now at the same path
|
||||
let (live2, _) = backup_fixture(&root, "BBBBBBBB-0000-0000-0000-000000000002");
|
||||
assert_eq!(live, live2);
|
||||
apply(&mut s, read(&live2).unwrap(), false).unwrap();
|
||||
assert_eq!(albums(&s), 2, "the second catalog's collection is its own album");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Libraries imported by earlier releases (path keys) still find their albums.
|
||||
#[test]
|
||||
fn collections_imported_before_the_catalog_id_was_read_are_still_matched_by_path() {
|
||||
let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-pathkey-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut s = crate::Session::new();
|
||||
s.open_library(&dir, false).unwrap();
|
||||
// an import made by an earlier release: no catalog id, keys on the path
|
||||
apply(&mut s, sample(), false).unwrap();
|
||||
let before = albums(&s);
|
||||
let mut data = sample();
|
||||
data.catalog_id = Some("A-B".into());
|
||||
apply(&mut s, data, false).unwrap();
|
||||
assert_eq!(albums(&s), before, "the old path keys still find the albums");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_reimport_keeps_copy_and_collection_ids_and_capture_time() {
|
||||
let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-reimport-{}", std::process::id()));
|
||||
@@ -1175,7 +1349,9 @@ fn native_catalog_with_last_table_page(tables: &[(&str, &str, Vec<SqlValue>)], l
|
||||
/// table's root page.
|
||||
fn native_catalog_rows(tables: &[(&str, &str, Vec<Vec<SqlValue>>)], last_page: Option<i64>) -> Vec<u8> {
|
||||
use SqlValue::{Integer as I, Text as T};
|
||||
let mut bytes = vec![0u8; 5 * 2048];
|
||||
// the schema page, then one page per table (at least four: the photo tables)
|
||||
let pages = (tables.len() + 1).max(5);
|
||||
let mut bytes = vec![0u8; pages * 2048];
|
||||
bytes[..16].copy_from_slice(b"SQLite format 3\0");
|
||||
bytes[16..18].copy_from_slice(&2048u16.to_be_bytes());
|
||||
bytes[18] = 1;
|
||||
@@ -1183,7 +1359,7 @@ fn native_catalog_rows(tables: &[(&str, &str, Vec<Vec<SqlValue>>)], last_page: O
|
||||
bytes[21] = 64;
|
||||
bytes[22] = 32;
|
||||
bytes[23] = 32;
|
||||
bytes[28..32].copy_from_slice(&5u32.to_be_bytes());
|
||||
bytes[28..32].copy_from_slice(&(pages as u32).to_be_bytes());
|
||||
bytes[44..48].copy_from_slice(&4u32.to_be_bytes());
|
||||
bytes[56..60].copy_from_slice(&1u32.to_be_bytes());
|
||||
let mut schema = Vec::new();
|
||||
|
||||
@@ -6,14 +6,20 @@
|
||||
//! an empty LightCraft library inside Lightroom's folder; [`Session::open_library`] refuses with
|
||||
//! [`EngineError::LightroomCatalog`] instead, and the app offers File ▸ Import Lightroom Catalog….
|
||||
//!
|
||||
//! What counts (only names are looked at; no catalog is opened or read):
|
||||
//! What counts (only names are looked at, and a backup zip's list of files; no catalog is opened
|
||||
//! or read):
|
||||
//! - a LightCraft library (`catalog.snap` or `catalog.log` in the folder) is never a Lightroom
|
||||
//! catalog, whatever else the folder holds: it opens as before;
|
||||
//! - a path named `*.lrcat` or one of its companions (`*.lrcat-wal`, `*.lrcat-shm`,
|
||||
//! `*.lrcat-journal`, `*.lrcat.lock`);
|
||||
//! - a folder named `*.lrdata` or `*.lrcat-data` (Lightroom's previews and data);
|
||||
//! - a folder holding a `*.lrcat` at its top level (the catalog folder itself), or `Backups/`
|
||||
//! next to one.
|
||||
//! next to one;
|
||||
//! - Lightroom's backups (issue #2592), even with the catalog itself gone: a `Backups/` folder or
|
||||
//! one of its dated folders, `Backups/YYYY-MM-DD HHMM/`, holding a `*.zip` with one `.lrcat` in
|
||||
//! it ([`crate::lightroom_backup::holds_catalog`]). A dated folder names
|
||||
//! its zip; `Backups/` names one only when it holds a single backup, since the person has to choose
|
||||
//! among several (the import then asks for the file).
|
||||
//!
|
||||
//! The folder scan is bounded ([`SCAN_LIMIT`] entries, top level only) and every I/O error just
|
||||
//! means "not found": this never fails and never panics.
|
||||
@@ -133,6 +139,41 @@ pub fn lightroom_catalog_at(path: &Path) -> Option<LightroomPlace> {
|
||||
{
|
||||
return Some(LightroomPlace { catalog: Some(catalog) });
|
||||
}
|
||||
// `Backups/` alone (the catalog deleted): its backup when there is only one; with several,
|
||||
// which one to import is the person's choice
|
||||
if lower == "backups"
|
||||
&& let Some(backups) = backup_zips(path)
|
||||
{
|
||||
let catalog = if backups.len() == 1 { backups.into_iter().next() } else { None };
|
||||
return Some(LightroomPlace { catalog });
|
||||
}
|
||||
// a dated backup folder, `Backups/2023-11-07 0900/`
|
||||
if parent.and_then(lower_name).as_deref() == Some("backups")
|
||||
&& let Some(zip) = find_backup_zip(path)
|
||||
{
|
||||
return Some(LightroomPlace { catalog: Some(zip) });
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The first `*.zip` file (by name) at the top level of `dir` that holds a Lightroom catalog,
|
||||
/// looking at no more than [`SCAN_LIMIT`] entries.
|
||||
fn find_backup_zip(dir: &Path) -> Option<PathBuf> {
|
||||
let entries = std::fs::read_dir(dir).ok()?;
|
||||
entries
|
||||
.take(SCAN_LIMIT)
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| crate::lightroom_backup::is_backup(p) && p.is_file())
|
||||
.filter(|p| crate::lightroom_backup::holds_catalog(p))
|
||||
.min()
|
||||
}
|
||||
|
||||
/// The backup zips in the dated folders of `backups`, one per folder; `None` when there are none.
|
||||
fn backup_zips(backups: &Path) -> Option<Vec<PathBuf>> {
|
||||
let entries = std::fs::read_dir(backups).ok()?;
|
||||
let zips: Vec<PathBuf> =
|
||||
entries.take(SCAN_LIMIT).flatten().map(|e| e.path()).filter(|p| p.is_dir()).filter_map(|d| find_backup_zip(&d)).collect();
|
||||
(!zips.is_empty()).then_some(zips)
|
||||
}
|
||||
@@ -241,8 +241,14 @@ impl LightroomJob {
|
||||
return Err(cancelled());
|
||||
}
|
||||
// (reading stops with a message when `cancel` is set: the flag says it was cancelled)
|
||||
let mut data = lightroom_catalog::read_with_progress(&self.path, cancel, &self.progress.catalog_total, &self.progress.catalog_done)
|
||||
.map_err(|e| if cancel.load(Ordering::Relaxed) { cancelled() } else { error(e) })?;
|
||||
let mut data = lightroom_catalog::read_source(
|
||||
&self.path,
|
||||
self.archive_dir.as_deref(),
|
||||
cancel,
|
||||
&self.progress.catalog_total,
|
||||
&self.progress.catalog_done,
|
||||
)
|
||||
.map_err(|e| if cancel.load(Ordering::Relaxed) { cancelled() } else { error(e) })?;
|
||||
lightroom_catalog::validate_for_job(&data).map_err(error)?;
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err(cancelled());
|
||||
@@ -350,6 +356,8 @@ mod tests {
|
||||
fn empty_data() -> CatalogImport {
|
||||
CatalogImport {
|
||||
source: "fixture.lrcat".into(),
|
||||
catalog_id: None,
|
||||
catalog_path: None,
|
||||
photos: Vec::new(),
|
||||
collections: Vec::new(),
|
||||
members: Vec::new(),
|
||||
@@ -384,6 +392,8 @@ mod tests {
|
||||
PreparedLightroom {
|
||||
data: CatalogImport {
|
||||
source: "fixture.lrcat".into(),
|
||||
catalog_id: None,
|
||||
catalog_path: None,
|
||||
photos: vec![lightroom_catalog::CatalogPhoto {
|
||||
source_id: 1,
|
||||
uuid: "fixture-photo".into(),
|
||||
|
||||
@@ -98,6 +98,37 @@ fn an_lrdata_folder_whose_catalog_was_renamed_finds_the_one_next_to_it() {
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Issue #2592: someone who deleted Lightroom and its catalog keeps only `Backups/`; that folder and
|
||||
/// each dated folder in it are refused. A dated folder names its zip; `Backups/` names one only when
|
||||
/// it is the only backup (with several, the import asks which).
|
||||
#[test]
|
||||
fn lightroom_backups_without_their_catalog_are_refused_and_name_the_zip() {
|
||||
let root = temp_dir("backups");
|
||||
let backups = root.join("Lightroom").join("Backups");
|
||||
let backup = crate::lightroom_backup::tests::zip(&[("Cat.lrcat", b"SQLite format 3\0")], true, false);
|
||||
for (dated, zip) in [("2019-03-26 0751", "Cat-2.lrcat.zip"), ("2023-11-07 0900", "Cat-v13.zip")] {
|
||||
std::fs::create_dir_all(backups.join(dated)).unwrap();
|
||||
std::fs::write(backups.join(dated).join(zip), &backup).unwrap();
|
||||
}
|
||||
// a zip without a catalog in a dated folder is not a backup
|
||||
std::fs::create_dir_all(backups.join("2024-01-01 1200")).unwrap();
|
||||
std::fs::write(backups.join("2024-01-01 1200").join("photos.zip"), crate::lightroom_backup::tests::zip(&[("a.jpg", b"x")], false, false))
|
||||
.unwrap();
|
||||
assert_eq!(lightroom_catalog_at(&backups.join("2024-01-01 1200")), None, "no catalog in the zip");
|
||||
let newest = backups.join("2023-11-07 0900").join("Cat-v13.zip");
|
||||
assert_eq!(lightroom_catalog_at(&backups), Some(LightroomPlace { catalog: None }), "two backups: no arbitrary pick");
|
||||
refused(&root, &backups.join("2023-11-07 0900"), &newest);
|
||||
refused(&root, &backups.join("2019-03-26 0751"), &backups.join("2019-03-26 0751").join("Cat-2.lrcat.zip"));
|
||||
std::fs::remove_dir_all(backups.join("2019-03-26 0751")).unwrap();
|
||||
refused(&root, &backups, &newest);
|
||||
// a folder of zips that isn't in a `Backups/` folder is not Lightroom's
|
||||
let other = root.join("Downloads");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
std::fs::write(other.join("photos.zip"), &backup).unwrap();
|
||||
assert_eq!(lightroom_catalog_at(&other), None);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_folder_still_becomes_a_library() {
|
||||
let root = temp_dir("empty");
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn default_location(app: &LightcraftApp) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// The new library's default name: the catalog's file name without `.lrcat` (`Travel.lrcat` →
|
||||
/// `Travel`), or `Travel 2`, `Travel 3`… when `location` has something by that name already.
|
||||
/// `Travel`; a backup's `Travel.zip` gives `Travel` too), or `Travel 2`, `Travel 3`… when `location` has something by that name already.
|
||||
pub fn default_name(catalog: &Path, location: Option<&Path>) -> String {
|
||||
let stem = catalog.file_stem().map(|s| s.to_string_lossy().trim().to_string()).filter(|s| !s.is_empty());
|
||||
let stem = stem.unwrap_or_else(|| "Lightroom Catalog".to_string());
|
||||
@@ -353,6 +353,7 @@ mod tests {
|
||||
fn the_new_library_is_named_after_the_catalog() {
|
||||
assert_eq!(default_name(Path::new("/x/Travel.lrcat"), None), "Travel");
|
||||
assert_eq!(default_name(Path::new("/x/Lightroom Catalog-v13-3.lrcat"), None), "Lightroom Catalog-v13-3");
|
||||
assert_eq!(default_name(Path::new("/x/Backups/2026-10-22 1200/Travel.zip"), None), "Travel");
|
||||
// nothing to name it after
|
||||
assert_eq!(default_name(Path::new(""), None), "Lightroom Catalog");
|
||||
// a name taken in the location: the next free one
|
||||
|
||||
@@ -175,6 +175,7 @@ fn busy(app: &LightcraftApp) -> Result<(), String> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn spawn_inspect(
|
||||
path: PathBuf,
|
||||
temp: Option<PathBuf>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
progress: LightroomProgress,
|
||||
tx: mpsc::Sender<Message>,
|
||||
@@ -184,7 +185,7 @@ fn spawn_inspect(
|
||||
.name("lc-lightroom-inspect".into())
|
||||
.spawn(move || {
|
||||
let result = lightcraft_engine::guard::catch("Lightroom inspect", || {
|
||||
lightcraft_engine::lightroom_catalog::read_with_progress(&path, &cancel, &progress.catalog_total, &progress.catalog_done)
|
||||
lightcraft_engine::lightroom_catalog::read_source(&path, temp.as_deref(), &cancel, &progress.catalog_total, &progress.catalog_done)
|
||||
})
|
||||
.and_then(|r| r.map(inspect_report));
|
||||
let _ = tx.send(Message::Inspected(result));
|
||||
@@ -385,7 +386,8 @@ fn start_inspect(app: &mut LightcraftApp, path: PathBuf, ctx: &egui::Context) ->
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let progress = LightroomProgress::default();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
spawn_inspect(path.clone(), cancel.clone(), progress.clone(), tx, ctx.clone())?;
|
||||
let temp = lightcraft_engine::lightroom_catalog::backup_temp_root(&app.session);
|
||||
spawn_inspect(path.clone(), temp, cancel.clone(), progress.clone(), tx, ctx.clone())?;
|
||||
app.lightroom_last = None;
|
||||
app.lightroom = Some(LightroomTask::new(&app.session, Kind::Inspect, path.clone(), cancel, progress, rx));
|
||||
Ok(json!({"running": true, "kind": "inspect", "path": path}))
|
||||
@@ -788,6 +790,8 @@ mod tests {
|
||||
fn inspect_report_keeps_empty_catalog_shape() {
|
||||
let report = inspect_report(CatalogImport {
|
||||
source: "synthetic.lrcat".into(),
|
||||
catalog_id: None,
|
||||
catalog_path: None,
|
||||
photos: Vec::new(),
|
||||
collections: Vec::new(),
|
||||
members: Vec::new(),
|
||||
|
||||
@@ -1353,8 +1353,11 @@ fn ui_commands_10(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Va
|
||||
let path = match p.get("path").and_then(Value::as_str).map(str::to_string) {
|
||||
Some(path) => Some(path),
|
||||
None => {
|
||||
let req =
|
||||
PickRequest::file(crate::i18n::tr("Import Lightroom Catalog"), crate::i18n::tr("Lightroom Classic Catalog"), &["lrcat"]);
|
||||
let req = PickRequest::file(
|
||||
crate::i18n::tr("Import Lightroom Catalog"),
|
||||
crate::i18n::tr("Lightroom Classic Catalog"),
|
||||
&["lrcat", "zip"],
|
||||
);
|
||||
match crate::pick::ask(app, id, p, "path", req, |s| s.pick_lightroom_catalog.as_mut().and_then(|f| f()).map(|x| vec![x])) {
|
||||
Picked::Now(v) => v.into_iter().next(),
|
||||
Picked::Later | Picked::Unavailable => None,
|
||||
|
||||
+2
-1
@@ -27,7 +27,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app
|
||||
| 10 B | **Per-model verification thin, plus cheap per-body decode fixes**: 557 of 1,446 Adobe models verified (39%), ~86% of photographers on a verified body; Nikon 5 bodies verified, Canon 34, Leica 14 (the Q3 by a recorded check of 38 private DNGs). Cheap fixes: Z 6II packed 14-bit NEF (#769, PR #671), Sony A100 regression (#702); F828 SRF now discovered and imported as preview-only, sensor decoding still missing, DSLR-A200…A390 / A850 12-bit ARW (#535) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 25–45 | [raw-parity](raw-parity.md#by-maker-measured) |
|
||||
| 11 | **Enhance: Raw Details, Super Resolution; trained denoise weights and X-Trans** | ENH rows 0%; denoise Bayer only; the built-in denoiser is classical (block-matching collaborative filtering), RawNIND weights GPL and opt-in | Fujifilm users get no AI denoise; very noisy files gain less than from a trained model | 30–60 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) |
|
||||
| 12 | **Content-aware / generative remove, detect distractions, reflections removal** | REM rows 75%; patch synthesis missing | cleanup work goes back to Photoshop | 25–45 (+ generative model) | [target-app-parity](target-app-parity.md#ai) |
|
||||
| 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; main-file pages read on demand up to 16 GiB, with dense-table and WAL bounds retained (#798); offline record counts and destination are now shown in a lasting import result; catalog VIDEO records match the Videos filter, with older classification repaired on reimport; before an import the app asks whether the catalog merges into the open library or goes into a new library (opt-out in Settings, #2672) | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) |
|
||||
| 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; main-file pages read on demand up to 16 GiB, with dense-table and WAL bounds retained (#798); offline record counts and destination are now shown in a lasting import result; catalog VIDEO records match the Videos filter, with older classification repaired on reimport; before an import the app asks whether the catalog merges into the open library or goes into a new library (opt-out in Settings, #2672); Lightroom's backup zips import directly (#2592) | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) |
|
||||
| 14 | **HDR display** (EDR / Windows HDR); the headroom limit and SDR rendition from `crs` XMP (the HDR switch, `HDREditMode`, is read). HLG AVIF export done; the display's SDR/HDR decision is tested, blocked on eframe's 8-bit surface | HDR rows 70%; LR-VIEW-HDR-DISPLAY ⬜ | HDR editing works blind on HDR monitors | 12–25 | [hardware-parity](hardware-parity.md) |
|
||||
| 15 | **Print module**: identity plate / watermark / photo info overlays, Cut Guides for the packages, Custom Package Auto Layout, printer-driver Page Setup and direct printing, JPEG file output (the Print dialog writes a colour-managed PDF) | LRC-PRINT rows | Classic users who print | 15–25 | [target-app-parity](target-app-parity.md#features) |
|
||||
| 16 | **Map view, Book, Slideshow module, publish services** | LRC-MAP / BOOK / SS rows ⬜ | Classic users; publish services matter for Flickr / SmugMug workflows | 60–100 | [target-app-parity](target-app-parity.md#features) |
|
||||
@@ -90,6 +90,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-01 | minor | Gap 13: Lightroom catalog backup zips import directly, and a backup of an imported catalog adds no collection twice (#2592); the gap stays open |
|
||||
| 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. |
|
||||
| 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). |
|
||||
| 2026-11-05 | minor | Gap 3: process V5 rolls a raw's tone curve off into white in stops, so raising Exposure keeps the highlights the sensor recorded (#1632); the gap stays open (no Lightroom comparison) and hours are unchanged |
|
||||
|
||||
@@ -42,6 +42,9 @@ being the choice the window opens with) or merges when the setting says so. A ca
|
||||
refused before a new library is made. The engine command `library.importLightroom` always imports into the library
|
||||
open now.
|
||||
|
||||
A Lightroom Classic catalog backup is imported the same way, as the `.zip` Lightroom writes
|
||||
(`Backups/YYYY-MM-DD HHMM/<name>.zip`; see *Catalog backups* below).
|
||||
|
||||
Equivalent commands:
|
||||
|
||||
```text
|
||||
@@ -164,6 +167,39 @@ photo and its virtual copies out of the library. To import originals on a share,
|
||||
from that share. A path that is not a path on this computer (a Windows drive path read on macOS or
|
||||
Linux) is not looked at either and stays catalogued as missing.
|
||||
|
||||
## Catalog backups
|
||||
|
||||
Lightroom Classic backs a catalog up as `<catalog folder>/Backups/YYYY-MM-DD HHMM/<name>.zip`: one `.lrcat` (plus,
|
||||
since Classic 12, a small `<name>.lrcat-data/` folder the import does not need). Someone who has removed Lightroom
|
||||
and its catalog may have nothing else, so `library.importLightroom` / `library.inspectLightroom` and File ▸ Import
|
||||
Lightroom Catalog… take the zip directly (issue #2592, `crates/engine/src/lightroom_backup.rs`):
|
||||
|
||||
- The `.lrcat` entry is inflated by streaming (stored or deflated, ZIP64 included) into a private folder,
|
||||
`Interop/lc-lrbackup-<pid>-<time>/` in the open library (the system's temporary folder when the library is not
|
||||
on disk), checked against the zip's size and CRC-32, read like any catalog, and removed after the read, on an
|
||||
error and on cancel alike. A folder left by a crash is removed by the next backup import once it is a day old.
|
||||
The zip is only read. A zip with no `.lrcat`, more than one, a damaged or cut-short entry, or a catalog over
|
||||
16 GiB is refused with a message. A known space shortage is refused before extraction; later write errors are reported.
|
||||
- The import's `source` is the zip. Paths the catalog records relative to itself (`relativePathFromCatalog`) are
|
||||
taken from where the catalog was: two folders above a dated backup folder, else next to the zip.
|
||||
- Open Library given `Backups/` without its catalog, or a dated folder in it, makes no library there and offers the
|
||||
import: of the dated folder's zip, of the only backup in `Backups/`, or, when `Backups/` holds several, of the zip
|
||||
the person picks (the file dialog asks).
|
||||
- Collections are matched across imports by the catalog's own id (`Adobe_storeProviderID` in
|
||||
`Adobe_variablesTable`), which every backup of the catalog keeps, so importing a backup of a catalog already
|
||||
imported adds no collection twice. Collections imported by earlier releases, keyed on the catalog's path, are
|
||||
still found by that key. Each key records the id it was written for, so two catalogs with different ids that sat
|
||||
at the same path keep their own albums. A catalog without `Adobe_storeProviderID` (every Lightroom Classic
|
||||
catalog checked, from Lightroom 7 to Classic 13, has one; only a damaged or foreign file lacks it) is known by its
|
||||
path alone. If that path is already associated with a known catalog ID, the importer refuses the ambiguous
|
||||
match rather than silently combining different catalogs. Unowned legacy path keys can still match. Photos are matched as
|
||||
before, by Lightroom's image id and path: a backup whose photos were at another place (an older backup from
|
||||
before a move) adds them as other records.
|
||||
|
||||
Checked on 2026-10-22 on a real catalog (2,740 photos, 96 collections) and its four backups from Lightroom 7
|
||||
(2018) to Classic 13 (2023), 88 MB zips holding 138 MB catalogs: each zip imports the same photos and collections
|
||||
as its unpacked catalog in about 2.4 s on an Apple M4, leaves no file behind and is not changed.
|
||||
|
||||
## Historical local validation
|
||||
|
||||
Validated in a local Linux environment after upstream reconciliation: 47 catalog-focused tests, nine pipeline spot tests, the exact sparse-catalog regression, and all eight `cargo xtask ci` stages passed. The full gate recorded 3,166 passing test executions, zero failures, and 28 ignored tests. An original synthetic sparse catalog with a required image-table page beyond 1 GiB also passed headless application import and selection; its expected missing-original placeholder retained its five-star rating. This snapshot check does not establish native-window coverage or dense-catalog performance.
|
||||
@@ -701,7 +701,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-
|
||||
| LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N |
|
||||
| LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo; each pane says “Rendering…” (widget `compare:rendering:<pane>`) or “This photo can't be opened” (`compare:renderFailed:<pane>`) as the loupe does. Escape → Detail without losing edits; pins are catalog-local; missing/deleted photos refused and deleted references no longer drawn (Windows regression/native smoke verified) |
|
||||
| LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) |
|
||||
| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders; VIDEO records match the Videos filter, with reimport repairing older image classification while keeping edits and memberships; a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) |
|
||||
| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders; VIDEO records match the Videos filter, with reimport repairing older image classification while keeping edits and memberships; a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891). Lightroom catalog backups (`Backups/<date>/<name>.zip`) import directly: the `.lrcat` is streamed (ZIP64 included) into a private folder in the library, CRC-checked, read and deleted; the zip is only read; `Backups/` or a dated folder given to Open Library offers that import (asking which zip when `Backups/` holds several); collections are matched by the catalog's `Adobe_storeProviderID`, so a backup adds no collection twice (`crates/engine/src/lightroom_backup.rs`, issue #2592) |
|
||||
| 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 (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); 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`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) |
|
||||
| LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290); the library last opened that is missing at launch (moved, or on a drive or network share that isn't connected) opens the can't-open window (Try Again, Choose Another, Continue Without Saving, Quit) instead of a new library with demo photos in its place (`apps/lightcraft/src/tests.rs`: `a_remembered_library_missing_at_launch_is_reported_not_made_anew`, issue #3239); a library's `catalog.snap` or folder given at launch (a double-click in the file manager) opens that library, through the usual launch path (lock check), makes it the library in use and is never imported; a second library argument gets a notice |
|
||||
| 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`), `crates/ui-egui/src/tests/move_folder.rs` | 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); Move Folder To… (here and in Folders) asks for the destination in a folder dialog that doesn't hold up the window (issue #3140); the rows of the standard places themselves (Pictures, Desktop, Downloads, Home) offer neither Rename Folder… nor Move Folder To…, while the folders inside them and the ones kept with Browse Folder… do, starting from their real name; `folder.rename` and `folder.move` refuse the home folder and its Pictures, Desktop and Downloads for every caller |
|
||||
@@ -1048,6 +1048,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
|
||||
| 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) |
|
||||
| 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) |
|
||||
| 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) |
|
||||
| 2026-11-01 | minor | LRC-LIB-CATALOG-IMPORT: Lightroom catalog backup `.zip` files import directly (streamed into a temporary folder in the library, deleted after reading); Open Library recognises `Backups/` and its dated folders; collections are matched by the catalog's `Adobe_storeProviderID` (issue #2592); status unchanged (🟡) |
|
||||
| 2026-10-20 | patch | LR-PRE-PANEL, LR-PRE-AMOUNT: a preset changes only the settings it names; each is measured from the photo's import look when one is recorded, otherwise from its current value (issue #2159). Statuses and feature counts unchanged. |
|
||||
| 2026-10-17 | minor | LR-EXP-DIALOG: built-in export presets for the issue #2104 delivery targets — Instagram Feed (1080 px, screen sharpening), Instagram Story / Reel (1920 px), Web / Portfolio (2048 px, copyright-only metadata), Full Resolution Master (full size, Display P3, quality 95); LR-EXP-PREVIOUS drops its stale "no named export presets yet" note; status unchanged (✅) |
|
||||
| 2026-10-17 | minor | LR-EXP-DIALOG: built-in export presets for the issue #2104 delivery targets — Instagram Feed (1080 px, screen sharpening), Instagram Story / Reel (1920 px), Web / Portfolio (2048 px, copyright and creator metadata), Full Resolution Master (full size, Display P3, quality 95); LR-EXP-PREVIOUS drops its stale "no named export presets yet" note; status unchanged (✅) |
|
||||
|
||||
@@ -74,6 +74,16 @@
|
||||
gives a request 60 s) can ask again once that search has ended (while it runs, a new request is refused as already
|
||||
running), and what was read isn't read again.
|
||||
|
||||
## 2026-11-01
|
||||
|
||||
### Import a Lightroom catalog backup as it is
|
||||
- File ▸ Import Lightroom Catalog… also takes the `.zip` backups Lightroom Classic writes in its `Backups` folder
|
||||
(issue #2592), for when Lightroom and its catalog are gone and only the backups and the photos are left. LightCraft
|
||||
unpacks the catalog into a temporary folder in the library, imports it and deletes the copy; the zip is not
|
||||
changed. Open Library given a `Backups` folder, or one of its dated folders, offers to import the backup.
|
||||
- Importing a backup of a catalog you already imported no longer adds every collection a second time: collections
|
||||
are matched by the catalog's own id, which its backups keep, instead of by the catalog file's path.
|
||||
|
||||
## 2026-10-30
|
||||
|
||||
### Lightroom catalogs with a print inside a collection import their collections
|
||||
|
||||
Reference in new issue
Block a user