diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fed247372f..71d2e93321 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1537,6 +1537,8 @@ pub fn json_delta(old: &Value, new: &Value) -> Option { } } +#[cfg(test)] +mod lightroom_fixture; #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 511f81f308..4af75bb1a9 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -2,10 +2,10 @@ //! //! Archives use a deterministic JSON representation wrapped in zlib. The JSON //! writer streams through a bounded compressor, so an import cannot first build -//! an unbounded archive buffer. Blob columns are omitted by the catalog reader; -//! decoded XMP, -//! settings, history, snapshots, identities, paths, collections & membership -//! remain available for recovery. +//! an unbounded archive buffer. The catalog reader decodes Lightroom's compressed +//! XMP and history-step and snapshot settings and omits other blob columns, so +//! decoded XMP, settings, history, snapshots, identities, paths, collections & +//! membership remain available for recovery. use std::collections::BTreeMap; use std::fs::{self, File}; @@ -29,6 +29,41 @@ pub const MAX_TOTAL_ARCHIVE_BYTES: u64 = 128 * 1024 * 1024; /// Maximum number of managed archives retained. pub const MAX_MANAGED_ARCHIVES: usize = 8; +/// Why [`store`] stored no archive. +#[derive(Debug)] +pub enum StoreError { + /// The archive would pass [`MAX_ARCHIVE_BYTES`], as JSON or on disk. + TooBig, + /// Anything else, such as a folder or file that can't be written. + Failed(String), +} + +impl From for StoreError { + fn from(why: String) -> Self { + Self::Failed(why) + } +} + +impl std::fmt::Display for StoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::TooBig => write!(f, "{TooBig}"), + Self::Failed(why) => f.write_str(why), + } + } +} + +/// What [`store_best_effort`] kept. +#[derive(Debug, PartialEq, Eq)] +pub enum Kept { + /// The whole archive. + All(PathBuf), + /// The archive without history-step and snapshot settings (`text`): with them it passed [`MAX_ARCHIVE_BYTES`]. + WithoutSettings(PathBuf), + /// No archive: it passed [`MAX_ARCHIVE_BYTES`] even without them. + Nothing, +} + const FORMAT_VERSION: u8 = 1; const HEADER: &[u8] = b"LC-LRARCH\0\x01Z"; const NAME_PREFIX: &str = "lightroom-import-"; @@ -44,13 +79,18 @@ const IO_BUFFER: usize = 16 * 1024; /// most [`MAX_MANAGED_ARCHIVES`] and [`MAX_TOTAL_ARCHIVE_BYTES`]. Legacy /// `lightroom-import-*.json` files are deliberately ignored and preserved for /// an explicit caller warning. -pub fn store(directory: &Path, data: &CatalogImport) -> Result { +pub fn store(directory: &Path, data: &CatalogImport) -> Result { + store_with(directory, data, true) +} + +/// [`store`], with the `text` of history steps and snapshots only when `settings`. +fn store_with(directory: &Path, data: &CatalogImport, settings: bool) -> Result { prepare_directory(directory)?; let mut managed = managed_files(directory)?; managed.sort_by_key(|entry| entry.index); let temporary = temporary_path(directory)?; - write_archive(&temporary, data).inspect_err(|_| { + write_archive(&temporary, data, settings).inspect_err(|_| { let _ = remove_managed_file(&temporary); })?; @@ -60,7 +100,7 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result Ok(same) => same, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } }; if same { @@ -75,20 +115,20 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result let index = managed.last().map_or(0, |entry| entry.index.saturating_add(1)); if managed.last().is_some_and(|entry| entry.index == u64::MAX) { let _ = remove_managed_file(&temporary); - return Err("managed Lightroom archive index is exhausted".into()); + return Err(StoreError::Failed("managed Lightroom archive index is exhausted".into())); } let destination = match next_destination(directory, index) { Ok(path) => path, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; let size = match fs::metadata(&temporary) { Ok(meta) => meta.len(), Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } }; let new_entry = Managed { index, path: destination.clone(), size }; @@ -99,40 +139,46 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result Ok(retirees) => retirees, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; let quarantined = match quarantine(&retirees) { Ok(quarantined) => quarantined, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; if let Err(error) = publish_new(&temporary, &destination) { rollback_quarantine(&quarantined); let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } if let Err(error) = remove_managed_file(&temporary) { - return Err(format!("archive published but temporary cleanup failed: {error}")); + return Err(StoreError::Failed(format!("archive published but temporary cleanup failed: {error}"))); } for (old, held) in quarantined { if let Err(error) = remove_managed_file(&held) { - return Err(format!("archive published but could not retire {}: {error}", old.display())); + return Err(StoreError::Failed(format!("archive published but could not retire {}: {error}", old.display()))); } } Ok(destination) } -/// Store source data when possible. An archive that reaches its bounded size is -/// omitted with a warning so catalog import can still complete. -pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result, String> { +/// Store source data when possible, so catalog import can still complete. An archive past +/// [`MAX_ARCHIVE_BYTES`] is stored again without the history-step and snapshot settings, which +/// can be most of a catalog's data; one still too big is not stored at all. +pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result { match store(directory, data) { - Ok(path) => Ok(Some(path)), - Err(error) if error.contains("Lightroom archive exceeds 32 MiB") => Ok(None), - Err(error) => Err(error), + Ok(path) => return Ok(Kept::All(path)), + Err(StoreError::TooBig) => {} + Err(StoreError::Failed(why)) => return Err(why), + } + match store_with(directory, data, false) { + Ok(path) => Ok(Kept::WithoutSettings(path)), + Err(StoreError::TooBig) => Ok(Kept::Nothing), + Err(StoreError::Failed(why)) => Err(why), } } @@ -213,21 +259,25 @@ fn next_destination(directory: &Path, mut index: u64) -> Result Err("no safe managed archive name available".into()) } -fn write_archive(path: &Path, data: &CatalogImport) -> Result<(), String> { +fn write_archive(path: &Path, data: &CatalogImport, settings: bool) -> Result<(), StoreError> { lightcraft_catalog::safe_file::write_atomic_with(path, &mut |raw| { let mut bounded = BoundedWriter { inner: raw, total: 0 }; bounded.write_all(HEADER)?; let mut compressor = ZlibWriter::new(&mut bounded); - serde_json::to_writer(&mut compressor, &ArchiveRef(data)).map_err(json_io)?; + serde_json::to_writer(&mut compressor, &ArchiveRef(data, settings)).map_err(json_io)?; compressor.finish()?; Ok(()) }) .map(|_| ()) - .map_err(|error| format!("could not write Lightroom archive: {error}")) + .map_err(|error| match error.get_ref().is_some_and(|inner| inner.is::()) { + true => StoreError::TooBig, + false => StoreError::Failed(format!("could not write Lightroom archive: {error}")), + }) } +/// A write error from the archive writers keeps its own `io::Error`, so [`TooBig`] can still be told apart. fn json_io(error: serde_json::Error) -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, error.to_string()) + io::Error::from(error) } struct BoundedWriter<'a> { @@ -251,8 +301,20 @@ impl Write for BoundedWriter<'_> { } } +/// The archive writers' error when the archive would pass [`MAX_ARCHIVE_BYTES`]. +#[derive(Debug)] +struct TooBig; + +impl std::fmt::Display for TooBig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Lightroom archive exceeds {} MiB", MAX_ARCHIVE_BYTES >> 20) + } +} + +impl std::error::Error for TooBig {} + fn limit_error() -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, "Lightroom archive exceeds 32 MiB") + io::Error::new(io::ErrorKind::InvalidData, TooBig) } struct ZlibWriter<'a, 'b> { @@ -435,67 +497,70 @@ fn remove_managed_file(path: &Path) -> io::Result<()> { fs::remove_file(path) } -struct ArchiveRef<'a>(&'a CatalogImport); +/// The archive of a catalog import, with the `text` of history steps and snapshots only when `.1`. +struct ArchiveRef<'a>(&'a CatalogImport, bool); impl Serialize for ArchiveRef<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_struct("CatalogImportArchive", 7)?; out.serialize_field("version", &FORMAT_VERSION)?; out.serialize_field("source", &self.0.source)?; - out.serialize_field("photos", &PhotoSeq(&self.0.photos))?; - out.serialize_field("collections", &RowSeq(&self.0.collections))?; - out.serialize_field("members", &RowSeq(&self.0.members))?; - out.serialize_field("collection_content", &RowSeq(&self.0.collection_content))?; + out.serialize_field("photos", &PhotoSeq(&self.0.photos, self.1))?; + out.serialize_field("collections", &RowSeq(&self.0.collections, None))?; + out.serialize_field("members", &RowSeq(&self.0.members, None))?; + out.serialize_field("collection_content", &RowSeq(&self.0.collection_content, None))?; out.serialize_field("warnings", &self.0.warnings)?; out.end() } } -struct PhotoSeq<'a>(&'a [CatalogPhoto]); +struct PhotoSeq<'a>(&'a [CatalogPhoto], bool); impl Serialize for PhotoSeq<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_seq(Some(self.0.len()))?; for photo in self.0 { - out.serialize_element(&PhotoRef(photo))?; + out.serialize_element(&PhotoRef(photo, self.1))?; } out.end() } } -struct PhotoRef<'a>(&'a CatalogPhoto); +struct PhotoRef<'a>(&'a CatalogPhoto, bool); impl Serialize for PhotoRef<'_> { fn serialize(&self, serializer: S) -> Result { let p = self.0; + let skip = (!self.1).then_some("text"); let mut out = serializer.serialize_struct("CatalogPhotoArchive", 8)?; out.serialize_field("source_id", &p.source_id)?; out.serialize_field("uuid", &p.uuid)?; out.serialize_field("path", &p.path)?; - out.serialize_field("image", &RowRef(&p.image))?; + out.serialize_field("image", &RowRef(&p.image, None))?; out.serialize_field("settings", &p.settings)?; out.serialize_field("xmp", &p.xmp)?; out.serialize_field("keywords", &p.keywords)?; - out.serialize_field("history", &RowSeq(&p.history))?; - out.serialize_field("snapshots", &RowSeq(&p.snapshots))?; + out.serialize_field("history", &RowSeq(&p.history, skip))?; + out.serialize_field("snapshots", &RowSeq(&p.snapshots, skip))?; out.end() } } -struct RowSeq<'a>(&'a [BTreeMap]); +/// Rows, each without the column `.1` names. +struct RowSeq<'a>(&'a [BTreeMap], Option<&'a str>); impl Serialize for RowSeq<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_seq(Some(self.0.len()))?; for row in self.0 { - out.serialize_element(&RowRef(row))?; + out.serialize_element(&RowRef(row, self.1))?; } out.end() } } -struct RowRef<'a>(&'a BTreeMap); +struct RowRef<'a>(&'a BTreeMap, Option<&'a str>); impl Serialize for RowRef<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_map(None)?; - for (key, value) in self.0 { + for (key, value) in self.0.iter().filter(|(key, _)| Some(key.as_str()) != self.1) { out.serialize_entry(key, value)?; } out.end() @@ -608,40 +673,84 @@ mod tests { fn rejects_oversize_before_creating_archive() { let path = tempdir(); let input = data("x".repeat((MAX_ARCHIVE_BYTES as usize) + 1)); - assert!(store(&path, &input).is_err()); + assert!(matches!(store(&path, &input), Err(StoreError::TooBig)), "an oversize archive is told apart by its error"); assert_eq!(managed_count(&path), 0); fs::remove_dir_all(path).unwrap(); } - #[test] - fn large_catalog_history_is_best_effort_and_does_not_abort_import() { - let path = tempdir(); + /// 5,000 photos with 8 KiB of history settings each: about 40 MiB of JSON. + fn large_catalog(history: bool) -> CatalogImport { let mut input = data("catalog.lrcat".into()); input.photos = (0..5_000) - .map(|index| CatalogPhoto { - source_id: index, - uuid: format!("photo-{index}"), - path: format!("/photos/{index}.raw"), - image: BTreeMap::new(), - settings: String::new(), - xmp: String::new(), - keywords: Vec::new(), - history: vec![BTreeMap::from([("text".into(), serde_json::json!(format!("history-{index}-{}", "x".repeat(8 * 1024))))])], - snapshots: Vec::new(), - original: crate::lightroom_catalog::Original::Local, + .map(|index| { + let bulk = format!("history-{index}-{}", "x".repeat(8 * 1024)); + CatalogPhoto { + source_id: index, + uuid: format!("photo-{index}"), + path: format!("/photos/{index}.raw"), + image: BTreeMap::new(), + settings: if history { String::new() } else { bulk.clone() }, + xmp: String::new(), + keywords: Vec::new(), + history: vec![BTreeMap::from([ + ("name".into(), serde_json::json!("Exposure")), + ("text".into(), serde_json::json!(if history { bulk.as_str() } else { "s = {}" })), + ])], + snapshots: vec![BTreeMap::from([("name".into(), serde_json::json!("Before")), ("text".into(), serde_json::json!("s = {}"))])], + original: crate::lightroom_catalog::Original::Local, + } }) .collect(); - assert_eq!(store_best_effort(&path, &input).unwrap(), None); + input + } + + #[test] + fn an_archive_too_big_with_its_history_settings_is_kept_without_them() { + let path = tempdir(); + let kept = store_best_effort(&path, &large_catalog(true)).unwrap(); + let Kept::WithoutSettings(archive) = kept else { panic!("the archive should be kept without settings, not {kept:?}") }; + let decoded = crate::lightroom_fixture::read_archive(&archive); + let photos = decoded["photos"].as_array().unwrap(); + assert_eq!(photos.len(), 5_000, "every photo is still archived"); + assert_eq!(photos[7]["uuid"], serde_json::json!("photo-7")); + assert_eq!(photos[7]["history"], serde_json::json!([{"name": "Exposure"}]), "history steps keep everything but their settings"); + assert_eq!(photos[7]["snapshots"], serde_json::json!([{"name": "Before"}]), "and so do snapshots"); + assert_eq!(fs::read_dir(&path).unwrap().count(), 1, "the first, too big try leaves nothing behind"); + fs::remove_dir_all(path).unwrap(); + } + + #[test] + fn large_catalog_is_best_effort_and_does_not_abort_import() { + let path = tempdir(); + assert_eq!(store_best_effort(&path, &large_catalog(false)).unwrap(), Kept::Nothing, "too big even without history settings"); assert_eq!(managed_count(&path), 0); fs::remove_dir_all(path).unwrap(); } + /// Only the size limit leads to a smaller archive or none: any other failure is reported as such. + #[test] + fn a_write_failure_is_not_taken_for_an_oversize_archive() { + let path = tempdir(); + let file = path.join("not-a-folder"); + fs::write(&file, b"x").unwrap(); + assert!(matches!(store(&file, &rich_data()), Err(StoreError::Failed(_))), "a folder that can't be made"); + let folder = path.join("Interop"); + { + let _full = lightcraft_catalog::safe_file::fail_writes_after(0); + assert!(matches!(store(&folder, &rich_data()), Err(StoreError::Failed(_))), "a full disk while writing"); + assert!(store_best_effort(&folder, &rich_data()).is_err(), "a failure is an error, not a skipped archive"); + } + assert_eq!(fs::read_dir(&folder).unwrap().count(), 0, "a failed write leaves nothing behind"); + fs::remove_dir_all(path).unwrap(); + } + #[test] fn archive_roundtrips_zlib_payload_and_preserves_numeric_arrays() { let path = tempdir(); let archive = store(&path, &rich_data()).unwrap(); let bytes = fs::read(archive).unwrap(); assert!(bytes.starts_with(HEADER)); + assert_eq!(crate::lightroom_fixture::ARCHIVE_HEADER, HEADER, "the fixture reads archives with this module's header"); let json = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&bytes[HEADER.len()..], MAX_ARCHIVE_BYTES as usize).unwrap(); let decoded: Value = serde_json::from_slice(&json).unwrap(); assert_eq!(decoded["version"], serde_json::json!(FORMAT_VERSION)); diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 71721af264..914c70c7c9 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -48,8 +48,31 @@ struct Reader { db: Database, tables: Vec, } +/// Most bytes of history-step or snapshot settings decoded from one table. They are only archived, and an archive +/// holds at most [`crate::lightroom_archive::MAX_ARCHIVE_BYTES`] of JSON, so this keeps all a catalog can archive while +/// a hostile one can't make the reader allocate without bound (each row alone may decode to 16 MiB). +const MAX_DECODED_SETTINGS: usize = crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize; + +/// The column of table `name` that Lightroom Classic 13 and later store as compressed text (see [`decode_compressed`]), +/// and what a warning calls one and several of its rows. +fn compressed_settings(name: &str) -> Option<(&'static str, &'static str, &'static str)> { + match name { + "Adobe_libraryImageDevelopHistoryStep" => Some(("text", "history step", "history steps")), + "Adobe_libraryImageDevelopSnapshot" => Some(("text", "snapshot", "snapshots")), + _ => None, + } +} + impl Reader { - fn table(&self, name: &str, required: bool) -> Result, String> { + fn table(&self, name: &str, required: bool, warnings: &mut Vec) -> Result, String> { + self.table_within(name, required, MAX_DECODED_SETTINGS, warnings) + } + + /// The rows of table `name`. Its compressed settings column ([`compressed_settings`]) is decoded within `budget` + /// bytes for the whole table: each value is charged its declared length before it is inflated, even one that then + /// fails to decode. A value that can't be decoded is left out of its row with a warning naming the image, and + /// those past the budget with one warning for all. Other BLOB columns are always left out. + fn table_within(&self, name: &str, required: bool, budget: usize, warnings: &mut Vec) -> Result, String> { let Some(t) = self.tables.iter().find(|t| t.name == name) else { return if required { Err(format!("unsupported Lightroom catalog: missing {name}")) } else { Ok(Vec::new()) }; }; @@ -58,37 +81,69 @@ impl Reader { if rows.len() > 1_000_000 { return Err(format!("{name}: more than one million records")); } - Ok(rows - .into_iter() - .map(|r| { - columns - .iter() - .cloned() - .zip(r.values.into_iter().map(|v| match v { - SqlValue::Null => Some(Value::Null), - SqlValue::Integer(n) => Some(json!(n)), - SqlValue::Real(n) => Some(json!(n)), - SqlValue::Text(s) => Some(json!(s)), - // Opaque Lightroom payloads never become JSON byte arrays. - SqlValue::Blob(_) => None, - })) - .filter_map(|(column, value)| value.map(|value| (column, value))) - .collect() - }) - .collect()) + let compressed = compressed_settings(name); + let mut left = budget; + let mut over_budget = 0usize; + let mut out = Vec::with_capacity(rows.len()); + for r in rows { + let mut row = Row::new(); + let mut settings = None; + for (column, value) in columns.iter().zip(r.values) { + let value = match value { + SqlValue::Null => Value::Null, + SqlValue::Integer(n) => json!(n), + SqlValue::Real(n) => json!(n), + SqlValue::Text(s) => json!(s), + SqlValue::Blob(bytes) => { + if compressed.is_some_and(|(settings_column, _, _)| settings_column == column) { + settings = Some((column, bytes)); + } + // Other opaque Lightroom payloads never become JSON byte arrays. + continue; + } + }; + row.insert(column.clone(), value); + } + if let (Some((column, bytes)), Some((_, what, _))) = (settings, compressed) { + // charged at its declared length before it is inflated (which never goes past that length), so + // a row that then fails to decode counts too; past the budget, the rest aren't inflated at all + let declared = compressed_len(&bytes); + if declared.is_some_and(|n| over_budget > 0 || n > left) { + over_budget += 1; + } else { + left -= declared.unwrap_or(0); + match decode_compressed(&bytes, "settings") { + Ok(text) => { + row.insert(column.clone(), Value::String(text)); + } + Err(why) => warnings.push(format!( + "image {}: {what} {}: {why}; archived without its settings", + number(&row, "image"), + number(&row, "id_local") + )), + } + } + } + out.push(row); + } + if let (Some((_, one, many)), 1..) = (compressed, over_budget) { + let what = if over_budget == 1 { one } else { many }; + warnings.push(format!("{over_budget} {what} archived without their settings: more than {} MiB of settings in {name}", budget >> 20)); + } + Ok(out) } /// 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 { - let rows = self.table("Adobe_variablesTable", false).ok()?; + let rows = self.table("Adobe_variablesTable", false, &mut Vec::new()).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) -> Result, String> { - match self.table(name, false) { + match self.table(name, false, warnings) { Ok(rows) => Ok(rows), Err(error) => { warnings.push(format!("skipping optional Lightroom table {name}: {error}")); @@ -125,7 +180,7 @@ impl Reader { SqlValue::Integer(n) => Some(json!(n)), SqlValue::Real(n) => Some(json!(n)), SqlValue::Text(s) => Some(json!(s)), - SqlValue::Blob(bytes) if column == "xmp" => match decode_xmp_bytes(&bytes) { + SqlValue::Blob(bytes) if column == "xmp" => match decode_compressed(&bytes, "XMP") { Ok(packet) => Some(Value::String(packet)), Err(error) => { warnings.push(format!("image {image}: {error}")); @@ -352,17 +407,27 @@ fn xmp(v: Option<&Value>) -> Result { } } -fn decode_xmp_bytes(bytes: &[u8]) -> Result { - let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes).ok_or("truncated XMP header")?; - if size > 16 << 20 { - return Err("XMP packet exceeds 16 MiB".into()); +/// The decoded length [`decode_compressed`] reads from `bytes`' header, when it has one of at most 16 MiB. +fn compressed_len(bytes: &[u8]) -> Option { + let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes)?; + usize::try_from(size).ok().filter(|size| *size <= 16 << 20) +} + +/// Lightroom's compressed text (`Adobe_AdditionalMetadata.xmp`, and history-step and snapshot settings since Lightroom +/// Classic 13): the decoded length as 4 big-endian bytes, then a zlib stream, at most 16 MiB decoded. Errors name it +/// `what`. +fn decode_compressed(bytes: &[u8], what: &str) -> Result { + if bytes.len() < 4 { + return Err(format!("truncated {what} header")); } - let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or("truncated XMP")?, 16 << 20) - .map_err(|_| "invalid compressed XMP")?; - if decoded.len() != size as usize { - return Err("XMP packet length mismatch".into()); + let size = compressed_len(bytes).ok_or_else(|| format!("{what} longer than 16 MiB"))?; + // inflated no further than its declared length: a stream that goes on is invalid, at no more cost than a valid one + let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or_else(|| format!("truncated {what}"))?, size) + .map_err(|_| format!("invalid compressed {what}"))?; + if decoded.len() != size { + return Err(format!("{what} length mismatch")); } - String::from_utf8(decoded).map_err(|e| e.to_string()) + String::from_utf8(decoded).map_err(|e| format!("{what} not UTF-8: {e}")) } // SQLite file format §4: validate the live checksum chain in constant space, then overlay @@ -482,9 +547,9 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d } let reader = Reader { tables: db.live_tables()?, db }; let mut warnings = Vec::new(); - let table = |name: &str, required: bool| -> Result, String> { + let table = |name: &str, required: bool, warnings: &mut Vec| -> Result, String> { ensure_read_active(cancel)?; - let rows = reader.table(name, required)?; + let rows = reader.table(name, required, warnings)?; done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; @@ -494,9 +559,9 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; - let roots: HashMap<_, _> = table("AgLibraryRootFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let folders: HashMap<_, _> = table("AgLibraryFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let files: HashMap<_, _> = table("AgLibraryFile", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let roots: HashMap<_, _> = table("AgLibraryRootFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let folders: HashMap<_, _> = table("AgLibraryFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let files: HashMap<_, _> = table("AgLibraryFile", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); let develops: HashMap<_, _> = optional_table("Adobe_imageDevelopSettings", &mut warnings)? .into_iter() .map(|r| (number(&r, "image"), text(&r, "text").to_string())) @@ -580,7 +645,7 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d // these behind and ignores them); they and their virtual copies are skipped and reported // instead of failing the import let mut orphans = HashSet::new(); - for image in table("Adobe_images", true)? { + for image in table("Adobe_images", true, &mut out.warnings)? { ensure_read_active(cancel)?; let id = number(&image, "id_local"); let record = files.get(&number(&image, "rootFile")).ok_or(SkipReason::MissingFile).and_then(|file| { @@ -947,7 +1012,7 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) -> let archive_dir = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop")); let index_path = archive_dir.as_ref().map(|p| p.join("lightroom-index.json")); let mut index = load_index(index_path.as_deref())?; - let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(error)).transpose()?; + let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(|e| error(e.to_string()))).transpose()?; let undo0 = s.undo.len(); let existing: HashMap<_, _> = s.catalog.photos().filter(|p| p.copy_of.is_none()).filter_map(|p| source_path(p).map(|path| (key(path), p.id))).collect(); diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index fefc9577ae..3503960858 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -2012,3 +2012,62 @@ fn oversized_optional_table_warns_and_is_skipped() { assert!(rows.is_empty()); assert!(warnings.iter().any(|warning| warning.contains("optional_history"))); } + +/// A catalog whose settings decode to more than the budget keeps every row, archives the settings that fit, and +/// says once how many it left out, instead of allocating whatever its BLOBs inflate to. +#[test] +fn settings_past_the_decode_budget_are_left_out_with_one_warning() { + use crate::lightroom_fixture::{self as fixture, Field, Table}; + let dir = fixture::dir("history-budget"); + let catalog = dir.join("test.lrcat"); + let big = "x".repeat(512 << 10); + let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(fixture::compressed(&big)))).collect(); + fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]); + let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap(); + let reader = Reader { tables: db.live_tables().unwrap(), db }; + let mut warnings = Vec::new(); + let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap(); + assert_eq!(rows.len(), 4, "every step is still read"); + assert_eq!(rows.iter().filter(|r| r.contains_key("text")).count(), 2, "the two steps within 1 MiB keep their settings"); + assert_eq!(warnings, ["2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep"]); + let _ = std::fs::remove_dir_all(dir); +} + +/// A stream that inflates past the length its header declares is stopped there, not inflated up to 16 MiB first. +#[test] +fn a_stream_longer_than_its_declared_length_is_stopped_at_that_length() { + let mut bytes = 10u32.to_be_bytes().to_vec(); + bytes.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6)); + assert_eq!(decode_compressed(&bytes, "settings"), Err("invalid compressed settings".to_string())); + let mut exact = 1024u32.to_be_bytes().to_vec(); + exact.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6)); + assert_eq!(decode_compressed(&exact, "settings").map(|text| text.len()), Ok(1024), "exactly its length decodes"); +} + +/// Settings that fail to decode still cost their declared length, so a catalog of damaged rows can't make the +/// reader inflate without bound: past the budget, the rest are left out without being inflated. +#[test] +fn settings_that_fail_to_decode_still_count_against_the_budget() { + use crate::lightroom_fixture::{self as fixture, Field, Table}; + let dir = fixture::dir("history-budget-bad"); + let catalog = dir.join("test.lrcat"); + let mut damaged = (512u32 << 10).to_be_bytes().to_vec(); + damaged.extend([1, 2, 3]); + let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(damaged.clone()))).collect(); + fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]); + let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap(); + let reader = Reader { tables: db.live_tables().unwrap(), db }; + let mut warnings = Vec::new(); + let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap(); + assert_eq!(rows.len(), 4, "every step is still read"); + assert_eq!( + warnings, + [ + "image 1: history step 1: invalid compressed settings; archived without its settings", + "image 1: history step 2: invalid compressed settings; archived without its settings", + "2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep", + ], + "the two damaged steps within 1 MiB are tried; the other two aren't" + ); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/lightroom_fixture.rs b/crates/engine/src/lightroom_fixture.rs new file mode 100644 index 0000000000..ce8325a91e --- /dev/null +++ b/crates/engine/src/lightroom_fixture.rs @@ -0,0 +1,259 @@ +//! Synthetic Lightroom catalogs for tests: a small SQLite file written page by page, so the catalog reader is tested +//! on the bytes it reads in the field (text and BLOB cells, Lightroom's compressed encoding) with no SQLite library. +//! Each table is one leaf page; rows must fit in it without overflow pages. + +use std::path::{Path, PathBuf}; + +const PAGE_SIZE: usize = 4096; +/// The largest record a 4096-byte table leaf holds without an overflow page (SQLite file format §1.6: U - 35). +const MAX_LOCAL: usize = PAGE_SIZE - 35; + +#[derive(Clone, Debug)] +pub(crate) enum Field { + Null, + Integer(i64), + Real(f64), + Text(String), + Blob(Vec), +} + +pub(crate) fn text(s: &str) -> Field { + Field::Text(s.into()) +} + +pub(crate) struct Table { + pub name: &'static str, + /// The column list of its `CREATE TABLE`, as Lightroom writes it. + pub columns: &'static str, + pub rows: Vec>, +} + +/// Lightroom Classic's compressed text (as in `Adobe_AdditionalMetadata.xmp`, and history steps and snapshots since +/// Lightroom Classic 13): the decoded length as 4 big-endian bytes, then the zlib stream. +pub(crate) fn compressed(text: &str) -> Vec { + compressed_bytes(text.as_bytes()) +} + +/// [`compressed`] for any bytes, including ones that aren't UTF-8. +pub(crate) fn compressed_bytes(bytes: &[u8]) -> Vec { + let mut out = u32::try_from(bytes.len()).unwrap().to_be_bytes().to_vec(); + out.extend(miniz_oxide::deflate::compress_to_vec_zlib(bytes, 6)); + out +} + +pub(crate) const HISTORY_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, dateCreated, digest, \ + hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, name, relValueString, text, valueString"; +pub(crate) const SNAPSHOT_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, digest, \ + hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, locked, name, snapshotID, text"; + +/// A history step row for image `image` (columns as in [`HISTORY_COLUMNS`]); `settings` is a text or BLOB field. +pub(crate) fn history_step(id: i64, image: i64, date: f64, name: &str, settings: Field) -> Vec { + vec![ + Field::Integer(id), + text(&format!("history-{id}")), + Field::Real(date), + Field::Null, + Field::Integer(0), + Field::Integer(1), + Field::Integer(image), + text(name), + Field::Null, + settings, + Field::Null, + ] +} + +/// A snapshot row for image `image` (columns as in [`SNAPSHOT_COLUMNS`]); `settings` is a text or BLOB field. +pub(crate) fn snapshot(id: i64, image: i64, name: &str, settings: Field) -> Vec { + vec![ + Field::Integer(id), + text(&format!("snapshot-{id}")), + Field::Null, + Field::Integer(0), + Field::Integer(1), + Field::Integer(image), + Field::Null, + text(name), + Field::Null, + settings, + ] +} + +/// The tables of a catalog with one photo, image 1 (`/Photos/test.ARW`, not created), with the develop +/// settings `settings`. Add history, snapshot or other tables and pass them all to [`write`]. +pub(crate) fn one_photo(originals: &Path, settings: &str) -> Vec { + let mut root = originals.to_string_lossy().into_owned(); + if !root.ends_with('/') { + root.push('/'); + } + vec![ + Table { + name: "AgLibraryRootFolder", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, absolutePath UNIQUE NOT NULL DEFAULT '', name NOT NULL DEFAULT '', relativePathFromCatalog", + rows: vec![vec![Field::Integer(1), text("root-1"), Field::Text(root), text("originals"), Field::Null]], + }, + Table { + name: "AgLibraryFolder", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, pathFromRoot NOT NULL DEFAULT '', rootFolder INTEGER NOT NULL DEFAULT 0", + rows: vec![vec![Field::Integer(1), text("folder-1"), text("Photos/"), Field::Integer(1)]], + }, + Table { + name: "AgLibraryFile", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, baseName NOT NULL DEFAULT '', extension NOT NULL DEFAULT '', folder INTEGER NOT NULL DEFAULT 0, idx_filename NOT NULL DEFAULT ''", + rows: vec![vec![Field::Integer(1), text("file-1"), text("test"), text("ARW"), Field::Integer(1), text("test.ARW")]], + }, + Table { + name: "Adobe_images", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, fileFormat NOT NULL DEFAULT 'unset', fileHeight, fileWidth, masterImage INTEGER, pick NOT NULL DEFAULT 0, rating, rootFile INTEGER NOT NULL DEFAULT 0", + rows: vec![vec![ + Field::Integer(1), + text("image-1"), + text("RAW"), + Field::Integer(10), + Field::Integer(20), + Field::Null, + Field::Integer(0), + Field::Null, + Field::Integer(1), + ]], + }, + Table { + name: "Adobe_imageDevelopSettings", + columns: "id_local INTEGER PRIMARY KEY, image INTEGER, text", + rows: vec![vec![Field::Integer(1), Field::Integer(1), text(settings)]], + }, + ] +} + +/// The format header an import archive starts with (`lightroom_archive`'s), before its zlib-compressed JSON. +pub(crate) const ARCHIVE_HEADER: &[u8] = b"LC-LRARCH\0\x01Z"; + +/// The JSON the import archive at `path` holds, for tests that check what an import kept. The JSON itself is capped +/// at `MAX_ARCHIVE_BYTES` too, so that is the most it can inflate to. +pub(crate) fn read_archive(path: &Path) -> serde_json::Value { + let bytes = std::fs::read(path).unwrap(); + let json = bytes.strip_prefix(ARCHIVE_HEADER).unwrap_or_else(|| panic!("{} is not an import archive", path.display())); + serde_json::from_slice( + &miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(json, crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize).unwrap(), + ) + .unwrap() +} + +/// A new, empty folder for one test's catalog. +pub(crate) fn dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lightcraft-lrcat-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Write `tables` as a SQLite database at `path`: page 1 holds the schema, table `i` page `i + 2`. +pub(crate) fn write(path: &Path, tables: &[Table]) { + let mut schema = Vec::new(); + let mut pages = Vec::new(); + for (i, table) in tables.iter().enumerate() { + let root = i64::try_from(i + 2).unwrap(); + schema.push(vec![ + text("table"), + text(table.name), + text(table.name), + Field::Integer(root), + Field::Text(format!("CREATE TABLE {}({})", table.name, table.columns)), + ]); + pages.push(leaf(0, &table.rows, table.name)); + } + let mut first = leaf(100, &schema, "sqlite_master"); + first[..16].copy_from_slice(b"SQLite format 3\0"); + first[16..18].copy_from_slice(&u16::try_from(PAGE_SIZE).unwrap().to_be_bytes()); + first[18] = 1; // legacy journal mode: no WAL file is read unless it exists + first[19] = 1; + first[21] = 64; + first[22] = 32; + first[23] = 32; + first[24..28].copy_from_slice(&1u32.to_be_bytes()); + first[28..32].copy_from_slice(&u32::try_from(pages.len() + 1).unwrap().to_be_bytes()); + first[40..44].copy_from_slice(&1u32.to_be_bytes()); + first[44..48].copy_from_slice(&4u32.to_be_bytes()); + first[56..60].copy_from_slice(&1u32.to_be_bytes()); // UTF-8 + first[92..96].copy_from_slice(&1u32.to_be_bytes()); + first[96..100].copy_from_slice(&3_045_000u32.to_be_bytes()); + let mut bytes = first; + for page in pages { + bytes.extend(page); + } + std::fs::write(path, bytes).unwrap(); +} + +fn leaf(base: usize, rows: &[Vec], table: &str) -> Vec { + let mut page = vec![0u8; PAGE_SIZE]; + page[base] = 0x0d; + page[base + 3..base + 5].copy_from_slice(&u16::try_from(rows.len()).unwrap().to_be_bytes()); + let mut end = PAGE_SIZE; + for (i, values) in rows.iter().enumerate() { + let payload = record(values); + assert!(payload.len() <= MAX_LOCAL, "{table} row {i}: {} bytes needs an overflow page, which the fixture doesn't write", payload.len()); + let rowid = match values.first() { + Some(Field::Integer(id)) => u64::try_from(*id).unwrap(), + _ => u64::try_from(i + 1).unwrap(), + }; + let mut cell = varint(u64::try_from(payload.len()).unwrap()); + cell.extend(varint(rowid)); + cell.extend(payload); + let pointers_end = base + 8 + (i + 1) * 2; + end = end.checked_sub(cell.len()).filter(|e| *e >= pointers_end).unwrap_or_else(|| panic!("{table}: rows don't fit in one page")); + page[end..end + cell.len()].copy_from_slice(&cell); + page[pointers_end - 2..pointers_end].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes()); + } + page[base + 5..base + 7].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes()); + page +} + +/// A record (SQLite file format §2.1). An `INTEGER PRIMARY KEY` column's value is the rowid, stored as NULL. +fn record(values: &[Field]) -> Vec { + let mut serials = Vec::new(); + let mut body = Vec::new(); + for (i, value) in values.iter().enumerate() { + let serial = match value { + Field::Integer(_) if i == 0 => 0, + Field::Null => 0, + Field::Integer(n) => { + body.extend(n.to_be_bytes()); + 6 + } + Field::Real(n) => { + body.extend(n.to_be_bytes()); + 7 + } + Field::Text(s) => { + body.extend(s.as_bytes()); + 13 + 2 * u64::try_from(s.len()).unwrap() + } + Field::Blob(b) => { + body.extend(b); + 12 + 2 * u64::try_from(b.len()).unwrap() + } + }; + serials.extend(varint(serial)); + } + // the header length counts its own varint + let mut header_len = serials.len() + 1; + if varint(u64::try_from(header_len).unwrap()).len() > 1 { + header_len += 1; + } + let mut out = varint(u64::try_from(header_len).unwrap()); + out.extend(serials); + out.extend(body); + out +} + +/// SQLite's big-endian varint (values below 2^56, which is all a fixture needs). +fn varint(mut value: u64) -> Vec { + let mut out = vec![(value & 0x7f) as u8]; + value >>= 7; + while value != 0 { + out.push((value & 0x7f) as u8 | 0x80); + value >>= 7; + } + out.reverse(); + out +} diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 7a039fe0f1..695398bcc6 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -31,11 +31,20 @@ fn cancelled() -> crate::EngineError { } fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result> { - let archive_path = archive_dir.map(|dir| crate::lightroom_archive::store_best_effort(dir, data).map_err(error)).transpose()?.flatten(); - if archive_dir.is_some() && archive_path.is_none() { - data.warnings.push("Lightroom source archive exceeded 32 MiB; archive skipped".into()); - } - Ok(archive_path) + use crate::lightroom_archive::{Kept, MAX_ARCHIVE_BYTES}; + let Some(dir) = archive_dir else { return Ok(None) }; + let limit = MAX_ARCHIVE_BYTES >> 20; + Ok(match crate::lightroom_archive::store_best_effort(dir, data).map_err(error)? { + Kept::All(path) => Some(path), + Kept::WithoutSettings(path) => { + data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archived without history-step and snapshot settings")); + Some(path) + } + Kept::Nothing => { + data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archive skipped")); + None + } + }) } /// Memory identity of the library which owns a prepared completion. @@ -521,59 +530,67 @@ mod tests { assert_eq!(session.undo.len(), 3); } + /// 5,000 photos with 8 KiB each of history settings (`in_history`) or develop settings: about 40 MiB of JSON. An + /// archive too big with its history settings is kept without them; one too big even then is skipped. Either + /// way the import goes on and says so. #[test] - fn oversized_history_archive_keeps_prepared_import_successful_with_warning() { - let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{}", std::process::id())); - let mut data = empty_data(); - data.photos = (0..5_000) - .map(|source_id| { - let image = std::collections::BTreeMap::from([ - ("id_local".into(), serde_json::json!(source_id)), - ("fileFormat".into(), serde_json::json!("JPG")), - ("fileWidth".into(), serde_json::json!(1)), - ("fileHeight".into(), serde_json::json!(1)), - ]); - lightroom_catalog::CatalogPhoto { - source_id, - uuid: format!("scale-{source_id}"), - path: format!("/missing/scale-{source_id}.jpg"), - image, - settings: String::new(), - xmp: String::new(), - keywords: Vec::new(), - history: vec![std::collections::BTreeMap::from([( - "text".into(), - serde_json::json!(format!("history-{source_id}-{}", "x".repeat(8 * 1024))), - )])], - snapshots: Vec::new(), - original: lightroom_catalog::Original::Local, - } - }) - .collect(); - let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap(); - assert!(archive_path.is_none()); - let mut session = crate::Session::new(); - let token = LightroomLibraryToken::capture(&session); - let prepared = PreparedLightroom { - data, - normal: Prepared::default(), - index: ImportIndex::default(), - archive_path, - token, - missing_sources: HashSet::new(), - update_existing: false, - now: "2026-01-01T00:00:00".into(), - cancelled: false, - }; - let completion = commit_prepared(&mut session, prepared).unwrap(); - assert_eq!(completion.report["photos"], 5_000); - assert!( - completion.report["warnings"] - .as_array() - .is_some_and(|warnings| warnings.iter().any(|warning| warning == "Lightroom source archive exceeded 32 MiB; archive skipped")) - ); - assert_eq!(session.catalog.len(), 5_000); - std::fs::remove_dir_all(archive_dir).unwrap(); + fn oversized_archive_keeps_prepared_import_successful_with_warning() { + for (in_history, warning, archived) in [ + (true, "Lightroom source archive exceeded 32 MiB; archived without history-step and snapshot settings", true), + (false, "Lightroom source archive exceeded 32 MiB; archive skipped", false), + ] { + let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{in_history}-{}", std::process::id())); + let mut data = empty_data(); + data.photos = (0..5_000) + .map(|source_id| { + let image = std::collections::BTreeMap::from([ + ("id_local".into(), serde_json::json!(source_id)), + ("fileFormat".into(), serde_json::json!("JPG")), + ("fileWidth".into(), serde_json::json!(1)), + ("fileHeight".into(), serde_json::json!(1)), + ]); + let bulk = format!("history-{source_id}-{}", "x".repeat(8 * 1024)); + lightroom_catalog::CatalogPhoto { + source_id, + uuid: format!("scale-{source_id}"), + path: format!("/missing/scale-{source_id}.jpg"), + image, + settings: if in_history { String::new() } else { bulk.clone() }, + xmp: String::new(), + keywords: Vec::new(), + history: vec![std::collections::BTreeMap::from([( + "text".into(), + serde_json::json!(if in_history { bulk } else { String::new() }), + )])], + snapshots: Vec::new(), + original: lightroom_catalog::Original::Local, + } + }) + .collect(); + let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap(); + assert_eq!(archive_path.is_some(), archived, "{warning}"); + let mut session = crate::Session::new(); + let token = LightroomLibraryToken::capture(&session); + let prepared = PreparedLightroom { + data, + normal: Prepared::default(), + index: ImportIndex::default(), + archive_path, + token, + missing_sources: HashSet::new(), + update_existing: false, + now: "2026-01-01T00:00:00".into(), + cancelled: false, + }; + let completion = commit_prepared(&mut session, prepared).unwrap(); + assert_eq!(completion.report["photos"], 5_000); + assert!( + completion.report["warnings"].as_array().is_some_and(|warnings| warnings.iter().any(|w| w == warning)), + "the report should say: {warning}" + ); + assert_eq!(session.catalog.len(), 5_000); + std::fs::remove_dir_all(archive_dir).unwrap(); + } } #[test] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a491fe1184..9c84b179da 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -38,6 +38,7 @@ mod lens_refresh; mod libops; mod library; mod lightroom_folder; +mod lightroom_history; mod mask_effects; mod mask_geometry; mod merge; diff --git a/crates/engine/src/tests/lightroom_history.rs b/crates/engine/src/tests/lightroom_history.rs new file mode 100644 index 0000000000..d1fa044186 --- /dev/null +++ b/crates/engine/src/tests/lightroom_history.rs @@ -0,0 +1,136 @@ +//! Lightroom history steps and snapshots read from a catalog file into the import archive: stored as text +//! (Lightroom 6) or as compressed BLOBs (history steps since Lightroom Classic 13, which also converts an upgraded +//! catalog's steps). + +use crate::lightroom_fixture::{self as fixture, Field, Table}; +use serde_json::{Value, json}; + +const CURRENT: &str = "s = { Exposure2012 = 1.25, Contrast2012 = 17 }"; +const FIRST: &str = "s = { Exposure2012 = 1.25 }"; + +/// Write a one-photo catalog with `extra` tables, read it, archive it, and return the archive's JSON. +fn archive(tag: &str, extra: Vec
) -> Value { + let dir = fixture::dir(tag); + let mut tables = fixture::one_photo(&dir.join("originals"), CURRENT); + tables.extend(extra); + let catalog = dir.join("test.lrcat"); + fixture::write(&catalog, &tables); + let data = crate::lightroom_catalog::read(&catalog).unwrap(); + let stored = crate::lightroom_archive::store(&dir.join("Interop"), &data).unwrap(); + let archived = fixture::read_archive(&stored); + let _ = std::fs::remove_dir_all(dir); + archived +} + +fn steps(settings: impl Fn(&str) -> Field) -> Table { + Table { + name: "Adobe_libraryImageDevelopHistoryStep", + columns: fixture::HISTORY_COLUMNS, + rows: vec![fixture::history_step(3, 1, 20.0, "Contrast", settings(CURRENT)), fixture::history_step(2, 1, 10.0, "Exposure", settings(FIRST))], + } +} + +/// `(name, dateCreated, text)` of each archived row, in the order the archive holds them. +fn rows(archive: &Value, key: &str) -> Vec<(Value, Value, Value)> { + let rows = archive["photos"][0][key].as_array().unwrap_or_else(|| panic!("the archive should list {key}: {archive}")); + rows.iter().map(|r| (r["name"].clone(), r["dateCreated"].clone(), r["text"].clone())).collect() +} + +#[test] +fn compressed_history_steps_keep_their_settings_in_the_archive() { + let archived = archive("history-blob", vec![steps(|t| Field::Blob(fixture::compressed(t)))]); + let mut steps = rows(&archived, "history"); + steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap()); + assert_eq!( + steps, + [(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))], + "each compressed step should be archived with its decoded settings: {archived}" + ); + assert_eq!(archived["warnings"], json!([]), "no step should be reported unreadable"); +} + +#[test] +fn text_history_steps_are_archived_as_before() { + let archived = archive("history-text", vec![steps(fixture::text)]); + let mut steps = rows(&archived, "history"); + steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap()); + assert_eq!(steps, [(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))], "{archived}"); + assert_eq!(archived["warnings"], json!([])); +} + +#[test] +fn compressed_and_text_snapshots_keep_their_settings_in_the_archive() { + let snapshots = Table { + name: "Adobe_libraryImageDevelopSnapshot", + columns: fixture::SNAPSHOT_COLUMNS, + rows: vec![ + fixture::snapshot(5, 1, "Bright", Field::Blob(fixture::compressed("s = { Exposure2012 = 2 }"))), + fixture::snapshot(6, 1, "Plain", fixture::text("s = { Contrast2012 = 30 }")), + ], + }; + let archived = archive("snapshot-blob", vec![snapshots]); + let mut kept: Vec<_> = rows(&archived, "snapshots").into_iter().map(|(name, _, text)| (name, text)).collect(); + kept.sort_by_key(|(name, _)| name.to_string()); + assert_eq!( + kept, + [(json!("Bright"), json!("s = { Exposure2012 = 2 }")), (json!("Plain"), json!("s = { Contrast2012 = 30 }"))], + "compressed and text snapshots should both be archived with their settings: {archived}" + ); + assert_eq!(archived["warnings"], json!([])); +} + +/// A hostile or damaged catalog: each bad BLOB costs only its own row's settings, with a warning naming the image. +#[test] +fn a_malformed_settings_blob_is_archived_without_its_settings_and_warned_about() { + let mut mismatch = fixture::compressed(FIRST); + mismatch[3] = mismatch[3].wrapping_add(1); + let mut over_cap = fixture::compressed(FIRST); + over_cap[..4].copy_from_slice(&((16u32 << 20) + 1).to_be_bytes()); + let bad = [ + ("Short", vec![0, 0]), + ("Not zlib", vec![0, 0, 0, 5, 1, 2, 3, 4, 5]), + ("Wrong length", mismatch), + ("Too big", over_cap), + ("Not UTF-8", fixture::compressed_bytes(&[0xff, 0xfe])), + ]; + let mut history = steps(|t| Field::Blob(fixture::compressed(t))); + for (i, (name, bytes)) in bad.iter().enumerate() { + let id = 10 + i64::try_from(i).unwrap(); + history.rows.push(fixture::history_step(id, 1, 30.0 + id as f64, name, Field::Blob(bytes.clone()))); + } + let snapshots = Table { + name: "Adobe_libraryImageDevelopSnapshot", + columns: fixture::SNAPSHOT_COLUMNS, + rows: vec![fixture::snapshot(5, 1, "Broken", Field::Blob(vec![0, 0, 0, 9, 9]))], + }; + let archived = archive("history-bad", vec![history, snapshots]); + assert_eq!(archived["photos"].as_array().map(Vec::len), Some(1), "the photo is still read: {archived}"); + let steps = rows(&archived, "history"); + assert_eq!(steps.len(), 7, "every step is still archived: {archived}"); + for (name, _, text) in &steps { + let good = name == "Exposure" || name == "Contrast"; + assert_eq!(text.is_string(), good, "{name}: only the good steps keep settings: {archived}"); + } + assert_eq!(rows(&archived, "snapshots")[0].2, Value::Null, "the broken snapshot is archived without settings"); + let warnings: Vec<_> = archived["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(warnings.len(), bad.len() + 1, "one warning per bad step and snapshot: {warnings:?}"); + assert!(warnings.iter().all(|w| w.starts_with("image 1: ")), "each warning names the image: {warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("history step 10")), "a warning names the step: {warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("snapshot 5")), "a warning names the snapshot: {warnings:?}"); +} + +/// Only the settings column is decoded; any other BLOB (even one in Lightroom's compressed encoding) stays out of +/// the archive, as before. +#[test] +fn other_blob_columns_never_reach_the_archive() { + let mut history = steps(|t| Field::Blob(fixture::compressed(t))); + for row in &mut history.rows { + row[3] = Field::Blob(vec![1, 2, 3, 4]); // digest + row[10] = Field::Blob(fixture::compressed("s = { Exposure2012 = 3 }")); // valueString + } + let archived = archive("history-other-blobs", vec![history]); + for step in archived["photos"][0]["history"].as_array().unwrap() { + assert!(step.get("digest").is_none() && step.get("valueString").is_none(), "other BLOB columns leaked: {step}"); + assert!(step["text"].is_string(), "the settings are still decoded: {step}"); + } +} diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index d2316d17bc..87d17c999e 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -86,8 +86,11 @@ Before changing records, the importer attempts to save source image records, dec verbatim develop settings, history, snapshots and collection content to compressed `Interop/lightroom-import-N.lca` recovery archives in the LightCraft library. Archiving is best-effort: a size limit or write failure produces a warning and does not prevent photo import. -Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. Each archive is -capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total +Unchanged source data reuses its existing archive. History-step and snapshot settings that Lightroom +Classic 13 and later store compressed are decoded into it; one that can't be decoded, or past 32 MiB of +them in one table, is archived without its settings, with a warning. Other opaque SQL BLOBs are skipped. Each archive is +capped at 32 MiB (uncompressed and on disk); one past that with its history-step and snapshot settings is +saved without them, with a warning, and skipped only when still too big. At most eight archives and 128 MiB total are retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. `Interop/lightroom-index.json` records imported identities. Source catalogs and originals are never overwritten. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 432fd3d81d..96f639a6f2 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -706,7 +706,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:`) or “This photo can't be opened” (`compare:renderFailed:`) 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). Lightroom catalog backups (`Backups//.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-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, except the compressed history-step and snapshot settings of Lightroom Classic 13 and later, which are decoded into the archive (an archive too big with them is kept without them). 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//.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/catalog/src/opened_folder.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); a library is written only to the folder it was opened from: the folder's device and inode number are recorded when it opens and checked before every write of the catalog, its log, the settings, the lock note and the thumbnail cache (a folder that holds exactly the lock note this session wrote (a note holds a value no other lock's note has) counts as the same folder, and so does one with the same inode number and the same creation time under another device number (a drive or share mounted again), or on the same device when no two creation times that are both known differ (an inode number is given again to a folder made later); so saving goes on after a drive or share is mounted again, also on file systems that number their folders anew at every mount; a copy of the folder made while the library was open holds that note and counts too, and the log in it is appended to only while it is the log this session wrote, else a snapshot replaces it), so a share mounted over the library's folder, or a folder put in its place, is refused with the reason (nothing is written, the changes are kept in memory as unsaved, and saving goes on when the folder is back, a preference that could not be saved being written with the next one; issue #3240; on Windows only that a folder is still there is checked; on every system `Originals/` (copies, and what is done to the photos in it), Smart Previews, `focus-scanned.bin`, `Interop/` and the other files beside the catalog are still written by path); a Move import removes its originals only once the catalog log is on disk; dropping the lock removes only the owner note it wrote itself, with the bytes it wrote, from the folder it locked or one that holds that note | | 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 | @@ -848,6 +848,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | patch | LR-META-LOCATION: Info GPS text validates the complete decimal/DMS expression, axis markers and component ranges before metadata changes; readiness and feature counts unchanged | +| 2026-10-24 | patch | LRC-LIB-CATALOG-IMPORT: the recovery archive keeps the compressed history-step and snapshot settings of Lightroom Classic 13 and later; an archive too big with them is kept without them; status and counts unchanged | | 2026-10-24 | patch | LR-LIB-RATING, LR-LIB-DELETE: a slider drag still open when a rating, flag or label takes the photo out of the view, or when the photo is deleted, ends as its own undo step before the selection moves on, as moving to the next photo does; LR-BEHAV-LOCALIZE lists all 18 languages; status unchanged | | 2026-10-24 | patch | Integration batch 43: Integrated main 98702b5c, preserving the new fail-closed GPS metadata check for Original export. Watermark geometry/orientation and HDR JPEG size-limit fixes remain in their shared helpers; no feature-count changes. | | 2026-10-23 | minor | LR-FILT-FLAG, LRC-LIB-FILTERBAR: the filter bar's flag toggles combine (any of them, `library.filter` `flags`), issue #2588; status and counts unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index 94a0ea09d2..3bff874712 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -601,6 +601,14 @@ Rating is ≥ 3. Move with the arrow keys". - OK saves the rules in the order shown, in one undo step like any other change to the rules. +### Lightroom catalog import keeps the settings of each history step +- Importing a Lightroom Classic catalog saves its history steps and snapshots in a recovery archive in the library. + For catalogs from Lightroom Classic 13 and later, the archive kept each step's name and date but not its + settings, because those versions store them compressed. They are now decoded and kept. A step whose settings + can't be read is kept without them, with a warning, and the import goes on. +- When an archive with the history settings would be too big (over 32 MiB), it is now saved without them, with a + warning, instead of not at all. + ## 2026-10-23 ### AI Denoise works out of the box